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/tests/class_tests/openms/source/Matrix_test.cpp
.cpp
6,276
278
// 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> /////////////////////////// // Includes go here.... #include <OpenMS/DATASTRUCTURES/Matrix.h> #include <sstream> /////////////////////////// START_TEST(Matrix, "$Id$"); ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; Matrix<int>* ptr = nullptr; Matrix<int>* nullPointer = nullptr; START_SECTION((Matrix())) { ptr = new Matrix<int>; TEST_NOT_EQUAL(ptr, nullPointer); Matrix<int> mi1; TEST_EQUAL(mi1.size(), 0); TEST_EQUAL(mi1.cols(), 0); TEST_EQUAL(mi1.rows(), 0); // Test iteration over empty matrix (should not execute loop body) for (auto & i : mi1) { TEST_EQUAL(i, i - 1); // this should not be executed on empty matrix } for (const auto & i : mi1) { TEST_EQUAL(i, i - 1); // this should not be executed on empty matrix } STATUS("mi1:\n"<< mi1); } END_SECTION; START_SECTION((~Matrix())) { delete ptr; } END_SECTION; Matrix<int> mi; START_SECTION((void resize(size_type i, size_type j))) { mi.resize(2,2); mi.fill(3); mi.resize(2,3); mi.fill(7); STATUS("mi1:\n"<< mi); TEST_EQUAL(mi(0,0),7); TEST_EQUAL(mi(0,1),7); TEST_EQUAL(mi(0,2),7); TEST_EQUAL(mi(1,0),7); TEST_EQUAL(mi(1,1),7); TEST_EQUAL(mi(1,2),7); } END_SECTION START_SECTION((Matrix(const Matrix & source))) { Matrix<int> mi2(mi); STATUS("mi2:\n"<< mi2); TEST_EQUAL(mi2.cols(),3); TEST_EQUAL(mi2.rows(),2); TEST_EQUAL(mi2(0,0),7); TEST_EQUAL(mi2(0,1),7); TEST_EQUAL(mi2(0,2),7); TEST_EQUAL(mi2(1,0),7); TEST_EQUAL(mi2(1,1),7); TEST_EQUAL(mi2(1,2),7); // test iterators and confirm column first order // Column-major storage: iterating should go (0,0), (1,0), (0,1), (1,1), (0,2), (1,2) Size row = 0, col = 0; for (auto it = mi2.begin(); it != mi2.end(); ++it) { TEST_EQUAL(*it, mi.getValue(row, col)); ++row; if (row == mi2.rows()) { row = 0; ++col; } } row = 0; col = 0; for (auto it = mi2.cbegin(); it != mi2.cend(); ++it) { TEST_EQUAL(*it, mi.getValue(row, col)); ++row; if (row == mi2.rows()) { row = 0; ++col; } } } END_SECTION START_SECTION((Matrix& operator = (const Matrix & rhs))) { Matrix<int> mi3; STATUS("mi3:\n"<<mi3); mi3=mi; STATUS("mi3:\n"<<mi3); TEST_EQUAL(mi3.cols(),3); TEST_EQUAL(mi3.rows(),2); TEST_EQUAL(mi3(0,0),7); TEST_EQUAL(mi3(0,1),7); TEST_EQUAL(mi3(0,2),7); TEST_EQUAL(mi3(1,0),7); TEST_EQUAL(mi3(1,1),7); TEST_EQUAL(mi3(1,2),7); } END_SECTION mi(1,1)=17; START_SECTION((const_reference operator()(size_type const i, size_type const j) const)) { Matrix<int> const & micr = mi; STATUS("micr:\n"<<micr); TEST_EQUAL(micr(1,1),17); } END_SECTION START_SECTION((reference operator()(size_type const i, size_type const j))) { STATUS(mi(1,2)); mi(1,2)=33; STATUS(mi(1,2)); Matrix<int> const & micr = mi; TEST_EQUAL(micr(1,2), 33); } END_SECTION START_SECTION((reference operator() (size_type const i, size_type const j))) { STATUS(mi(1,0)); mi(1,0) = 44; STATUS(mi(1,0)); Matrix<int> const & micr = mi; TEST_EQUAL(micr(1,0), 44); } END_SECTION START_SECTION((Value& getValue(size_t const i, size_t const j))) { // Create a test matrix Matrix<int> test_matrix(2, 2, 0); // Test non-const version of getValue by modifying values through it test_matrix.getValue(0, 0) = 100; test_matrix.getValue(0, 1) = 200; test_matrix.getValue(1, 0) = 300; test_matrix.getValue(1, 1) = 400; // Verify the values were set correctly TEST_EQUAL(test_matrix(0, 0), 100); TEST_EQUAL(test_matrix(0, 1), 200); TEST_EQUAL(test_matrix(1, 0), 300); TEST_EQUAL(test_matrix(1, 1), 400); // Verify getValue returns reference that can be modified test_matrix.getValue(0, 0) += 5; TEST_EQUAL(test_matrix(0, 0), 105); } END_SECTION START_SECTION((void operator()(size_type const i, size_type const j) = value_type value)) { mi(1,1) = 18; STATUS("mi:\n" << mi); TEST_EQUAL(mi(1,1),18); } END_SECTION; Matrix<int> mi5(4,5,6); START_SECTION((Matrix(const SizeType rows, const SizeType cols, ValueType value = ValueType()))) { STATUS("mi5:\n"<<mi5); TEST_EQUAL(mi5.size(),20); } END_SECTION; START_SECTION((SizeType cols() const)) { TEST_EQUAL(mi5.rows(),4); } END_SECTION; START_SECTION((SizeType rows() const)) { TEST_EQUAL(mi5.cols(),5); } END_SECTION; Matrix<float> mf(6,7,8); START_SECTION((bool operator==(Matrix const &rhs) const)) { Matrix<int> mi1(4,5,6); mi1(2,3)=17; Matrix<int> mi2(4,5,6); TEST_NOT_EQUAL(mi1,mi2); mi1(2,3)=6; TEST_EQUAL(mi1,mi2); Matrix<int> mi3(5,4,6); Matrix<int> mi4(4,4,6); Matrix<int> mi5(5,5,6); TEST_PRECONDITION_VIOLATED(bool comparison = (mi1==mi3);(void) comparison); TEST_PRECONDITION_VIOLATED(bool comparison = (mi1==mi4);(void) comparison); TEST_PRECONDITION_VIOLATED(bool comparison = (mi1==mi5);(void) comparison); } END_SECTION START_SECTION((template <int ROWS, int COLS> void setMatrix(const ValueType matrix[ROWS][COLS]))) { double test_matrix[4][4] = { {0, 2.5, 3, 0.1}, {0, 1, 5.9, 0.2}, {0, 2, 5.6, 0.1}, {0, 2, 3, 0.1} }; Matrix<double> myMatrix; myMatrix.setMatrix<double, 4 , 4>(test_matrix); for (size_t i=0; i<4; ++i) { for (size_t j=0; j<4; ++j) { TEST_EQUAL( myMatrix(i,j), test_matrix[i][j] ) } } } END_SECTION START_SECTION((template <typename Value > std::ostream & operator<<(std::ostream &os, const Matrix< Value > &matrix))) { Matrix<int> mi(2,3,6); mi(1,2)=112; mi(0,0)=100; mi(1,1)=111; mi(0,2)=103; std::ostringstream os; os << mi; // Uh, finally I got the whitespace right char matrix_dump[] = " 100 6 103 \n" " 6 111 112 \n"; TEST_EQUAL(os.str(),matrix_dump); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SwathMapMassCorrection_test.cpp
.cpp
26,722
741
// 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/CONCEPT/Constants.h> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/SwathMapMassCorrection.h> /////////////////////////// #include <OpenMS/KERNEL/MRMTransitionGroup.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h> #include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h> #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> #include <OpenMS/IONMOBILITY/IMDataConverter.h> using namespace OpenMS; typedef OpenSwath::LightTransition TransitionType; typedef std::map<String, OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType *> TransitionGroupMapPtrType; OpenMS::MRMFeatureFinderScoring::TransitionGroupMapType getData() { OpenMS::MRMFeatureFinderScoring::TransitionGroupMapType map; return map; } OpenSwath::LightTargetedExperiment addTransitions( OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType & transition_group) { OpenSwath::LightTargetedExperiment exp; { String native_id = "tr1"; TransitionType tr; tr.product_mz = 500.00; tr.precursor_mz = 412; tr.peptide_ref = "pep1"; tr.precursor_im = 11; tr.transition_name = native_id; transition_group.addTransition(tr, native_id ); exp.transitions.push_back(tr); } { String native_id = "tr2"; TransitionType tr; tr.product_mz = 600.00; tr.precursor_mz = 412; tr.peptide_ref = "pep1"; tr.precursor_im = 11; tr.transition_name = native_id; transition_group.addTransition(tr, native_id ); exp.transitions.push_back(tr); } { String native_id = "tr3"; TransitionType tr; tr.product_mz = 700.00; tr.precursor_mz = 412; tr.peptide_ref = "pep1"; tr.precursor_im = 11; tr.transition_name = native_id; transition_group.addTransition(tr, native_id ); exp.transitions.push_back(tr); } { String native_id = "tr4"; TransitionType tr; tr.product_mz = 800.00; tr.precursor_mz = 412; tr.peptide_ref = "pep1"; tr.precursor_im = 11; tr.transition_name = native_id; transition_group.addTransition(tr, native_id ); exp.transitions.push_back(tr); } OpenSwath::LightCompound cmp; cmp.id = "pep1"; cmp.drift_time = 11; exp.compounds.push_back(cmp); return exp; } void addTransitionsPep2( OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType & transition_group, OpenSwath::LightTargetedExperiment& exp) { String native_id = "tr5"; TransitionType tr; tr.product_mz = 900.00; tr.precursor_mz = 500.0; tr.precursor_im = 15; tr.peptide_ref = "pep2"; tr.transition_name = native_id; transition_group.addTransition(tr, native_id ); exp.transitions.push_back(tr); OpenSwath::LightCompound cmp; cmp.id = "pep2"; cmp.drift_time = 15; exp.compounds.push_back(cmp); } void addTransitionsPep3( OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType & transition_group, OpenSwath::LightTargetedExperiment& exp) { String native_id = "tr6"; TransitionType tr; tr.product_mz = 950.00; tr.precursor_mz = 600.0; tr.precursor_im = 20; tr.peptide_ref = "pep3"; tr.transition_name = native_id; transition_group.addTransition(tr, native_id ); exp.transitions.push_back(tr); OpenSwath::LightCompound cmp; cmp.id = "pep3"; cmp.drift_time = 20; exp.compounds.push_back(cmp); } START_TEST(SwathMapMassCorrection, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// SwathMapMassCorrection* ptr = nullptr; SwathMapMassCorrection* nullPointer = nullptr; START_SECTION(SwathMapMassCorrection()) ptr = new SwathMapMassCorrection; TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(virtual ~SwathMapMassCorrection()) delete ptr; END_SECTION START_SECTION( void correctMZ(OpenMS::MRMFeatureFinderScoring::TransitionGroupMapType & transition_group_map, std::vector< OpenSwath::SwathMap > & swath_maps, const std::string& corr_type, const bool pasef)) { // None of the tests here test pasef flag bool pasef = false; // targets for correction are : 500.00, 600.00, 700.00, 800.00 // "measured data" as input : 500.02, 600.00, 699.97, 800.02 // IM of feature is 11 MRMFeature feature; feature.setRT(3120); OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType transition_group; transition_group.addFeature(feature); OpenSwath::LightTargetedExperiment targ_exp = addTransitions(transition_group); // Add one group to the map std::map<String, OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType *> transition_group_map; transition_group_map["group1"] = &transition_group; transition_group_map["group2"] = &transition_group; transition_group_map["group3"] = &transition_group; // Create a mock spectrum fitting to the transition group std::shared_ptr<PeakMap > exp(new PeakMap); { MSSpectrum spec; Peak1D p; p.setMZ(500.02); p.setIntensity(150); spec.push_back(p); p.setMZ(600.00); p.setIntensity(150); spec.push_back(p); p.setMZ(699.97); p.setIntensity(22500.01); // double the weight of all other data spec.push_back(p); p.setMZ(800.02); p.setIntensity(150); spec.push_back(p); spec.setRT(3121); // 3120 is the feature exp->addSpectrum(spec); } // Create secondary mock spectrum for testing PASEF flag, this spectrum should never be used std::shared_ptr<PeakMap > exp2(new PeakMap); { MSSpectrum spec; Peak1D p; p.setMZ(499.97); p.setIntensity(1500000); // This has the highest weight in this spectrum spec.push_back(p); p.setMZ(600.00); p.setIntensity(150); spec.push_back(p); p.setMZ(699.97); p.setIntensity(150); spec.push_back(p); p.setMZ(800.02); p.setIntensity(150); spec.push_back(p); spec.setRT(3122); // 3120 is the feature exp2->addSpectrum(spec); } OpenSwath::SpectrumAccessPtr sptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp); OpenSwath::SpectrumAccessPtr sptr2 = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp2); OpenSwath::SwathMap map; map.sptr = sptr; map.lower = 400; map.upper = 425; map.center = 412.5; map.imLower = 10; // only used for pasef results map.imUpper = 20; // only used for pasef results map.ms1 = false; OpenSwath::SwathMap mapPASEF; mapPASEF.sptr = sptr2; mapPASEF.lower = 400; mapPASEF.center = 412.5; mapPASEF.ms1 = false; mapPASEF.imLower=20; mapPASEF.imUpper=30; SwathMapMassCorrection mc; // should work with empty maps std::vector< OpenSwath::SwathMap > empty_swath_maps; mc.correctMZ(transition_group_map, targ_exp, empty_swath_maps, pasef); auto p = mc.getDefaults(); p.setValue("mz_correction_function", "unweighted_regression"); mc.setParameters(p); mc.correctMZ(transition_group_map, targ_exp, empty_swath_maps, pasef); std::vector<double> data; { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "none"); p.setValue("mz_extraction_window", 1.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); mc.correctMZ(transition_group_map, targ_exp, swath_maps, pasef); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(data[0], 500.02) TEST_REAL_SIMILAR(data[1], 600.00) TEST_REAL_SIMILAR(data[2], 699.97) TEST_REAL_SIMILAR(data[3], 800.02) } { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "unweighted_regression"); p.setValue("mz_extraction_window", 0.05); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); mc.correctMZ(transition_group_map, targ_exp, swath_maps, pasef); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(data[0], -0.00428216 + 0.999986 * 500.02) // 500.00857204075 TEST_REAL_SIMILAR(data[1], -0.00428216 + 0.999986 * 600.00) // 599.987143224553 TEST_REAL_SIMILAR(data[2], -0.00428216 + 0.999986 * 699.97) // 699.955714551266 TEST_REAL_SIMILAR(data[3], -0.00428216 + 0.999986 * 800.02) // 800.004284734697 } { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "unweighted_regression"); p.setValue("mz_extraction_window", 1.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); mc.correctMZ(transition_group_map, targ_exp, swath_maps, pasef); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(data[0], -0.0219795 + 1.00003 * 500.02) // 500.01300527988 TEST_REAL_SIMILAR(data[1], -0.0219795 + 1.00003 * 600.00) // 599.99600151022 TEST_REAL_SIMILAR(data[2], -0.0219795 + 1.00003 * 699.97) // 699.96899744088 TEST_REAL_SIMILAR(data[3], -0.0219795 + 1.00003 * 800.02) // 800.02199576900 } { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "unweighted_regression"); p.setValue("mz_extraction_window", 1.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); mc.correctMZ(transition_group_map, targ_exp, swath_maps, pasef); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(data[0], -0.0315101 + 1.00005 * 500.02) // 500.01539273402 TEST_REAL_SIMILAR(data[1], -0.0315101 + 1.00005 * 600.00) // 600.00077200650 TEST_REAL_SIMILAR(data[2], -0.0315101 + 1.00005 * 699.97) // 699.97615074094 TEST_REAL_SIMILAR(data[3], -0.0315101 + 1.00005 * 800.02) // 800.03153377967 } { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "quadratic_regression"); p.setValue("mz_extraction_window", 1.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); mc.correctMZ(transition_group_map, targ_exp, swath_maps, pasef); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(data[0], -0.7395987927448004 + 1.002305255194642 * 500.02 -1.750157412772069e-06 * 500.02 * 500.02) // 499.995500552639 TEST_REAL_SIMILAR(data[1], -0.7395987927448004 + 1.002305255194642 * 600.00 -1.750157412772069e-06 * 600.00 * 600.00) // 600.013497655443 TEST_REAL_SIMILAR(data[2], -0.7395987927448004 + 1.002305255194642 * 699.97 -1.750157412772069e-06 * 699.97 * 699.97) // 699.986507058627 TEST_REAL_SIMILAR(data[3], -0.7395987927448004 + 1.002305255194642 * 800.02 -1.750157412772069e-06 * 800.02 * 800.02) // 800.004494718161 } { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "weighted_quadratic_regression"); p.setValue("mz_extraction_window", 1.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); mc.correctMZ(transition_group_map, targ_exp, swath_maps, pasef); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(data[0], -0.8323316718451679 + 1.002596944948891 * 500.02 -1.967834556637627e-06 * 500.02 * 500.02) // 499.994194744862 TEST_REAL_SIMILAR(data[1], -0.8323316718451679 + 1.002596944948891 * 600.00 -1.967834556637627e-06 * 600.00 * 600.00) // 600.0174148571 TEST_REAL_SIMILAR(data[2], -0.8323316718451679 + 1.002596944948891 * 699.97 -1.967834556637627e-06 * 699.97 * 699.97) // 699.991295598558 TEST_REAL_SIMILAR(data[3], -0.8323316718451679 + 1.002596944948891 * 800.02 -1.967834556637627e-06 * 800.02 * 800.02) // 800.005799138426 } { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "quadratic_regression_delta_ppm"); p.setValue("mz_extraction_window", 1.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); mc.correctMZ(transition_group_map, targ_exp, swath_maps, pasef); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(data[0], 499.997160932778) TEST_REAL_SIMILAR(data[1], 600.010219722383) TEST_REAL_SIMILAR(data[2], 699.988081672119) TEST_REAL_SIMILAR(data[3], 800.004537672719) } { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "weighted_quadratic_regression_delta_ppm"); p.setValue("mz_extraction_window", 1.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); mc.correctMZ(transition_group_map, targ_exp, swath_maps, pasef); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(data[0], 499.996336995751) TEST_REAL_SIMILAR(data[1], 600.013185628794) TEST_REAL_SIMILAR(data[2], 699.992311403648) TEST_REAL_SIMILAR(data[3], 800.005854568825) } { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "unweighted_regression"); p.setValue("mz_extraction_window", 0.05); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); mc.correctMZ(transition_group_map, targ_exp, swath_maps, pasef); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(data[0], -0.00428216 + 0.999986 * 500.02) // 500.00857204075 TEST_REAL_SIMILAR(data[1], -0.00428216 + 0.999986 * 600.00) // 599.987143224553 TEST_REAL_SIMILAR(data[2], -0.00428216 + 0.999986 * 699.97) // 699.955714551266 TEST_REAL_SIMILAR(data[3], -0.00428216 + 0.999986 * 800.02) // 800.004284734697 } { // Test with PASEF flag on, correction should only occur based on the first spectrum and thus should acheive the same results as above auto p = mc.getDefaults(); p.setValue("mz_correction_function", "unweighted_regression"); p.setValue("mz_extraction_window", 0.05); mc.setParameters(p); bool pasef = true; std::vector< OpenSwath::SwathMap > swath_maps_pasef; swath_maps_pasef.push_back(map); swath_maps_pasef.push_back(mapPASEF); mc.correctMZ(transition_group_map, targ_exp, swath_maps_pasef, pasef); data = swath_maps_pasef[0].sptr->getSpectrumById(0)->getMZArray()->data; std::cout << data[0] << ";" << data[1] << ";" <<data[2] << ";" << data[3] << std::endl; TEST_REAL_SIMILAR(data[0], -0.00428216 + 0.999986 * 500.02) // 500.00857204075 TEST_REAL_SIMILAR(data[1], -0.00428216 + 0.999986 * 600.00) // 599.987143224553 TEST_REAL_SIMILAR(data[2], -0.00428216 + 0.999986 * 699.97) // 699.955714551266 TEST_REAL_SIMILAR(data[3], -0.00428216 + 0.999986 * 800.02) // 800.004284734697 } } END_SECTION START_SECTION( void correctIM(const std::map<String, OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType *> & transition_group_map, const std::vector< OpenSwath::SwathMap > & swath_maps, const bool pasef, TransformationDescription& im_trafo)) { // m/z targets for correction are : 500.00, 600.00, 700.00, 800.00, 900.00, 950.00 // mobility targets : 11.00, 11.00, 11.00, 11.00, 15.00, 20.00 // "measured data" as input : 22.00, 21.50, 20.50, 21.00, 24.00, 31.00 MRMFeature feature; feature.setRT(3120); OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType gr1, gr2, gr3; gr1.addFeature(feature); gr2.addFeature(feature); gr3.addFeature(feature); OpenSwath::LightTargetedExperiment targ_exp = addTransitions(gr1); addTransitionsPep2(gr2, targ_exp); addTransitionsPep3(gr3, targ_exp); bool pasef = false; // Add one group to the map std::map<String, OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType *> transition_group_map; transition_group_map["group1"] = &gr1; transition_group_map["group2"] = &gr2; transition_group_map["group3"] = &gr3; // Create a mock spectrum fitting to the transition group std::shared_ptr<PeakMap > exp(new PeakMap); { MSSpectrum spec; Peak1D p; p.setMZ(500.02); p.setIntensity(150); spec.push_back(p); p.setMZ(600.00); p.setIntensity(150); spec.push_back(p); p.setMZ(699.97); p.setIntensity(22500.01); // double the weight of all other data spec.push_back(p); p.setMZ(800.02); p.setIntensity(150); spec.push_back(p); p.setMZ(900.02); p.setIntensity(150); spec.push_back(p); p.setMZ(950.02); p.setIntensity(150); spec.push_back(p); spec.setRT(3121); // 3120 is the feature DataArrays::FloatDataArray ion_mobility; ion_mobility.push_back(22.0); ion_mobility.push_back(21.5); ion_mobility.push_back(20.5); ion_mobility.push_back(21.0); ion_mobility.push_back(24.0); ion_mobility.push_back(31.0); IMDataConverter::setIMUnit(ion_mobility, DriftTimeUnit::MILLISECOND); ion_mobility.setName(Constants::UserParam::ION_MOBILITY); auto& fda = spec.getFloatDataArrays(); fda.push_back(ion_mobility); spec.setFloatDataArrays(fda); exp->addSpectrum(spec); } // Create a mock pasef spectrum, should not be used std::shared_ptr<PeakMap > exp2(new PeakMap); { MSSpectrum spec; Peak1D p; p.setMZ(500.02); p.setIntensity(150); spec.push_back(p); p.setMZ(600.00); p.setIntensity(150); spec.push_back(p); p.setMZ(699.97); p.setIntensity(22500.01); // double the weight of all other data spec.push_back(p); p.setMZ(800.02); p.setIntensity(150); spec.push_back(p); p.setMZ(900.02); p.setIntensity(150); spec.push_back(p); p.setMZ(950.02); p.setIntensity(150); spec.push_back(p); spec.setRT(3121); // 3120 is the feature DataArrays::FloatDataArray ion_mobility; ion_mobility.push_back(22.3); ion_mobility.push_back(21.5); ion_mobility.push_back(20.5); ion_mobility.push_back(21.5); ion_mobility.push_back(24.4); ion_mobility.push_back(31.0); IMDataConverter::setIMUnit(ion_mobility, DriftTimeUnit::MILLISECOND); ion_mobility.setName(Constants::UserParam::ION_MOBILITY); auto& fda = spec.getFloatDataArrays(); fda.push_back(ion_mobility); spec.setFloatDataArrays(fda); exp->addSpectrum(spec); } std::shared_ptr<PeakMap > exp_ms1(new PeakMap); { MSSpectrum spec; Peak1D p; p.setMZ(412.02); p.setIntensity(150); spec.push_back(p); p.setMZ(500.02); p.setIntensity(150); spec.push_back(p); p.setMZ(600.01); p.setIntensity(150.0); spec.push_back(p); spec.setRT(3121); // 3120 is the feature DataArrays::FloatDataArray ion_mobility; ion_mobility.push_back(22.0); ion_mobility.push_back(24.0); ion_mobility.push_back(31.0); IMDataConverter::setIMUnit(ion_mobility, DriftTimeUnit::MILLISECOND); ion_mobility.setName(Constants::UserParam::ION_MOBILITY); auto& fda = spec.getFloatDataArrays(); fda.push_back(ion_mobility); spec.setFloatDataArrays(fda); exp_ms1->addSpectrum(spec); } OpenSwath::SpectrumAccessPtr sptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp); OpenSwath::SpectrumAccessPtr sptr2 = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp2); OpenSwath::SpectrumAccessPtr sptr_ms1 = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp_ms1); OpenSwath::SwathMap map; map.sptr = sptr; map.lower = 400; map.upper = 800; map.center = 412.5; map.imLower = 10; map.imUpper = 30; map.ms1 = false; OpenSwath::SwathMap mapPASEF; mapPASEF.sptr = sptr2; mapPASEF.lower = 400; mapPASEF.upper = 800; mapPASEF.center = 412.5; mapPASEF.ms1 = false; mapPASEF.imLower=100; // although this does not make complete sense with spectrum (since spectrum has values in 20s) this is ok because do not want to use this window mapPASEF.imUpper=200; OpenSwath::SwathMap ms1_map; ms1_map.sptr = sptr_ms1; ms1_map.ms1 = true; SwathMapMassCorrection mc; // should work with empty maps std::vector< OpenSwath::SwathMap > empty_swath_maps; TransformationDescription im_trafo; mc.correctIM(transition_group_map, targ_exp, empty_swath_maps, pasef, im_trafo); TEST_REAL_SIMILAR(im_trafo.apply(10), 10) TEST_REAL_SIMILAR(im_trafo.apply(100), 100) auto p = mc.getDefaults(); p.setValue("mz_correction_function", "unweighted_regression"); mc.setParameters(p); mc.correctIM(transition_group_map, targ_exp, empty_swath_maps, pasef, im_trafo); TEST_REAL_SIMILAR(im_trafo.apply(10), 10) TEST_REAL_SIMILAR(im_trafo.apply(100), 100) std::vector<double> data; // test MS2-based ion mobility alignment { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "none"); p.setValue("mz_extraction_window", 1.0); p.setValue("im_extraction_window", 100.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); swath_maps.push_back(ms1_map); TransformationDescription trafo_result; mc.correctIM(transition_group_map, targ_exp, swath_maps, pasef, trafo_result); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(trafo_result.apply(10), 0.889721627408994) TEST_REAL_SIMILAR(trafo_result.apply(20), 10.0974304068522) TEST_REAL_SIMILAR(trafo_result.apply(30), 19.3051391862955) } // test MS2-based ion mobility alignment without MS1 map { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "none"); p.setValue("mz_extraction_window", 1.0); p.setValue("im_extraction_window", 100.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); // swath_maps.push_back(ms1_map); TransformationDescription trafo_result; mc.correctIM(transition_group_map, targ_exp, swath_maps, pasef, trafo_result); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(trafo_result.apply(10), 0.889721627408994) TEST_REAL_SIMILAR(trafo_result.apply(20), 10.0974304068522) TEST_REAL_SIMILAR(trafo_result.apply(30), 19.3051391862955) } // test MS2-based ion mobility from a single peptide { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "none"); p.setValue("mz_extraction_window", 1.0); p.setValue("im_extraction_window", 100.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; OpenSwath::SwathMap map_single = map; map_single.upper = 425; swath_maps.push_back(map_single); // swath_maps.push_back(ms1_map); TransformationDescription trafo_result; mc.correctIM(transition_group_map, targ_exp, swath_maps, pasef, trafo_result); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; // only got a single peptide, so regression is only intercept TEST_REAL_SIMILAR(trafo_result.apply(10), 11) TEST_REAL_SIMILAR(trafo_result.apply(20), 11) TEST_REAL_SIMILAR(trafo_result.apply(30), 11) } // test MS2-based ion mobility alignment for PASEF data (should exclude second spectrum) { auto p = mc.getDefaults(); bool pasef = true; p.setValue("mz_correction_function", "none"); p.setValue("mz_extraction_window", 1.0); p.setValue("im_extraction_window", 100.0); mc.setParameters(p); std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); swath_maps.push_back(mapPASEF); swath_maps.push_back(ms1_map); TransformationDescription trafo_result; mc.correctIM(transition_group_map, targ_exp, swath_maps, pasef, trafo_result); data = swath_maps[0].sptr->getSpectrumById(0)->getMZArray()->data; TEST_REAL_SIMILAR(trafo_result.apply(10), 0.889721627408994) TEST_REAL_SIMILAR(trafo_result.apply(20), 10.0974304068522) TEST_REAL_SIMILAR(trafo_result.apply(30), 19.3051391862955) } /* // test MS1 map when no MS1 is present { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "none"); p.setValue("mz_extraction_window", 1.0); p.setValue("im_extraction_window", 100.0); p.setValue("ms1_im_calibration", "true"); mc.setParameters(p); map.upper = 800; std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); // swath_maps.push_back(ms1_map); TransformationDescription trafo_result; TEST_EXCEPTION(OpenMS::Exception::UnableToFit, mc.correctIM(transition_group_map, targ_exp, swath_maps, pasef, trafo_result)); } */ // test MS1 map when no MS2 is present // This test does not work due to preconditions { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "none"); p.setValue("mz_extraction_window", 1.0); p.setValue("im_extraction_window", 100.0); p.setValue("ms1_im_calibration", "true"); mc.setParameters(p); map.upper = 800; std::vector< OpenSwath::SwathMap > swath_maps; // swath_maps.push_back(map); swath_maps.push_back(ms1_map); TransformationDescription trafo_result; TEST_EXCEPTION(OpenMS::Exception::UnableToFit, mc.correctIM(transition_group_map, targ_exp, swath_maps, pasef, trafo_result)); // this could work in principle but in practice this just fails as an MS2 is expected } // test MS1 ion mobility alignment { auto p = mc.getDefaults(); p.setValue("mz_correction_function", "none"); p.setValue("mz_extraction_window", 1.0); p.setValue("im_extraction_window", 100.0); p.setValue("ms1_im_calibration", "true"); mc.setParameters(p); map.upper = 800; std::vector< OpenSwath::SwathMap > swath_maps; swath_maps.push_back(map); swath_maps.push_back(ms1_map); TransformationDescription trafo_result; mc.correctIM(transition_group_map, targ_exp, swath_maps, pasef, trafo_result); TEST_REAL_SIMILAR(trafo_result.apply(10), 0.835820895522389) TEST_REAL_SIMILAR(trafo_result.apply(20), 10.089552238806) TEST_REAL_SIMILAR(trafo_result.apply(30), 19.3432835820896) } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AbsoluteQuantitationStandards_test.cpp
.cpp
5,428
147
// 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/METADATA/AbsoluteQuantitationStandards.h> #include <OpenMS/FORMAT/AbsoluteQuantitationStandardsFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(AbsoluteQuantitationStandards, "$Id$") ///////////////////////////////////////////////////////////// AbsoluteQuantitationStandards* ptr = 0; AbsoluteQuantitationStandards* null_ptr = 0; vector<AbsoluteQuantitationStandards::runConcentration> runs; AbsoluteQuantitationStandards::runConcentration run; for (Size i = 0; i < 10; ++i) { run.sample_name = i < 5 ? String("sample1") : String("sample2"); run.component_name = String("component") + i; run.IS_component_name = String("IS_component") + i; run.actual_concentration = i; run.IS_actual_concentration = i * 1.1; run.concentration_units = "uM"; run.dilution_factor = 1; runs.push_back(run); } run.sample_name = ""; runs.push_back(run); // without sample_name run.sample_name = "sample2"; run.component_name = ""; runs.push_back(run); // without component_name run.component_name = "component10"; run.IS_component_name = ""; runs.push_back(run); // without IS_component_name run.component_name = "component11"; runs.push_back(run); // without IS_component_name and no match for component_name run.component_name = "component0"; runs.push_back(run); // with a component_name equal to one of those in sample1 vector<FeatureMap> fmaps; FeatureMap fm; Feature feature; vector<Feature> subordinates; fm.setPrimaryMSRunPath({"sample1.mzML"}); for (Size i = 0; i < 5; ++i) { Feature f; f.setMetaValue("native_id", String("component") + i); subordinates.push_back(f); f.setMetaValue("native_id", String("IS_component") + i); subordinates.push_back(f); } feature.setSubordinates(subordinates); fm.push_back(feature); fmaps.push_back(fm); // The first FeatureMap has sample_name: "sample1". It contains 1 feature. This feature has 10 subordinates: // 5 subordinates have native_id: "component0" to "component4", and the other 5 subordinates have native_id: "IS_component0" to "IS_component4". fm.setPrimaryMSRunPath({"sample2.txt"}); Feature f; f.setMetaValue("native_id", String("component10")); subordinates.push_back(f); f.setMetaValue("native_id", String("component0")); subordinates.push_back(f); feature.setSubordinates(subordinates); fm.push_back(feature); fmaps.push_back(fm); // The second FeatureMap has sample_name: "sample2". It contains 1 feature. This feature has 2 subordinates. Their native_id are "component10" and "component0". START_SECTION(AbsoluteQuantitationStandards()) { ptr = new AbsoluteQuantitationStandards(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~AbsoluteQuantitationStandards()) { delete ptr; } END_SECTION START_SECTION(void mapComponentsToConcentrations( const std::vector<runConcentration>& run_concentrations, const std::vector<FeatureMap>& feature_maps, std::map<String, std::vector<featureConcentration>>& components_to_concentrations ) const) { AbsoluteQuantitationStandards aqs; std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>> m; aqs.mapComponentsToConcentrations(runs, fmaps, m); TEST_EQUAL(m.size(), 6) std::vector<AbsoluteQuantitationStandards::featureConcentration> fc; for (Size i = 0; i < 5; ++i) { fc = m.at(String("component") + i); TEST_EQUAL(fc[0].feature.getMetaValue("native_id"), String("component") + i) TEST_EQUAL(fc[0].IS_feature.getMetaValue("native_id"), String("IS_component") + i) } fc = m.at("component10"); TEST_EQUAL(fc.size(), 1) TEST_EQUAL(fc[0].feature.getMetaValue("native_id"), "component10") TEST_EQUAL(fc[0].IS_feature.metaValueExists("native_id"), false) fc = m.at("component0"); TEST_EQUAL(fc.size(), 2) TEST_EQUAL(fc[1].feature.getMetaValue("native_id"), "component0") TEST_EQUAL(fc[1].IS_feature.metaValueExists("native_id"), false) } END_SECTION START_SECTION(void getComponentFeatureConcentrations( const std::vector<AbsoluteQuantitationStandards::runConcentration>& run_concentrations, const std::vector<FeatureMap>& feature_maps, const String& component_name, std::vector<AbsoluteQuantitationStandards::featureConcentration>& feature_concentrations ) const) { AbsoluteQuantitationStandards aqs; std::vector<AbsoluteQuantitationStandards::featureConcentration> fc; aqs.getComponentFeatureConcentrations(runs, fmaps, "component0", fc); TEST_EQUAL(fc.size(), 2) TEST_EQUAL(fc[0].feature.getMetaValue("native_id"), "component0") TEST_EQUAL(fc[0].IS_feature.getMetaValue("native_id"), "IS_component0") TEST_EQUAL(fc[1].feature.getMetaValue("native_id"), "component0") TEST_EQUAL(fc[1].IS_feature.metaValueExists("native_id"), false) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PepXMLFileMascot_test.cpp
.cpp
4,357
101
// 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/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/PepXMLFileMascot.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(PepXMLFileMascot, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PepXMLFileMascot* ptr = nullptr; PepXMLFileMascot* nullPointer = nullptr; PepXMLFileMascot file; START_SECTION(PepXMLFileMascot()) ptr = new PepXMLFileMascot(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~PepXMLFileMascot()) delete ptr; END_SECTION START_SECTION(void load(const String& filename, std::map<String, std::vector<AASequence> >& peptides)) std::map<String, std::vector<AASequence> > peptides; std::map<String, std::vector<AASequence> >::iterator it; std::vector<AASequence> temp_sequences; String filename = OPENMS_GET_TEST_DATA_PATH("PepXMLFileMascot_test.pepXML"); file.load(filename, peptides); it = peptides.begin(); TEST_EQUAL(peptides.size(), 3) TEST_EQUAL(it->first, "402.42_14_3688.53") temp_sequences = it->second; TEST_EQUAL(temp_sequences.size(), 4) TEST_EQUAL(temp_sequences[0].toUnmodifiedString(), "LAPSAAEDGAFR") TEST_EQUAL(temp_sequences[0].toString(), "LAPSAAEDGAFR") TEST_EQUAL(temp_sequences[1].toUnmodifiedString(), "GQPLGQLEAHR") TEST_EQUAL(temp_sequences[1].toString(), "GQPLGQLEAHR") TEST_EQUAL(temp_sequences[2].toUnmodifiedString(), "SPAPLVPVRLR") TEST_EQUAL(temp_sequences[2].toString(), "SPAPLVPVRLR") TEST_EQUAL(temp_sequences[3].toUnmodifiedString(), "QPYLHPSFSK") TEST_EQUAL(temp_sequences[3].toString(), "Q(Deamidated)PYLHPSFSK") ++it; TEST_EQUAL(it->first, "404.875_14_333.442") temp_sequences = it->second; TEST_EQUAL(temp_sequences.size(), 7) TEST_EQUAL(temp_sequences[0].toUnmodifiedString(), "AQAVAAEIRER") TEST_EQUAL(temp_sequences[0].toString(), "AQAVAAEIRER") TEST_EQUAL(temp_sequences[1].toUnmodifiedString(), "AALNAADIVTVR") TEST_EQUAL(temp_sequences[1].toString(), "AALNAADIVTVR") TEST_EQUAL(temp_sequences[2].toUnmodifiedString(), "AEPAAELALEAK") TEST_EQUAL(temp_sequences[2].toString(), "AEPAAELALEAK") TEST_EQUAL(temp_sequences[3].toUnmodifiedString(), "LANAASPAITQR") TEST_EQUAL(temp_sequences[3].toString(), "LANAASPAITQ(Deamidated)R") TEST_EQUAL(temp_sequences[4].toUnmodifiedString(), "SGHSAVLLQDGK") TEST_EQUAL(temp_sequences[4].toString(), "SGHSAVLLQ(Deamidated)DGK") TEST_EQUAL(temp_sequences[5].toUnmodifiedString(), "AGAGIANVQAAIR") TEST_EQUAL(temp_sequences[5].toString(), "AGAGIAN(Deamidated)VQ(Deamidated)AAIR") TEST_EQUAL(temp_sequences[6].toUnmodifiedString(), "VTAPAARSAALGK") TEST_EQUAL(temp_sequences[6].toString(), "VTAPAARSAALGK") ++it; TEST_EQUAL(it->first, "411.766_14_3724.98") temp_sequences = it->second; TEST_EQUAL(temp_sequences.size(), 7) TEST_EQUAL(temp_sequences[0].toUnmodifiedString(), "LLAWMGRTER") TEST_EQUAL(temp_sequences[0].toString(), "LLAWMGRTER") TEST_EQUAL(temp_sequences[1].toUnmodifiedString(), "VLALYRAAQAR") TEST_EQUAL(temp_sequences[1].toString(), "VLALYRAAQ(Deamidated)AR") TEST_EQUAL(temp_sequences[2].toUnmodifiedString(), "RTLLMSLTGLK") TEST_EQUAL(temp_sequences[2].toString(), "RTLLMSLTGLK") TEST_EQUAL(temp_sequences[3].toUnmodifiedString(), "LLGLSRFGLQK") TEST_EQUAL(temp_sequences[3].toString(), "LLGLSRFGLQ(Deamidated)K") TEST_EQUAL(temp_sequences[4].toUnmodifiedString(), "MGGIALLDEIGK") TEST_EQUAL(temp_sequences[4].toString(), "M(Oxidation)GGIALLDEIGK") TEST_EQUAL(temp_sequences[5].toUnmodifiedString(), "DQMDNALRIR") TEST_EQUAL(temp_sequences[5].toString(), "DQMDN(Deamidated)ALRIR") TEST_EQUAL(temp_sequences[6].toUnmodifiedString(), "QTLAGRMVVQK") TEST_EQUAL(temp_sequences[6].toString(), "Q(Deamidated)TLAGRMVVQ(Deamidated)K") END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/StatisticFunctions_test.cpp
.cpp
21,144
583
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Clemens Groepl, Johannes Junker, Mathias Walzer, Chris Bielow $ // -------------------------------------------------------------------------- /////////////////////////// // This one is going to be tested. #include <OpenMS/MATH/StatisticFunctions.h> #include <OpenMS/MATH/MathFunctions.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <boost/math/special_functions/fpclassify.hpp> /////////////////////////// #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <list> using namespace OpenMS; using namespace OpenMS::Math; ///////////////////////////////////////////////////////////// START_TEST( StatisticFunctions, "$Id$" ); ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION([EXTRA](template <typename IteratorType> static double sum(IteratorType begin, IteratorType end))) { int x[] = {-1, 0, 1, 2, 3}; TEST_EQUAL(int(Math::sum(x, x + 5)), 5); TEST_EQUAL(int(Math::sum(x, x)), 0); DoubleList y; y.push_back(-1.0); y.push_back(-0.5); y.push_back(0.0); y.push_back(0.5); y.push_back(1.0); y.push_back(1.5); y.push_back(2.0); TEST_REAL_SIMILAR(Math::sum(y.begin(), y.end()), 3.5); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType> static double mean(IteratorType begin, IteratorType end))) { int x[] = {-1, 0, 1, 2, 3}; TEST_EQUAL(Math::mean(x, x + 5), 1); TEST_EXCEPTION(Exception::InvalidRange, Math::mean(x, x)); DoubleList y = ListUtils::create<double>("-1.0,-0.5,0.0,0.5,1.0,1.5,2.0"); TEST_REAL_SIMILAR(Math::mean(y.begin(), y.end()), 0.5); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType> static double median(IteratorType begin, IteratorType end, bool sorted = false))) { int x[] = {-1, 0, 1, 2, 3}; TEST_REAL_SIMILAR(Math::median(x, x + 5, true), 1.0); int x2[] = {-1, 0, 1, 2, 3, 4}; // (1+2)/2 TEST_REAL_SIMILAR(Math::median(x2, x2 + 6, true), 1.5); TEST_EXCEPTION(Exception::InvalidRange, Math::median(x, x)); // unsorted DoubleList y = ListUtils::create<double>("1.0,-0.5,2.0,0.5,-1.0,1.5,0.0"); TEST_REAL_SIMILAR(Math::median(y.begin(), y.end()), 0.5); y.push_back(-1.5); // even length TEST_REAL_SIMILAR(Math::median(y.begin(), y.end()), 0.25); // sorted DoubleList z_odd = ListUtils::create<double>("-1.0,-0.5,0.0,0.5,1.0,1.5,2.0"); TEST_REAL_SIMILAR(Math::median(z_odd.begin(), z_odd.end(), true), 0.5); DoubleList z_even = ListUtils::create<double>("-1.5,-1.0,-0.5,0.0,0.5,1.0,1.5,2.0"); TEST_REAL_SIMILAR(Math::median(z_even.begin(), z_even.end(), true), 0.25); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType> double MAD(IteratorType begin, IteratorType end, double median_of_numbers))) { int x[] = {-1, 0, 1, 2, 3}; TEST_EQUAL(Math::MAD(x, x + 5, 1), 1); // median{2, 1, 0, 1, 2} int x2[] = {-1, 0, 1, 2, 3, 4}; // median = 1.5 --> median{2.5, 1.5, 0.5, 0.5, 1.5, 2.5} TEST_REAL_SIMILAR(Math::MAD(x2, x2 + 6, true), 1.5); DoubleList z_odd = ListUtils::create<double>("-1.0,-0.5,0.0,0.5,1.0,1.5,2.0"); // median{1.5, 1, 0.5, 0, 0.5, 1, 1.5} == median{0, 0.5, 0.5, 1, 1, 1.5 ,1.5} TEST_REAL_SIMILAR(Math::MAD(z_odd.begin(), z_odd.end(), 0.5), 1); DoubleList z_even = ListUtils::create<double>("-1.5,-1.0,-0.5,0.0,0.5,1.0,1.5,2.0"); // median{2, 1.5, 1, 0.5, 0, 0.5, 1, 1.5} == median{0, 0.5, 0.5, 1, 1, 1.5 , 1.5, 2} TEST_REAL_SIMILAR(Math::MAD(z_even.begin(), z_even.end(), 0.5), 1); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType> double MeanAbsoluteDeviation(IteratorType begin, IteratorType end, double mean_of_numbers))) { int x1[] = {-1, 0, 1, 2, 3}; // mean = 1 TEST_EQUAL(Math::MeanAbsoluteDeviation(x1, x1 + 5, 1), 1.2); int x2[] = {-1, 0, 1, 2, 3, 4}; // mean = 1.5 TEST_REAL_SIMILAR(Math::MeanAbsoluteDeviation(x2, x2 + 6, 1.5), 1.5); // single element test int x3[] = {-1}; // mean = -1 TEST_REAL_SIMILAR(Math::MeanAbsoluteDeviation(x3, x3 + 1, -1.0), 0.0); // empty range int x4[] = {1}; // mean = 1 TEST_EQUAL(std::isnan(Math::MeanAbsoluteDeviation(x4, x4, 1)), true); // NaN DoubleList z_odd = ListUtils::create<double>("-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0"); // mean = 0.5 TEST_REAL_SIMILAR(Math::MeanAbsoluteDeviation(z_odd.begin(), z_odd.end(), 0.5), 0.857142); DoubleList z_even = ListUtils::create<double>("-1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0"); // mean = 0.25 TEST_REAL_SIMILAR(Math::MeanAbsoluteDeviation(z_even.begin(), z_even.end(), 0.25), 1); } END_SECTION START_SECTION([EXTRA](template< typename IteratorType1, typename IteratorType2 > static RealType meanSquareError( IteratorType1 begin_a, const IteratorType1 end_a, IteratorType2 begin_b, const IteratorType2 end_b ))) { std::list<double> numbers1(20, 1.5); std::list<double> numbers2(20, 1.3); double result = 0; TOLERANCE_ABSOLUTE(0.000001); result = Math::meanSquareError(numbers1.begin(), numbers1.end(), numbers2.begin(), numbers2.end()); TEST_REAL_SIMILAR(result, 0.04); } END_SECTION START_SECTION([EXTRA](template< typename IteratorType1, typename IteratorType2 > static RealType classificationRate( IteratorType1 begin_a, const IteratorType1 end_a, IteratorType2 begin_b, const IteratorType2 end_b ))) { std::vector<double> numbers1(20, 1); std::vector<double> numbers2(20, 1); double result = 0; numbers1.resize(40, -1); numbers2.resize(40, -1); numbers1[2] = -1; numbers1[7] = -1; numbers1[11] = -1; numbers1[15] = -1; numbers1[17] = -1; numbers1[25] = 1; numbers1[27] = 1; numbers1[29] = 1; numbers1[31] = 1; numbers1[37] = 1; result = Math::classificationRate(numbers1.begin(), numbers1.end(), numbers2.begin(), numbers2.end()); TEST_REAL_SIMILAR(result, 0.75); } END_SECTION START_SECTION([EXTRA](template< typename IteratorType1, typename IteratorType2 > static RealType pearsonCorrelationCoefficient( const IteratorType1 begin_a, const IteratorType1 end_a, const IteratorType2 begin_b, const IteratorType2 end_b ))) { std::vector<double> numbers1(20, 1.5); std::vector<double> numbers2(20, 1.3); double result = 0; numbers1[0] = 0.1; numbers2[0] = 0.5; numbers1[1] = 0.2; numbers2[1] = 0.7; numbers1[2] = 0.01; numbers2[2] = 0.03; numbers1[3] = 1.7; numbers2[3] = 1.0; numbers1[4] = 3.2; numbers2[4] = 4.0; result = Math::pearsonCorrelationCoefficient(numbers1.begin(), numbers1.end(), numbers2.begin(), numbers2.end()); TEST_REAL_SIMILAR(result, 0.897811); // ************ TEST for nan ***************** std::vector<float> vv1,vv2; vv1.push_back(1); vv1.push_back(1); vv1.push_back(1); vv1.push_back(1); vv1.push_back(1); vv2.push_back(1); vv2.push_back(2); vv2.push_back(3); vv2.push_back(4); vv2.push_back(5); result = Math::pearsonCorrelationCoefficient(vv1.begin(), vv1.end(), vv2.begin(), vv2.end()); if (std::isnan(result) ) result = -1.0; TEST_REAL_SIMILAR(result, -1.0); // ************ TEST for nan ***************** std::vector<float> v1,v2; v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(5); v2.push_back(1); v2.push_back(2); v2.push_back(3); v2.push_back(4); v2.push_back(5); TEST_REAL_SIMILAR(Math::pearsonCorrelationCoefficient(v1.begin(), v1.end(), v2.begin(), v2.end()),1); v2.clear(); v2.push_back(-1); v2.push_back(-2); v2.push_back(-3); v2.push_back(-4); v2.push_back(-5); TEST_REAL_SIMILAR(Math::pearsonCorrelationCoefficient(v1.begin(), v1.end(), v2.begin(), v2.end()),-1); v1.clear(); v2.clear(); v1.push_back(0.3716803f); v1.push_back(0.2778111f); v1.push_back(0.8152372f); v1.push_back(0.7715097f); v1.push_back(0.0163179f); v1.push_back(-0.4898738f); v1.push_back(-0.6060137f); v1.push_back(-0.8882970f); v1.push_back(0.2913591f); v1.push_back(-0.3661791f); v1.push_back(0.1320750f); v1.push_back(0.2637229f); v1.push_back(-0.7390226f); v1.push_back(-0.0395929f); v1.push_back(0.3387334f); v1.push_back(0.8598541f); v1.push_back(0.7388236f); v1.push_back(-0.5928083f); v1.push_back(0.9226006f); v1.push_back(-0.3571427f); v2.push_back(0.6396969f); v2.push_back(0.7942405f); v2.push_back(-0.6364473f); v2.push_back(-0.6845633f); v2.push_back(-0.6908862f); v2.push_back(-0.5034169f); v2.push_back(0.5745298f); v2.push_back(-0.1247591f); v2.push_back(-0.5129564f); v2.push_back(0.0745857f); v2.push_back(0.0733665f); v2.push_back(-0.0118882f); v2.push_back(0.1763471f); v2.push_back(0.1027599f); v2.push_back(-0.9737805f); v2.push_back(0.8747677f); v2.push_back(0.9479392f); v2.push_back(0.0843604f); v2.push_back(-0.3518961f); v2.push_back(-0.3034039f); TEST_REAL_SIMILAR(Math::pearsonCorrelationCoefficient(v1.begin(), v1.end(), v2.begin(), v2.end()),0); v1.clear(); v2.clear(); v1.push_back(-0.1833341f); v1.push_back(0.6564449f); v1.push_back(0.8725039f); v1.push_back(0.3610921f); v1.push_back(0.7926144f); v1.push_back(0.1833341f); v1.push_back(-0.6564449f); v1.push_back(-0.4141061f); v1.push_back(-0.8725039f); v1.push_back(0.8269985f); v1.push_back(-0.5878715f); v1.push_back(-0.2950443f); v1.push_back(-0.3610921f); v1.push_back(-0.8269985f); v1.push_back(-0.0470327f); v1.push_back(0.4141061f); v1.push_back(0.0470327f); v1.push_back(0.2950443f); v1.push_back(-0.7926144f); v1.push_back(0.5878715f); v2.push_back(0.0336114f); v2.push_back(0.4309199f); v2.push_back(0.7612631f); v2.push_back(0.1303875f); v2.push_back(0.6282377f); v2.push_back(0.0336114f); v2.push_back(0.4309199f); v2.push_back(0.1714839f); v2.push_back(0.7612631f); v2.push_back(0.6839264f); v2.push_back(0.3455929f); v2.push_back(0.0870511f); v2.push_back(0.1303875f); v2.push_back(0.6839264f); v2.push_back(0.0022121f); v2.push_back(0.1714839f); v2.push_back(0.0022121f); v2.push_back(0.0870511f); v2.push_back(0.6282377f); v2.push_back(0.3455929f); TEST_REAL_SIMILAR(Math::pearsonCorrelationCoefficient(v1.begin(), v1.end(), v2.begin(), v2.end()),0); } END_SECTION START_SECTION([EXTRA](static void computeRank(std::vector<double>& w))) { std::vector<double> numbers1(10, 1.5); numbers1[0] = 1.4; numbers1[1] = 0.2; numbers1[2] = 0.01; numbers1[3] = 1.7; numbers1[4] = 3.2; numbers1[5] = 2.2; TEST_REAL_SIMILAR(numbers1[0], 1.4); TEST_REAL_SIMILAR(numbers1[5], 2.2); TEST_REAL_SIMILAR(numbers1[6], 1.5); TEST_REAL_SIMILAR(numbers1[9], 1.5); Math::computeRank(numbers1); TEST_REAL_SIMILAR(numbers1[0], 3); TEST_REAL_SIMILAR(numbers1[1], 2); TEST_REAL_SIMILAR(numbers1[2], 1); TEST_REAL_SIMILAR(numbers1[3], 8); TEST_REAL_SIMILAR(numbers1[4], 10); TEST_REAL_SIMILAR(numbers1[5], 9); TEST_REAL_SIMILAR(numbers1[6], 5.5); TEST_REAL_SIMILAR(numbers1[7], 5.5); TEST_REAL_SIMILAR(numbers1[8], 5.5); TEST_REAL_SIMILAR(numbers1[9], 5.5); } END_SECTION START_SECTION([EXTRA](template< typename IteratorType1, typename IteratorType2 > static RealType rankCorrelationCoefficient( const IteratorType1 begin_a, const IteratorType1 end_a, const IteratorType2 begin_b, const IteratorType2 end_b ))) { std::vector<double> numbers1(10, 1.5); std::vector<double> numbers2(10, 1.3); std::vector<double> numbers3(10, 0.42); std::vector<double> numbers4(10, 0.0); double result = 0; for (Size i = 0; i < numbers4.size(); ++i) { numbers4[i] = (double)(i+1); } numbers1[0] = 0.4; numbers2[0] = 0.5; numbers1[1] = 0.2; numbers2[1] = 0.7; numbers1[2] = 0.01; numbers2[2] = 0.03; numbers1[3] = 1.7; numbers2[3] = 1.0; numbers1[4] = 3.2; numbers2[4] = 4.0; numbers1[5] = 2.2; numbers2[5] = 3.0; result = Math::rankCorrelationCoefficient(numbers1.begin(), numbers1.end(), numbers2.begin(), numbers2.end()); TEST_REAL_SIMILAR(result, 0.858064516129032); result = Math::rankCorrelationCoefficient(numbers1.begin(), numbers1.end(), numbers2.rbegin(), numbers2.rend()); TEST_REAL_SIMILAR(result, 0.303225806451613); result = Math::rankCorrelationCoefficient(numbers3.begin(), numbers3.end(), numbers4.begin(), numbers4.end()); TEST_REAL_SIMILAR(result, 0.0); result = Math::rankCorrelationCoefficient(numbers3.begin(), numbers3.end(), numbers3.begin(), numbers3.end()); TEST_REAL_SIMILAR(result, 0.0); result = Math::rankCorrelationCoefficient(numbers4.begin(), numbers4.end(), numbers4.begin(), numbers4.end()); TEST_REAL_SIMILAR(result, 1.0); result = Math::rankCorrelationCoefficient(numbers4.begin(), numbers4.end(), numbers4.rbegin(), numbers4.rend()); TEST_REAL_SIMILAR(result, -1.0); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType> static double quantile(IteratorType begin, IteratorType end, UInt quantile, bool sorted = false) )) { std::vector<int> x = {3,6,7,8,8,10,13,15,16,20}; std::vector<int> y = {3,6,7,8,8,10,13,15,16}; TEST_REAL_SIMILAR(Math::quantile1st(x.begin(), x.end(), true), 6.5); TEST_REAL_SIMILAR(Math::median(x.begin(), x.end(), true), 9.0); TEST_REAL_SIMILAR(Math::quantile3rd(x.begin(), x.end(), true), 15.5); TEST_REAL_SIMILAR(Math::quantile1st(y.begin(), y.end(), true),6.5); TEST_REAL_SIMILAR(Math::median(y.begin(), y.end(), true), 8.0); TEST_REAL_SIMILAR(Math::quantile3rd(y.begin(), y.end(), true), 14.0); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType> static double quantile(IteratorType begin, IteratorType end, double q))) { std::vector<int> v{1,2,3,4}; // already sorted TEST_REAL_SIMILAR(Math::quantile(v.begin(), v.end(), 0.0), 1.0); TEST_REAL_SIMILAR(Math::quantile(v.begin(), v.end(), 1.0), 4.0); // Type-7 median (even length): pos = 0.5*(n-1) = 1.5 -> 2.5 TEST_REAL_SIMILAR(Math::quantile(v.begin(), v.end(), 0.5), 2.5); TEST_REAL_SIMILAR(Math::quantile(v.begin(), v.end(), 0.25), 1.75); TEST_REAL_SIMILAR(Math::quantile(v.begin(), v.end(), 0.75), 3.25); std::vector<double> empty; TEST_EXCEPTION(Exception::InvalidRange, Math::quantile(empty.begin(), empty.end(), 0.5)); TEST_EXCEPTION(Exception::InvalidValue, Math::quantile(v.begin(), v.end(), -0.1)); TEST_EXCEPTION(Exception::InvalidValue, Math::quantile(v.begin(), v.end(), 1.1)); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType> double tukeyUpperFence(IteratorType begin, IteratorType end, double k))) { // v = 1..9 → Q1=3, Q3=7, IQR=4 → UF = 7 + 1.5*4 = 13 std::vector<int> v = {1,2,3,4,5,6,7,8,9}; TEST_REAL_SIMILAR(Math::tukeyUpperFence(v.begin(), v.end(), 1.5), 13.0); // too few valid values → +inf std::vector<double> tiny = {1.0, std::numeric_limits<double>::quiet_NaN()}; TEST_EQUAL(std::isinf(Math::tukeyUpperFence(tiny.begin(), tiny.end(), 1.5)), true); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType> double tailFractionAbove(IteratorType begin, IteratorType end, double threshold))) { std::vector<int> v = {1,2,3,4,5,6,7,8,9}; // values > 7 are {8,9} → 2/9 double r = Math::tailFractionAbove(v.begin(), v.end(), 7.0); TOLERANCE_ABSOLUTE(1e-12); TEST_REAL_SIMILAR(r, 2.0/9.0); // threshold above max → 0 TEST_REAL_SIMILAR(Math::tailFractionAbove(v.begin(), v.end(), 10.0), 0.0); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType> double winsorizedQuantile(IteratorType begin, IteratorType end, double q, double upper_fence))) { // Example: v = {1,2,3,100} // Raw q=0.75 (Type-7): pos=2.25 → 0.75*3 + 0.25*100 = 27.25 // UF computed externally: Q1=1.75, Q3=27.25, IQR=25.5 → UF=65.5 std::vector<double> v = {1.0, 2.0, 3.0, 100.0}; const double uf = 65.5; const double raw_q = Math::quantile(v.begin(), v.end(), 0.75); TEST_REAL_SIMILAR(raw_q, 27.25); const double win_q = Math::winsorizedQuantile(v.begin(), v.end(), 0.75, uf); TEST_REAL_SIMILAR(win_q, 18.625); // pos=2.25 between 3 and 65.5 → 0.75*3 + 0.25*65.5 // If UF is +inf, falls back to raw quantile const double win_inf = Math::winsorizedQuantile(v.begin(), v.end(), 0.75, std::numeric_limits<double>::infinity()); TEST_REAL_SIMILAR(win_inf, raw_q); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType> double adaptiveQuantile(IteratorType begin, IteratorType end, double q, double k, double r_sparse, double r_dense, double* out_half_raw, double* out_half_rob, double* out_upper_fence, double* out_tail_frac))) { TOLERANCE_ABSOLUTE(1e-9); // --- Case A: sparse tail -> prefer robust (w=0) // Base: 0..9 repeated 20 times (200 values), plus one outlier 1000 (r ≈ 0.005 < 1%) std::vector<double> a; a.reserve(201); for (int rep = 0; rep < 20; ++rep) for (int z = 0; z <= 9; ++z) a.push_back(static_cast<double>(z)); a.push_back(1000.0); const double qA = 0.997; // forces interpolation with the last value present Math::AdaptiveQuantileResult ada_A = Math::adaptiveQuantile(a.begin(), a.end(), qA, /*k=*/1.5, /*r_sparse=*/0.01, /*r_dense=*/0.10); // Tail is sparse → expect robust to win and adaptive == robust (within tol), // and robust << raw because 1000 is capped at UF ~ 15. TEST_TRUE(ada_A.tail_fraction < 0.01); TEST_REAL_SIMILAR(ada_A.blended, ada_A.half_rob); TEST_TRUE(ada_A.half_raw > ada_A.half_rob); // --- Case B: dense tail -> prefer raw (w=1) // Add many outliers: 30 values of 1000 → r ≳ 0.13 > 0.10 std::vector<double> b = a; for (int i=0; i<29; ++i) b.push_back(1000.0); // total outliers now 30 Math::AdaptiveQuantileResult ada_B = Math::adaptiveQuantile(b.begin(), b.end(), qA, 1.5, 0.01, 0.10); TEST_TRUE(ada_B.tail_fraction > 0.10); TEST_REAL_SIMILAR(ada_B.blended, ada_B.half_raw); TEST_TRUE(ada_B.half_raw >= ada_B.half_rob); // --- Case C: intermediate tail density -> interpolation between robust and raw // Make about ~5% tail: add 10 outliers to the base (200 base + 10 outliers = 210, r≈0.0476) std::vector<double> c; c.reserve(210); for (int rep = 0; rep < 20; ++rep) for (int z = 0; z <= 9; ++z) c.push_back(static_cast<double>(z)); for (int i=0; i<10; ++i) c.push_back(1000.0); Math::AdaptiveQuantileResult ada_C = Math::adaptiveQuantile(c.begin(), c.end(), qA, 1.5, 0.01, 0.10); // Expected linear weight w = (r - r_sparse) / (r_dense - r_sparse) const double w = std::max(0.0, std::min(1.0, (ada_C.tail_fraction - 0.01) / (0.10 - 0.01))); const double expected_blend = (1.0 - w) * ada_C.half_rob + w * ada_C.half_raw; TEST_TRUE(ada_C.tail_fraction > 0.01 && ada_C.tail_fraction < 0.10); TEST_REAL_SIMILAR(ada_C.blended, expected_blend); TEST_TRUE(ada_C.half_rob <= ada_C.blended && ada_C.blended <= ada_C.half_raw); } END_SECTION START_SECTION([EXTRA](template <typename IteratorType1, typename IteratorType2> static double rootMeanSquareError(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b))) { using OpenMS::Math::meanSquareError; using OpenMS::Math::rootMeanSquareError; // Simple hand-checkable case: constant offset of -0.5 std::vector<double> a{1.0, 2.0, 3.0}; std::vector<double> b{1.5, 2.5, 3.5}; const double mse = meanSquareError(a.begin(), a.end(), b.begin(), b.end()); const double rmse = rootMeanSquareError(a.begin(), a.end(), b.begin(), b.end()); TEST_REAL_SIMILAR(mse, 0.25); TEST_REAL_SIMILAR(rmse, std::sqrt(0.25)); // Residuals vs zero baseline equals sqrt(mean of squares) std::vector<double> errs{-2.0, 0.0, 2.0}; std::vector<double> zeros(errs.size(), 0.0); TEST_REAL_SIMILAR( rootMeanSquareError(errs.begin(), errs.end(), zeros.begin(), zeros.end()), std::sqrt((4.0 + 0.0 + 4.0) / 3.0) ); // Exceptions: mismatched length and empty ranges std::vector<double> shortv{1.0, 2.0}; TEST_EXCEPTION(Exception::InvalidRange, rootMeanSquareError(errs.begin(), errs.end(), shortv.begin(), shortv.end())); std::vector<double> empty; TEST_EXCEPTION(Exception::InvalidRange, rootMeanSquareError(empty.begin(), empty.end(), empty.begin(), empty.end())); } END_SECTION START_SECTION((template<typename IteratorType1, typename IteratorType2> static void checkIteratorsAreValid)) { std::vector<int> v1 = {1, 2, 3}; std::vector<int> v2 = {10, 20, 30}; // Case 1: Both iterators at begin (not at end) --> OK checkIteratorsAreValid(v1.begin(), v1.end(), v2.begin(), v2.end()); // Case 2: Both iterators at end --> OK checkIteratorsAreValid(v1.end(), v1.end(), v2.end(), v2.end()); // Case 3: One iterator at end, other not --> should throw TEST_EXCEPTION(Exception::InvalidRange, checkIteratorsAreValid(v1.begin(), v1.end(), v2.end(), v2.end())); // Case 4: Reverse mismatch (other one at end) --> should throw TEST_EXCEPTION(Exception::InvalidRange, checkIteratorsAreValid(v1.end(), v1.end(), v2.begin(), v2.end())); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/StreamHandler_test.cpp
.cpp
4,221
129
// 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 <OpenMS/CONCEPT/StreamHandler.h> /////////////////////////// #include <sstream> using namespace OpenMS; using namespace std; START_TEST(StreamHandler, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// StreamHandler* ptr = nullptr; StreamHandler* nullPointer = nullptr; START_SECTION(StreamHandler()) { ptr = new StreamHandler(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~StreamHandler()) { delete ptr; } END_SECTION // main instance for the test StreamHandler handler; START_SECTION((Int registerStream(StreamType const type, const String &stream_name))) { String filename; NEW_TMP_FILE(filename) handler.registerStream(StreamHandler::FILE, filename); handler.getStream(StreamHandler::FILE, filename) << "This is a test!" << endl; ostream & s = handler.getStream(StreamHandler::FILE, filename); s << "And another test!" << endl; TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("StreamHandler_test.txt")) // if you try to register a stream with the same name, but a different type // an Exception should be thrown TEST_EXCEPTION_WITH_MESSAGE(Exception::IllegalArgument, handler.registerStream(StreamHandler::STRING, filename), "This stream was already registered with a different type.") } END_SECTION START_SECTION((void unregisterStream(StreamType const type, const String &stream_name))) { String filename; NEW_TMP_FILE(filename) // this one was registered twice handler.registerStream(StreamHandler::FILE, filename); handler.registerStream(StreamHandler::FILE, filename); // one unregister .. it should still be available handler.unregisterStream(StreamHandler::FILE, filename); handler.getStream(StreamHandler::FILE, filename); // now it should be gone handler.unregisterStream(StreamHandler::FILE, filename); TEST_EXCEPTION(Exception::ElementNotFound, handler.unregisterStream(StreamHandler::FILE, filename)) } END_SECTION START_SECTION((ostream& getStream(StreamType const type, const String &stream_name))) { String file2; NEW_TMP_FILE(file2); handler.registerStream(StreamHandler::FILE, file2); handler.getStream(StreamHandler::FILE, file2) << "This is a test!" << endl; ostream & file_stream = handler.getStream(StreamHandler::FILE, file2); file_stream << "And another test!" << endl; TEST_FILE_EQUAL(file2.c_str(), OPENMS_GET_TEST_DATA_PATH("StreamHandler_test.txt")) // now we test this with stringstreams handler.registerStream(StreamHandler::STRING, "getStream_testing_stream"); handler.getStream(StreamHandler::STRING, "getStream_testing_stream") << "This is a test!" << endl; ostream & string_stream = handler.getStream(StreamHandler::STRING, "getStream_testing_stream"); string_stream << "And another test!" << endl; ostringstream & ostr = static_cast<ostringstream&>(handler.getStream(StreamHandler::STRING, "getStream_testing_stream")); String output(ostr.str()); StringList results; output.trim().split('\n',results); TEST_EQUAL(results.size(), 2) TEST_EQUAL(results[0], "This is a test!") TEST_EQUAL(results[1], "And another test!") } END_SECTION START_SECTION((bool hasStream(const StreamType type, const String &stream_name))) { handler.registerStream(StreamHandler::STRING, "this_is_a_test_stream"); TEST_EQUAL(handler.hasStream(StreamHandler::STRING, "this_is_a_test_stream"), true) TEST_EQUAL(handler.hasStream(StreamHandler::FILE, "this_is_a_test_stream"), false) TEST_EQUAL(handler.hasStream(StreamHandler::STRING, "this_is_not_the_same_stream"), false) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DPosition_test.cpp
.cpp
17,366
648
// 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/DATASTRUCTURES/DPosition.h> #include <iterator> #include <unordered_set> #include <unordered_map> ///////////////////////////////////////////////////////////// #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshadow" #endif using namespace OpenMS; START_TEST(DPosition<D>, "$Id$") ///////////////////////////////////////////////////////////// std::cout.precision(writtenDigits<>(double())); std::cerr.precision(writtenDigits<>(double())); DPosition<10>* d10_ptr = nullptr; DPosition<10>* d10_nullPointer = nullptr; START_SECTION((DPosition())) d10_ptr = new DPosition<10>; TEST_NOT_EQUAL(d10_ptr, d10_nullPointer) END_SECTION START_SECTION((~DPosition())) delete d10_ptr; END_SECTION START_SECTION(void swap(DPosition& rhs) noexcept) { DPosition<3> i(1, 2, 3); DPosition<3> j(4, 5, 6); i.swap(j); TEST_REAL_SIMILAR(i[0], 4) TEST_REAL_SIMILAR(i[1], 5) TEST_REAL_SIMILAR(i[2], 6) TEST_REAL_SIMILAR(j[0], 1) TEST_REAL_SIMILAR(j[1], 2) TEST_REAL_SIMILAR(j[2], 3) } END_SECTION START_SECTION(DPosition& abs() noexcept) { // a bit of fuzz, just to make sure we call the correct std::abs() function for the appropriate data type constexpr const auto weird_negative_int = std::numeric_limits<int64_t>::lowest() + 2; // this value cannot be accurately represented by a double constexpr const auto weird_positive_int = -weird_negative_int; constexpr const double inaccutate_double(weird_negative_int); static_assert(int64_t(inaccutate_double) != weird_negative_int); // make sure its inaccurate DPosition<3, Int64> i(weird_negative_int, -5, weird_positive_int); // test if we call the correct abs() function, i.e. the one for int, not double i.abs(); TEST_EQUAL(i[0], weird_positive_int) TEST_EQUAL(i[1], 5) TEST_EQUAL(i[2], weird_positive_int) // test we call abs() for double, not for float const auto small_negative_double = -std::numeric_limits<double>::epsilon(); DPosition<3, double> j(-1.4444, -small_negative_double, small_negative_double); j.abs(); TEST_EQUAL(j[0], 1.4444) TEST_EQUAL(j[1], -small_negative_double) // test equal, not similar! TEST_EQUAL(j[2], -small_negative_double) // test equal, not similar! } END_SECTION START_SECTION((CoordinateType operator[](Size index) const)) const DPosition<3> i; TEST_EQUAL(i[0], 0.0) TEST_EQUAL(i[1], 0.0) TEST_EQUAL(i[2], 0.0) TEST_PRECONDITION_VIOLATED(i[3]) END_SECTION START_SECTION((CoordinateType& operator[](Size index))) DPosition<3> i; const DPosition<3>& c_i(i); i[0] = 1.0; TEST_REAL_SIMILAR(c_i[0], 1.0) TEST_EQUAL(c_i[1], 0.0) TEST_EQUAL(c_i[2], 0.0) i[1] = 2.0; TEST_REAL_SIMILAR(c_i[0], 1.0) TEST_REAL_SIMILAR(c_i[1], 2.0) TEST_EQUAL(c_i[2], 0.0) i[2] = 3.0; TEST_REAL_SIMILAR(c_i[0], 1.0) TEST_REAL_SIMILAR(c_i[1], 2.0) TEST_REAL_SIMILAR(c_i[2], 3.0) TEST_PRECONDITION_VIOLATED(i[3] = 4.0) END_SECTION START_SECTION((DPosition(const DPosition& pos))) DPosition<3> p; p[0] = 12.3; p[1] = 23.4; p[2] = 34.5; DPosition<3> copy_of_p(p); TEST_EQUAL(copy_of_p[0], p[0]) TEST_EQUAL(copy_of_p[1], p[1]) TEST_EQUAL(copy_of_p[2], p[2]) TEST_EQUAL(copy_of_p.size(), p.size()) END_SECTION START_SECTION((DPosition& operator=(const DPosition &source))) DPosition<3> p; p[0] = 12.3; p[1] = 23.4; p[2] = 34.5; DPosition<3> copy_of_p; copy_of_p = p; TEST_EQUAL(copy_of_p[0], p[0]) TEST_EQUAL(copy_of_p[1], p[1]) TEST_EQUAL(copy_of_p[2], p[2]) TEST_EQUAL(copy_of_p.size(), p.size()) END_SECTION START_SECTION((DPosition(CoordinateType x))) DPosition<3> p(12.34); TEST_REAL_SIMILAR(p[0], 12.34) TEST_REAL_SIMILAR(p[1], 12.34) TEST_REAL_SIMILAR(p[2], 12.34) END_SECTION START_SECTION((DPosition(CoordinateType x, CoordinateType y))) DPosition<2> p(1, 2); TEST_REAL_SIMILAR(p[0], 1) TEST_REAL_SIMILAR(p[1], 2) END_SECTION START_SECTION(DPosition(CoordinateType x, CoordinateType y, CoordinateType z)) DPosition<3> p(1, 2, 3); TEST_REAL_SIMILAR(p[0], 1) TEST_REAL_SIMILAR(p[1], 2) TEST_REAL_SIMILAR(p[2], 3) END_SECTION START_SECTION((CoordinateType operator*(const DPosition& point) const)) DPosition<3> i; i[0] = 2.0; i[1] = 3.0; i[2] = 4.0; DPosition<3> j; j[0] = 3.0; j[1] = 4.0; j[2] = 5.0; TEST_REAL_SIMILAR(i * j, 6.0 + 12.0 + 20.0) END_SECTION DPosition<10> i; i[0] = 1.0; i[1] = 2.0; i[2] = 3.0; i[3] = 4.0; i[4] = 5.0; i[5] = 6.0; i[6] = 7.0; i[7] = 8.0; i[8] = 9.0; i[9] = 10.0; START_SECTION((ConstIterator begin() const)) const DPosition<10>& c_i(i); TEST_EQUAL(*c_i.begin(), 1.0) END_SECTION START_SECTION((ConstIterator end() const)) const DPosition<10>& c_i(i); TEST_NOT_EQUAL(c_i.end(), c_i.begin()) std::vector<double> v; std::copy(c_i.begin(), c_i.end(), std::back_inserter<std::vector<double> >(v)); TEST_EQUAL(v.size(), 10) ABORT_IF(v.size() != 10) TEST_REAL_SIMILAR(v[0], 1.0) TEST_REAL_SIMILAR(v[1], 2.0) TEST_REAL_SIMILAR(v[2], 3.0) TEST_REAL_SIMILAR(v[3], 4.0) TEST_REAL_SIMILAR(v[4], 5.0) TEST_REAL_SIMILAR(v[5], 6.0) TEST_REAL_SIMILAR(v[6], 7.0) TEST_REAL_SIMILAR(v[7], 8.0) TEST_REAL_SIMILAR(v[8], 9.0) TEST_REAL_SIMILAR(v[9], 10.0) END_SECTION START_SECTION((Iterator begin())) TEST_EQUAL(*i.begin(), 1.0) TEST_EQUAL(i.begin(), &(i[0])) *i.begin() = 11.0; TEST_EQUAL(i[0], 11.0) END_SECTION START_SECTION((Iterator end())) const DPosition<10>& c_i(i); TEST_NOT_EQUAL(c_i.end(), c_i.begin()) std::vector<double> v; std::copy(c_i.begin(), c_i.end(), std::back_inserter<std::vector<double> >(v)); TEST_EQUAL(v.size(), 10) ABORT_IF(v.size() != 10) TEST_REAL_SIMILAR(v[0], 11.0) TEST_REAL_SIMILAR(v[1], 2.0) TEST_REAL_SIMILAR(v[2], 3.0) TEST_REAL_SIMILAR(v[3], 4.0) TEST_REAL_SIMILAR(v[4], 5.0) TEST_REAL_SIMILAR(v[5], 6.0) TEST_REAL_SIMILAR(v[6], 7.0) TEST_REAL_SIMILAR(v[7], 8.0) TEST_REAL_SIMILAR(v[8], 9.0) TEST_REAL_SIMILAR(v[9], 10.0) END_SECTION START_SECTION((static Size size())) TEST_EQUAL(DPosition<777>::size(), 777) DPosition<3> p3; TEST_EQUAL(p3.size(), 3) DPosition<1> p1; TEST_EQUAL(p1.size(), 1) DPosition<123> p123; TEST_EQUAL(p123.size(), 123) END_SECTION START_SECTION((void clear())) DPosition<3> p; p[0] = 1.2; p[1] = 2.3; p[2] = 3.4; TEST_REAL_SIMILAR(p[0], 1.2) TEST_REAL_SIMILAR(p[1], 2.3) TEST_REAL_SIMILAR(p[2], 3.4) p.clear(); TEST_REAL_SIMILAR(p[0], 0.0) TEST_REAL_SIMILAR(p[1], 0.0) TEST_REAL_SIMILAR(p[2], 0.0) END_SECTION START_SECTION((bool operator==(const DPosition &point) const)) DPosition<3> p1,p2; TEST_TRUE(p1 == p2) p1[0]=1.234; TEST_EQUAL(p1==p2, false) p2[0]=1.234; TEST_TRUE(p1 == p2) p1[1]=1.345; TEST_EQUAL(p1==p2, false) p2[1]=1.345; TEST_TRUE(p1 == p2) p1[2]=1.456; TEST_EQUAL(p1==p2, false) p2[2]=1.456; TEST_TRUE(p1 == p2) END_SECTION START_SECTION((bool operator!=(const DPosition &point) const)) DPosition<3> p1,p2; TEST_EQUAL(p1!=p2, false) p1[0]=1.234; TEST_FALSE(p1 == p2) p2[0]=1.234; TEST_EQUAL(p1!=p2, false) p1[1]=1.345; TEST_FALSE(p1 == p2) p2[1]=1.345; TEST_EQUAL(p1!=p2, false) p1[2]=1.456; TEST_FALSE(p1 == p2) p2[2]=1.456; TEST_EQUAL(p1!=p2, false) END_SECTION START_SECTION((bool operator<(const DPosition &point) const)) DPosition<3> p1,p2; TEST_EQUAL(p1<p2, false) p1[0]=p2[0]-0.1; TEST_EQUAL(p1<p2, true) p2[0]=p1[0]-0.1; TEST_EQUAL(p1<p2, false) p2[0]=p1[0]; p1[1]=p2[1]-0.1; TEST_EQUAL(p1<p2, true) p2[1]=p1[1]-0.1; TEST_EQUAL(p1<p2, false) p2[1]=p1[1]; p1[2]=p2[2]-0.1; TEST_EQUAL(p1<p2, true) p2[2]=p1[2]-0.1; TEST_EQUAL(p1<p2, false) p2[2]=p1[2]; END_SECTION START_SECTION((bool operator>(const DPosition &point) const)) DPosition<3> p1,p2; TEST_EQUAL(p1>p2, false) p1[0]=p2[0]-0.1; TEST_EQUAL(p1>p2, false) p2[0]=p1[0]-0.1; TEST_EQUAL(p1>p2, true) p2[0]=p1[0]; END_SECTION START_SECTION((bool operator>=(const DPosition &point) const)) DPosition<3> p1,p2; TEST_EQUAL(p1>=p2, true) p1[0]=p2[0]-0.1; TEST_EQUAL(p1>=p2, false) p2[0]=p1[0]-0.1; TEST_EQUAL(p1>=p2, true) p2[0]=p1[0]; END_SECTION START_SECTION((bool operator<=(const DPosition &point) const)) DPosition<3> p1,p2; TEST_EQUAL(p1<=p2, true) p1[0]=p2[0]-0.1; TEST_EQUAL(p1<=p2, true) p2[0]=p1[0]-0.1; TEST_EQUAL(p1<=p2, false) END_SECTION START_SECTION((DPosition operator-() const)) DPosition<3> p1, p2; p1[0] = 5.0; p2 = -p1; TEST_FALSE(p1 == p2); p2 = -p2; TEST_TRUE(p1 == p2); END_SECTION START_SECTION((DPosition operator-(const DPosition &point) const)) DPosition<3> p1, p2, p3; p1[0] = 1.234; p1[1] = 2.234; p1[2] = 3.234; p2[0] = 0.234; p2[1] = 0.234; p2[2] = 0.234; p3[0] = 1.0; p3[1] = 2.0; p3[2] = 3.0; TEST_REAL_SIMILAR(p1[0] - p2[0], p3[0]); TEST_REAL_SIMILAR(p1[1] - p2[1], p3[1]); TEST_REAL_SIMILAR(p2[0] - p1[0], -p3[0]); TEST_REAL_SIMILAR(p2[1] - p1[1], -p3[1]); END_SECTION START_SECTION((DPosition operator+(const DPosition &point) const)) DPosition<3> p1, p2, p3; p1[0] = -1.0; p1[1] = -2.0; p1[2] = -3.0; p2[0] = 1.0; p2[1] = 2.0; p2[2] = 3.0; TEST_EQUAL((p1 + p2) == p3, true); END_SECTION START_SECTION((DPosition(CoordinateType x, CoordinateType y))) DPosition<2> p1(11.0f,12.1f); TEST_REAL_SIMILAR(p1[0],11.0f); TEST_REAL_SIMILAR(p1[1],12.1f); DPosition<2> p(12.34,56.78); TEST_REAL_SIMILAR(p[0], 12.34) TEST_REAL_SIMILAR(p[1], 56.78) END_SECTION START_SECTION((CoordinateType getX() const)) DPosition<2> p1(11.0f,12.1f); TEST_REAL_SIMILAR(p1.getX(),11.0f); END_SECTION START_SECTION((CoordinateType getY() const)) DPosition<2> p1(11.0f,12.1f); TEST_REAL_SIMILAR(p1.getY(),12.1f); END_SECTION START_SECTION((void setX(CoordinateType c))) DPosition<2> p1(11.0f,12.1f); p1.setX(5.0f); TEST_REAL_SIMILAR(p1[0],5.0f); TEST_REAL_SIMILAR(p1[1],12.1f); END_SECTION START_SECTION((void setY(CoordinateType c))) DPosition<2> p1(11.0f,12.1f); p1.setY(5.0f); TEST_REAL_SIMILAR(p1[0],11.0f); TEST_REAL_SIMILAR(p1[1],5.0f); END_SECTION START_SECTION((DPosition& operator *=(CoordinateTypescalar))) DPosition<2> p1(3,4); p1 *= 5; DPosition<2> const p2(15,20); TEST_REAL_SIMILAR(p1[0],p2[0]); TEST_REAL_SIMILAR(p1[1],p2[1]); END_SECTION START_SECTION((DPosition& operator+=(const DPosition &point))) DPosition<2> p1(3,4); DPosition<2> const p2(15,20); p1 += p2; DPosition<2> const p3(18,24); TEST_REAL_SIMILAR(p1[0],p3[0]); TEST_REAL_SIMILAR(p1[1],p3[1]); END_SECTION START_SECTION((DPosition& operator-=(const DPosition &point))) DPosition<2> p1(3,4); DPosition<2> const p2(18,24); p1 -= p2; DPosition<2> const p3(-15,-20); TEST_REAL_SIMILAR(p1[0],p3[0]); TEST_REAL_SIMILAR(p1[1],p3[1]); END_SECTION START_SECTION((DPosition& operator/=(CoordinateTypescalar))) DPosition<2> p1(15,20); p1 /= 5; DPosition<2> const p2(3,4); TEST_REAL_SIMILAR(p1[0],p2[0]); TEST_REAL_SIMILAR(p1[1],p2[1]); END_SECTION START_SECTION((bool spatiallyGreaterEqual(const DPosition &point) const)) DPosition<2> const p00(0,0), p01(0,1), p10(1,0), p11(1,1); TEST_EQUAL(p00.spatiallyGreaterEqual(p00), true ) TEST_EQUAL(p00.spatiallyGreaterEqual(p01), false) TEST_EQUAL(p00.spatiallyGreaterEqual(p10), false) TEST_EQUAL(p00.spatiallyGreaterEqual(p11), false) TEST_EQUAL(p01.spatiallyGreaterEqual(p00), true ) TEST_EQUAL(p01.spatiallyGreaterEqual(p01), true ) TEST_EQUAL(p01.spatiallyGreaterEqual(p10), false) TEST_EQUAL(p01.spatiallyGreaterEqual(p11), false) TEST_EQUAL(p10.spatiallyGreaterEqual(p00), true ) TEST_EQUAL(p10.spatiallyGreaterEqual(p01), false) TEST_EQUAL(p10.spatiallyGreaterEqual(p10), true ) TEST_EQUAL(p10.spatiallyGreaterEqual(p11), false) TEST_EQUAL(p11.spatiallyGreaterEqual(p00), true ) TEST_EQUAL(p11.spatiallyGreaterEqual(p01), true ) TEST_EQUAL(p11.spatiallyGreaterEqual(p10), true ) TEST_EQUAL(p11.spatiallyGreaterEqual(p11), true ) END_SECTION START_SECTION((bool spatiallyLessEqual(const DPosition &point) const)) DPosition<2> const p00(0,0), p01(0,1), p10(1,0), p11(1,1); TEST_EQUAL(p00.spatiallyLessEqual(p00), true ) TEST_EQUAL(p00.spatiallyLessEqual(p01), true ) TEST_EQUAL(p00.spatiallyLessEqual(p10), true ) TEST_EQUAL(p00.spatiallyLessEqual(p11), true ) TEST_EQUAL(p01.spatiallyLessEqual(p00), false) TEST_EQUAL(p01.spatiallyLessEqual(p01), true ) TEST_EQUAL(p01.spatiallyLessEqual(p10), false) TEST_EQUAL(p01.spatiallyLessEqual(p11), true ) TEST_EQUAL(p10.spatiallyLessEqual(p00), false) TEST_EQUAL(p10.spatiallyLessEqual(p01), false) TEST_EQUAL(p10.spatiallyLessEqual(p10), true ) TEST_EQUAL(p10.spatiallyLessEqual(p11), true ) TEST_EQUAL(p11.spatiallyLessEqual(p00), false) TEST_EQUAL(p11.spatiallyLessEqual(p01), false) TEST_EQUAL(p11.spatiallyLessEqual(p10), false) TEST_EQUAL(p11.spatiallyLessEqual(p11), true ) END_SECTION START_SECTION((static const DPosition zero())) typedef DPosition<1> D1; TEST_EQUAL(D1::zero()[0],0); END_SECTION START_SECTION((static const DPosition minPositive())) typedef DPosition<1> D1; TEST_EQUAL(D1::minPositive()[0],std::numeric_limits<D1::CoordinateType>::min()); END_SECTION START_SECTION((static const DPosition minNegative())) typedef DPosition<1> D1; TEST_EQUAL(D1::minNegative()[0],-std::numeric_limits<D1::CoordinateType>::max()); END_SECTION START_SECTION((static const DPosition maxPositive())) typedef DPosition<1> D1; TEST_EQUAL(D1::maxPositive()[0],std::numeric_limits<D1::CoordinateType>::max()); END_SECTION START_SECTION(([EXTRA] Test int DPosition)) { DPosition<2,Int> const p00(0,0), p01(0,1), p10(1,0), p11(1,1); TEST_EQUAL(p00.spatiallyGreaterEqual(p00), true ) TEST_EQUAL(p00.spatiallyGreaterEqual(p01), false) TEST_EQUAL(p00.spatiallyGreaterEqual(p10), false) TEST_EQUAL(p00.spatiallyGreaterEqual(p11), false) TEST_EQUAL(p01.spatiallyGreaterEqual(p00), true ) TEST_EQUAL(p01.spatiallyGreaterEqual(p01), true ) TEST_EQUAL(p01.spatiallyGreaterEqual(p10), false) TEST_EQUAL(p01.spatiallyGreaterEqual(p11), false) TEST_EQUAL(p10.spatiallyGreaterEqual(p00), true ) TEST_EQUAL(p10.spatiallyGreaterEqual(p01), false) TEST_EQUAL(p10.spatiallyGreaterEqual(p10), true ) TEST_EQUAL(p10.spatiallyGreaterEqual(p11), false) TEST_EQUAL(p11.spatiallyGreaterEqual(p00), true ) TEST_EQUAL(p11.spatiallyGreaterEqual(p01), true ) TEST_EQUAL(p11.spatiallyGreaterEqual(p10), true ) TEST_EQUAL(p11.spatiallyGreaterEqual(p11), true ) } END_SECTION START_SECTION(([EXTRA] Test char DPosition)) { DPosition<3,char> pa1; DPosition<3,char> pb2; pa1[0] = 'a'; pb2 = -pa1; TEST_FALSE(pa1 == pb2) pb2 = -pb2; TEST_TRUE(pa1 == pb2) DPosition<1,char> pa('a'); DPosition<1,char> pb('b'); TEST_EQUAL(pa < pb, true) } END_SECTION START_SECTION(([EXTRA] Test scalar multiplication)) { DPosition<2> p1(3,4); DPosition<2> p2 = p1 * 5; DPosition<2> p3 = 5 * p1; DPosition<2> const pResult(15,20); TEST_REAL_SIMILAR(p2[0],pResult[0]); TEST_REAL_SIMILAR(p2[1],pResult[1]); TEST_REAL_SIMILAR(p3[0],pResult[0]); TEST_REAL_SIMILAR(p3[1],pResult[1]); } END_SECTION START_SECTION(([EXTRA] Test scalar division)) { DPosition<2> p1(15,20); DPosition<2> p2 = p1 / 5; DPosition<2> const pResult(3,4); TEST_REAL_SIMILAR(p2[0],pResult[0]); TEST_REAL_SIMILAR(p2[1],pResult[1]); } END_SECTION ///////////////////////////////////////////////////////////// // Hash function tests ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] std::hash<DPosition<2>>)) { // Test that equal positions have equal hashes DPosition<2> p1(1.5, 2.5); DPosition<2> p2(1.5, 2.5); std::hash<DPosition<2>> hasher; TEST_EQUAL(hasher(p1), hasher(p2)) // Test that hash changes when values change DPosition<2> p3(3.5, 2.5); TEST_NOT_EQUAL(hasher(p1), hasher(p3)) // Test use in unordered_set std::unordered_set<DPosition<2>> pos_set; pos_set.insert(p1); TEST_EQUAL(pos_set.size(), 1) pos_set.insert(p2); // same as p1 TEST_EQUAL(pos_set.size(), 1) // should not increase pos_set.insert(p3); TEST_EQUAL(pos_set.size(), 2) // Test use in unordered_map std::unordered_map<DPosition<2>, int> pos_map; pos_map[p1] = 42; TEST_EQUAL(pos_map[p1], 42) TEST_EQUAL(pos_map[p2], 42) // p2 == p1, should get same value pos_map[p3] = 99; TEST_EQUAL(pos_map[p3], 99) TEST_EQUAL(pos_map.size(), 2) } END_SECTION START_SECTION(([EXTRA] std::hash<DPosition<1>>)) { // Test DPosition<1> hash DPosition<1> p1(1.5); DPosition<1> p2(1.5); DPosition<1> p3(2.5); std::hash<DPosition<1>> hasher; TEST_EQUAL(hasher(p1), hasher(p2)) TEST_NOT_EQUAL(hasher(p1), hasher(p3)) std::unordered_set<DPosition<1>> pos_set; pos_set.insert(p1); pos_set.insert(p2); pos_set.insert(p3); TEST_EQUAL(pos_set.size(), 2) // p1 and p2 are the same } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST #ifdef __clang__ #pragma clang diagnostic pop #endif
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BinnedSharedPeakCount_test.cpp
.cpp
2,658
94
// 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/COMPARISON/BinnedSharedPeakCount.h> #include <OpenMS/KERNEL/BinnedSpectrum.h> #include <OpenMS/FORMAT/DTAFile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(BinnedSharedPeakCount, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// BinnedSharedPeakCount* ptr = nullptr; BinnedSharedPeakCount* nullPointer = nullptr; START_SECTION(BinnedSharedPeakCount()) { ptr = new BinnedSharedPeakCount(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~BinnedSharedPeakCount()) { delete ptr; } END_SECTION ptr = new BinnedSharedPeakCount(); START_SECTION((BinnedSharedPeakCount(const BinnedSharedPeakCount &source))) { BinnedSharedPeakCount copy(*ptr); TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); } END_SECTION START_SECTION((BinnedSharedPeakCount& operator=(const BinnedSharedPeakCount &source))) { BinnedSharedPeakCount copy; copy = *ptr; TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); } END_SECTION START_SECTION((double operator()(const BinnedSpectrum &spec1, const BinnedSpectrum &spec2) const)) { PeakSpectrum s1, s2; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s2); s2.pop_back(); BinnedSpectrum bs1(s1, 1.5, false, 2, 0); BinnedSpectrum bs2(s2, 1.5, false, 2, 0); double score = (*ptr)(bs1, bs2); TEST_REAL_SIMILAR(score, 0.997118) // compare to self score = (*ptr)(bs1, bs1); TEST_REAL_SIMILAR(score, 1) } END_SECTION START_SECTION((double operator()(const BinnedSpectrum &spec) const )) { PeakSpectrum s1; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); BinnedSpectrum bs1(s1, 1.5, false, 2, BinnedSpectrum::DEFAULT_BIN_OFFSET_LOWRES); double score = (*ptr)(bs1); TEST_REAL_SIMILAR(score,1); } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/VersionInfo_test.cpp
.cpp
5,270
176
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Clemens Groepl, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CONCEPT/VersionInfo.h> #include <OpenMS/openms_package_version.h> #include <OpenMS/DATASTRUCTURES/String.h> ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; START_TEST(VersionInfo, "$Id$") ///////////////////////////////////////////////////////////// START_SECTION(static String getTime()) { String t = VersionInfo::getTime(); NOT_TESTABLE } END_SECTION START_SECTION(static String getVersion() ) { TEST_STRING_EQUAL(VersionInfo::getVersion(), String(OPENMS_PACKAGE_VERSION).trim()); } END_SECTION START_SECTION((static VersionDetails getVersionStruct())) { VersionInfo::VersionDetails detail; detail.version_major = 3; detail.version_minor = 6; detail.version_patch = 0; TEST_EQUAL(VersionInfo::getVersionStruct().version_major, detail.version_major); TEST_EQUAL(VersionInfo::getVersionStruct().version_minor, detail.version_minor); TEST_EQUAL(VersionInfo::getVersionStruct().version_patch, detail.version_patch); } END_SECTION START_SECTION(([VersionInfo::VersionDetails] VersionDetails())) { VersionInfo::VersionDetails detail; TEST_EQUAL(detail == VersionInfo::VersionDetails::EMPTY, true) } END_SECTION START_SECTION(([VersionInfo::VersionDetails] VersionDetails(const VersionDetails &other))) { VersionInfo::VersionDetails detail = VersionInfo::VersionDetails::create("1.9.2"); VersionInfo::VersionDetails c(detail); TEST_EQUAL(c.version_major, detail.version_major) TEST_EQUAL(c.version_minor, detail.version_minor) TEST_EQUAL(c.version_patch, detail.version_patch) } END_SECTION START_SECTION(([VersionInfo::VersionDetails] bool operator<(const VersionDetails &rhs) const)) { VersionInfo::VersionDetails detail = VersionInfo::VersionDetails::create("1.9.2"); VersionInfo::VersionDetails c; c.version_major = 1; c.version_minor = 9; c.version_patch = 2; TEST_EQUAL(detail < c, false) c.version_patch = 3; TEST_EQUAL(detail < c, true) c.version_patch = 1; TEST_EQUAL(detail < c, false) c.version_major = 2; TEST_EQUAL(detail < c, true) } END_SECTION START_SECTION(([VersionInfo::VersionDetails] bool operator==(const VersionDetails &rhs) const)) { VersionInfo::VersionDetails detail = VersionInfo::VersionDetails::create("1.9.2"); VersionInfo::VersionDetails c; c.version_major = 1; c.version_minor = 9; c.version_patch = 2; TEST_TRUE(detail == c) c.version_patch = 3; TEST_EQUAL(detail == c, false) c.version_patch = 1; TEST_EQUAL(detail == c, false) c.version_major = 2; TEST_EQUAL(detail == c, false) } END_SECTION START_SECTION(([VersionInfo::VersionDetails] bool operator>(const VersionDetails &rhs) const)) { VersionInfo::VersionDetails detail = VersionInfo::VersionDetails::create("1.9.2"); VersionInfo::VersionDetails c; c.version_major = 1; c.version_minor = 9; c.version_patch = 2; TEST_EQUAL(detail > c, false) c.version_patch = 3; TEST_EQUAL(detail > c, false) c.version_patch = 1; TEST_EQUAL(detail > c, true) c.version_patch = 11; TEST_EQUAL(detail < c, true) c.version_patch = 2; TEST_EQUAL(detail > c, false) // note that any version with a pre-release identifier should be "less than" the release version c.pre_release_identifier = "alpha"; TEST_EQUAL(detail > c, true) } END_SECTION START_SECTION(([VersionInfo::VersionDetails] static VersionDetails create(const String &version))) { VersionInfo::VersionDetails detail = VersionInfo::VersionDetails::create("1.9.2"); VersionInfo::VersionDetails c; c.version_major = 1; c.version_minor = 9; c.version_patch = 2; TEST_TRUE(detail == c) detail = VersionInfo::VersionDetails::create("1.9"); c.version_major = 1; c.version_minor = 9; c.version_patch = 0; TEST_TRUE(detail == c) detail = VersionInfo::VersionDetails::create("1.0"); c.version_major = 1; c.version_minor = 0; c.version_patch = 0; TEST_TRUE(detail == c) detail = VersionInfo::VersionDetails::create("somestring"); c.version_major = 0; c.version_minor = 0; c.version_patch = 0; TEST_TRUE(detail == c) detail = VersionInfo::VersionDetails::create("1.2a.bla"); c.version_major = 0; c.version_minor = 0; c.version_patch = 0; TEST_TRUE(detail == c) detail = VersionInfo::VersionDetails::create("1.2.1-bla"); c.version_major = 1; c.version_minor = 2; c.version_patch = 1; c.pre_release_identifier = "bla"; TEST_EQUAL(detail.version_major, c.version_major) TEST_EQUAL(detail.version_minor, c.version_minor) TEST_EQUAL(detail.version_patch, c.version_patch) TEST_EQUAL(detail.pre_release_identifier, c.pre_release_identifier) TEST_TRUE(detail == c) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Residue_test.cpp
.cpp
23,835
853
// 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/Residue.h> #include <OpenMS/CHEMISTRY/ResidueDB.h> #include <OpenMS/CHEMISTRY/ResidueModification.h> #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(Residue, "$Id$") ///////////////////////////////////////////////////////////// Residue* e_ptr = nullptr; Residue* e_nullPointer = nullptr; START_SECTION((Residue())) { e_ptr = new Residue(); TEST_NOT_EQUAL(e_ptr, e_nullPointer) } END_SECTION START_SECTION((virtual ~Residue())) { delete e_ptr; } END_SECTION ResidueDB* db = ResidueDB::getInstance(); e_ptr = new Residue(*db->getResidue("Lys")); EmpiricalFormula h2o("H2O"); START_SECTION((static const EmpiricalFormula& getInternalToFull())) { TEST_EQUAL(e_ptr->getInternalToFull(), h2o) } END_SECTION TOLERANCE_ABSOLUTE(0.001) START_SECTION((static const EmpiricalFormula& getInternalToNTerm())) TEST_EQUAL(e_ptr->getInternalToNTerm(), EmpiricalFormula("H")) END_SECTION START_SECTION((static const EmpiricalFormula& getInternalToCTerm())) TEST_EQUAL(e_ptr->getInternalToCTerm(), EmpiricalFormula("OH")) END_SECTION START_SECTION((static const EmpiricalFormula& getInternalToAIon())) TEST_EQUAL(e_ptr->getInternalToAIon(), EmpiricalFormula("")-EmpiricalFormula("CO")) END_SECTION START_SECTION((static const EmpiricalFormula& getInternalToBIon())) TEST_EQUAL(e_ptr->getInternalToBIon(), EmpiricalFormula("")) END_SECTION START_SECTION((static const EmpiricalFormula& getInternalToCIon())) TEST_EQUAL(e_ptr->getInternalToCIon(), EmpiricalFormula("NH3")) END_SECTION START_SECTION((static const EmpiricalFormula& getInternalToXIon())) TEST_EQUAL(e_ptr->getInternalToXIon(), EmpiricalFormula("CO2")) END_SECTION START_SECTION((static const EmpiricalFormula& getInternalToYIon())) TEST_EQUAL(e_ptr->getInternalToYIon(), EmpiricalFormula("H2O")) END_SECTION START_SECTION((static const EmpiricalFormula& getInternalToZIon())) TEST_EQUAL(e_ptr->getInternalToZIon(), EmpiricalFormula("OH") - EmpiricalFormula("NH2")) END_SECTION START_SECTION(Residue(const Residue &residue)) Residue copy(*e_ptr); TEST_EQUAL(copy, *e_ptr) END_SECTION START_SECTION(Residue(const String &name, const String &three_letter_code, const String &one_letter_code, const EmpiricalFormula &formula)) { Residue copy(e_ptr->getName(), e_ptr->getThreeLetterCode(), e_ptr->getOneLetterCode(), e_ptr->getFormula()); TEST_EQUAL(copy.getName(), e_ptr->getName()) TEST_EQUAL(copy.getThreeLetterCode(), e_ptr->getThreeLetterCode()) TEST_EQUAL(copy.getOneLetterCode(), e_ptr->getOneLetterCode()) TEST_EQUAL(copy.getFormula(), e_ptr->getFormula()) } END_SECTION START_SECTION(Residue& operator=(const Residue &residue)) { Residue copy; copy = *e_ptr; TEST_EQUAL(copy, *e_ptr) } END_SECTION START_SECTION(void setName(const String &name)) { Residue copy(*e_ptr); e_ptr->setName("BLUBB"); TEST_NOT_EQUAL(copy, *e_ptr) } END_SECTION START_SECTION(const String& getName() const) { TEST_EQUAL(e_ptr->getName(), "BLUBB") } END_SECTION START_SECTION(void setSynonyms(const std::set< String > &synonyms)) { Residue copy(*e_ptr); set<String> syn; syn.insert("BLI"); syn.insert("BLA"); e_ptr->setSynonyms(syn); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(void addSynonym(const String &synonym)) { Residue copy(*e_ptr); e_ptr->addSynonym("BLUFF"); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(const std::set<String>& getSynonyms() const) { TEST_EQUAL(e_ptr->getSynonyms().size(), 3) } END_SECTION START_SECTION(void setThreeLetterCode(const String &three_letter_code)) { Residue copy(*e_ptr); e_ptr->setThreeLetterCode("BLA"); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(const String& getThreeLetterCode() const) { TEST_EQUAL(e_ptr->getThreeLetterCode(), "BLA") } END_SECTION START_SECTION(void setOneLetterCode(const String &one_letter_code)) { Residue copy(*e_ptr); e_ptr->setOneLetterCode("B"); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(const String& getOneLetterCode() const) { TEST_EQUAL(e_ptr->getOneLetterCode(), "B") } END_SECTION START_SECTION(void addLossFormula(const EmpiricalFormula&)) { Residue copy(*e_ptr); TEST_EQUAL(*e_ptr, copy) e_ptr->addLossFormula(EmpiricalFormula("H2O")); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(void setLossFormulas(const std::vector<EmpiricalFormula> &)) { Residue copy(*e_ptr); TEST_EQUAL(*e_ptr, copy) std::vector<EmpiricalFormula> losses; losses.push_back(EmpiricalFormula("H2O")); e_ptr->setLossFormulas(losses); TEST_NOT_EQUAL(*e_ptr == copy, true) } END_SECTION START_SECTION(const std::vector<EmpiricalFormula>& getLossFormulas() const) { std::vector<EmpiricalFormula> losses; losses.push_back(EmpiricalFormula("H2O")); TEST_EQUAL(e_ptr->getLossFormulas() == losses, true) } END_SECTION START_SECTION(void setLossNames(const std::vector<String> &name)) { Residue copy(*e_ptr); TEST_EQUAL(*e_ptr, copy) vector<String> names; names.push_back("Waesserchen"); e_ptr->setLossNames(names); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(const std::vector<String>& getLossNames() const) { vector<String> names; names.push_back("Waesserchen"); TEST_EQUAL(e_ptr->getLossNames() == names, true) } END_SECTION START_SECTION(void addLossName(const String& name)) { Residue copy(*e_ptr); TEST_EQUAL(*e_ptr, copy) copy.addLossName("Waesserchen2"); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(void setNTermLossFormulas(const std::vector< EmpiricalFormula > &)) { Residue copy(*e_ptr); TEST_EQUAL(*e_ptr, copy) vector<EmpiricalFormula> losses; losses.push_back(EmpiricalFormula("H3O")); e_ptr->setNTermLossFormulas(losses); TEST_NOT_EQUAL(*e_ptr == copy, true) } END_SECTION START_SECTION(const std::vector<EmpiricalFormula>& getNTermLossFormulas() const) { vector<EmpiricalFormula> losses; losses.push_back(EmpiricalFormula("H3O")); TEST_EQUAL(e_ptr->getNTermLossFormulas() == losses, true) } END_SECTION START_SECTION(void addNTermLossFormula(const EmpiricalFormula&)) { Residue copy(*e_ptr); TEST_EQUAL(*e_ptr, copy) e_ptr->addNTermLossFormula(EmpiricalFormula("H4O")); TEST_NOT_EQUAL(*e_ptr == copy, true) } END_SECTION START_SECTION(void setNTermLossNames(const std::vector< String > &name)) { Residue copy(*e_ptr); TEST_EQUAL(*e_ptr, copy); vector<String> names; names.push_back("Nwaesserchen"); e_ptr->setNTermLossNames(names); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(const std::vector<String>& getNTermLossNames() const) { vector<String> names; names.push_back("Nwaesserchen"); TEST_EQUAL(e_ptr->getNTermLossNames() == names, true) } END_SECTION START_SECTION(void addNTermLossName(const String &name)) { Residue copy(*e_ptr); TEST_EQUAL(*e_ptr, copy); e_ptr->addNTermLossName("Nwaesserchen2"); TEST_NOT_EQUAL(*e_ptr == copy, true); } END_SECTION START_SECTION(bool hasNTermNeutralLosses() const) { Residue copy(*e_ptr); TEST_EQUAL(copy.hasNTermNeutralLosses(), true) copy.setNTermLossFormulas(vector<EmpiricalFormula>()); copy.setNTermLossNames(vector<String>()); TEST_EQUAL(copy.hasNTermNeutralLosses(), false) } END_SECTION START_SECTION(void setFormula(const EmpiricalFormula &formula)) { Residue copy(*e_ptr); e_ptr->setFormula(EmpiricalFormula("C2H6O")); TEST_NOT_EQUAL(*e_ptr, copy) TEST_REAL_SIMILAR(e_ptr->getAverageWeight(), 46.06852164251619); TEST_REAL_SIMILAR(e_ptr->getMonoWeight(), 46.0418651914); } END_SECTION START_SECTION(EmpiricalFormula getFormula(ResidueType res_type=Full) const) TEST_EQUAL(e_ptr->getFormula(), EmpiricalFormula("C2H6O")) END_SECTION START_SECTION(void setAverageWeight(double weight)) { Residue copy(*e_ptr); e_ptr->setAverageWeight(123.4); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(double getAverageWeight(ResidueType res_type=Full) const) TEST_REAL_SIMILAR(e_ptr->getAverageWeight(), 123.4) END_SECTION START_SECTION(void setMonoWeight(double weight)) Residue copy(*e_ptr); e_ptr->setMonoWeight(1234.5); TEST_NOT_EQUAL(*e_ptr, copy) END_SECTION START_SECTION(double getMonoWeight(ResidueType res_type=Full) const) TEST_REAL_SIMILAR(e_ptr->getMonoWeight(), 1234.5) END_SECTION START_SECTION(void setModification(const String& name)) { e_ptr->setOneLetterCode("M"); // we need M for this mod TEST_EQUAL(e_ptr->getModificationName(), "") TEST_EQUAL(e_ptr->getModification() == nullptr, true) e_ptr->setModification("Oxidation"); TEST_EQUAL(e_ptr->getModificationName(), "Oxidation") TEST_EQUAL(e_ptr->getModification()->getFullId(), "Oxidation (M)") e_ptr->setOneLetterCode("C"); // TODO Why do we allow setting of the OneLetterCode?? This should be const after construction! // TODO Shouldn't the modification be re-checked or deleted if the OneLetterCode changes??? } END_SECTION START_SECTION(void setModificationByDiffMonoMass(double diffMonoMass)) { e_ptr->setModificationByDiffMonoMass(-1000000); TEST_EQUAL(e_ptr->getModificationName(), "") TEST_EQUAL(e_ptr->getModification()->getFullId(), "C[-1.0e06]") e_ptr->setOneLetterCode("M"); // we need M for the next mod to be findable e_ptr->setModificationByDiffMonoMass(15.9949); TEST_EQUAL(e_ptr->getModificationName(), "Oxidation") TEST_EQUAL(e_ptr->getModification()->getFullId(), "Oxidation (M)") e_ptr->setOneLetterCode("B"); } END_SECTION START_SECTION(String Residue::toString() const) { auto rr(*db->getResidue("Met")); TEST_EQUAL(rr.toString(), "M"); TEST_EQUAL(rr.getModification() == nullptr, true) rr.setModification("Oxidation"); TEST_EQUAL(rr.getModificationName(), "Oxidation") TEST_EQUAL(rr.toString(), "M(Oxidation)"); const ResidueModification* mod = ResidueModification::createUnknownFromMassString("123", 123.0, false, ResidueModification::ANYWHERE, &rr); rr.setModification(mod); TEST_EQUAL(rr.toString(), "M[123]"); } END_SECTION START_SECTION(const String& getModificationName() const) NOT_TESTABLE // tested above END_SECTION START_SECTION(const ResidueModification* getModification() const) NOT_TESTABLE // tested above END_SECTION START_SECTION(void setLowMassIons(const std::vector< EmpiricalFormula > &low_mass_ions)) { Residue copy(*e_ptr); vector<EmpiricalFormula> ions; ions.push_back(EmpiricalFormula("NH3")); ions.push_back(EmpiricalFormula("PO4")); e_ptr->setLowMassIons(ions); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(const std::vector<EmpiricalFormula>& getLowMassIons() const) TEST_EQUAL(e_ptr->getLowMassIons()[0], EmpiricalFormula("NH3")) END_SECTION START_SECTION(bool hasNeutralLoss() const) { Residue res; TEST_EQUAL(res.hasNeutralLoss(), false) res.addLossFormula(EmpiricalFormula("H2O")); TEST_EQUAL(res.hasNeutralLoss(), true) } END_SECTION START_SECTION(bool operator==(const Residue &residue) const) { Residue r; r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setName("other_name"); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) set<String> syns; syns.insert("new_syn"); r.setSynonyms(syns); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setThreeLetterCode("3lc"); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setOneLetterCode("1"); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.addLossFormula(EmpiricalFormula("C1H3")); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.addLossName("new_loss_name"); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setFormula(EmpiricalFormula("C16H18N3O5")); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setAverageWeight(12345.678); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setMonoWeight(12345.6789); TEST_EQUAL(r == *e_ptr, false) e_ptr->setOneLetterCode("M"); r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setModification("Oxidation"); TEST_EQUAL(r == *e_ptr, false) e_ptr->setOneLetterCode("B"); r = *e_ptr; TEST_EQUAL(r == *e_ptr, true); vector<EmpiricalFormula> low_mass_ions; low_mass_ions.push_back(EmpiricalFormula("H")); r.setLowMassIons(low_mass_ions); TEST_EQUAL(r == *e_ptr, false); r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setPka(123456.789); TEST_EQUAL(r == *e_ptr, false); r = *e_ptr; TEST_EQUAL(r == *e_ptr, true); r.setPkb(1234567.89); TEST_EQUAL(r == *e_ptr, false); r = *e_ptr; TEST_EQUAL(r == *e_ptr, true); r.setPkc(12345678.9); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setSideChainBasicity(111.2345); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setBackboneBasicityLeft(1112.345); TEST_EQUAL(r == *e_ptr, false) r = *e_ptr; TEST_EQUAL(r == *e_ptr, true) r.setBackboneBasicityRight(11123.45); TEST_EQUAL(r == *e_ptr, false) } END_SECTION START_SECTION(bool operator!=(const Residue &residue) const) { Residue r; r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.setName("other_name"); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) set<String> syns; syns.insert("new_syn"); r.setSynonyms(syns); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.setThreeLetterCode("3lc"); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.setOneLetterCode("1"); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.addLossFormula(EmpiricalFormula("C1H3")); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.addLossName("new_loss_name"); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.setFormula(EmpiricalFormula("C16H18N3O5")); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.setAverageWeight(12345.678); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.setMonoWeight(12345.6789); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false); vector<EmpiricalFormula> low_mass_ions; low_mass_ions.push_back(EmpiricalFormula("H")); r.setLowMassIons(low_mass_ions); TEST_EQUAL(r != *e_ptr, true); r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.setPka(123456.789); TEST_EQUAL(r != *e_ptr, true); r = *e_ptr; TEST_EQUAL(r != *e_ptr, false); r.setPkb(1234567.89); TEST_EQUAL(r != *e_ptr, true); r = *e_ptr; TEST_EQUAL(r != *e_ptr, false); r.setPkc(12345678.9); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.setSideChainBasicity(111.2345); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.setBackboneBasicityLeft(1112.345); TEST_EQUAL(r != *e_ptr, true) r = *e_ptr; TEST_EQUAL(r != *e_ptr, false) r.setBackboneBasicityRight(11123.45); TEST_EQUAL(r != *e_ptr, true) } END_SECTION START_SECTION(bool operator==(char one_letter_code) const) TEST_EQUAL(*e_ptr == 'B', true) END_SECTION START_SECTION(bool operator!=(char one_letter_code) const) TEST_EQUAL(*e_ptr != 'C', true) END_SECTION START_SECTION(void setPka(double value)) Residue copy(*e_ptr); e_ptr->setPka(345.5); TEST_NOT_EQUAL(*e_ptr, copy) END_SECTION START_SECTION(double getPka() const) TEST_REAL_SIMILAR(e_ptr->getPka(), 345.5) END_SECTION START_SECTION(void setPkb(double value)) { Residue copy(*e_ptr); e_ptr->setPkb(675.8); TEST_NOT_EQUAL(*e_ptr, copy) } END_SECTION START_SECTION(double getPkb() const) TEST_REAL_SIMILAR(e_ptr->getPkb(), 675.8) END_SECTION START_SECTION(void setPkc(double value)) Residue copy(*e_ptr); e_ptr->setPkc(9329.0); TEST_NOT_EQUAL(*e_ptr, copy) END_SECTION START_SECTION(double getPkc() const) TEST_REAL_SIMILAR(e_ptr->getPkc(), 9329.0) END_SECTION START_SECTION(double getPiValue() const) TEST_REAL_SIMILAR(db->getResidue("A")->getPiValue(), 6.11) END_SECTION START_SECTION(void setSideChainBasicity(double gb_sc)) Residue copy(*e_ptr); e_ptr->setSideChainBasicity(654.3); TEST_NOT_EQUAL(*e_ptr, copy) END_SECTION START_SECTION(double getSideChainBasicity() const) TEST_REAL_SIMILAR(e_ptr->getSideChainBasicity(), 654.3) END_SECTION START_SECTION(void setBackboneBasicityLeft(double gb_bb_l)) Residue copy(*e_ptr); e_ptr->setBackboneBasicityLeft(123.6); TEST_NOT_EQUAL(*e_ptr, copy) END_SECTION START_SECTION(double getBackboneBasicityLeft() const) TEST_REAL_SIMILAR(e_ptr->getBackboneBasicityLeft(), 123.6) END_SECTION START_SECTION(void setBackboneBasicityRight(double gb_bb_r)) Residue copy(*e_ptr); e_ptr->setBackboneBasicityRight(12345.6); TEST_NOT_EQUAL(*e_ptr, copy) END_SECTION START_SECTION(double getBackboneBasicityRight() const) TEST_REAL_SIMILAR(e_ptr->getBackboneBasicityRight(), 12345.6) END_SECTION START_SECTION(bool isModified() const) { Residue res; res.setOneLetterCode("M"); // we need M for this mod TEST_EQUAL(res.isModified(), false) res.setModification("Oxidation"); TEST_EQUAL(res.isModified(), true) } END_SECTION START_SECTION((void setResidueSets(const std::set< String > &residues_sets))) { set<String> res_sets; res_sets.insert("rs1"); res_sets.insert("rs2"); e_ptr->setResidueSets(res_sets); TEST_EQUAL(res_sets == e_ptr->getResidueSets(), true) } END_SECTION START_SECTION((void addResidueSet(const String &residue_sets))) e_ptr->addResidueSet("rs3"); TEST_EQUAL(e_ptr->getResidueSets().size(), 3) END_SECTION START_SECTION((const std::set<String>& getResidueSets() const)) { set<String> res_sets; res_sets.insert("rs1"); res_sets.insert("rs2"); res_sets.insert("rs3"); TEST_EQUAL(e_ptr->getResidueSets() == res_sets, true) } END_SECTION START_SECTION((bool isInResidueSet(const String &residue_set))) { TEST_EQUAL(e_ptr->isInResidueSet("rs1"), true) TEST_EQUAL(e_ptr->isInResidueSet("rs3"), true) TEST_EQUAL(e_ptr->isInResidueSet("rs4"), false) } END_SECTION START_SECTION((static String getResidueTypeName(const ResidueType res_type))) { TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::Full), "full") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::Internal), "internal") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::NTerminal), "N-terminal") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::CTerminal), "C-terminal") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::AIon), "a-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::BIon), "b-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::CIon), "c-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::XIon), "x-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::YIon), "y-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::ZIon), "z-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::Zp1Ion), "z+1-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::Zp2Ion), "z+2-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::Precursor), "precursor-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::BIonMinusH20), "b-H2O-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::YIonMinusH20), "y-H2O-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::BIonMinusNH3), "b-NH3-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::YIonMinusNH3), "y-NH3-ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::NonIdentified), "Non-identified ion") TEST_STRING_EQUAL(Residue::getResidueTypeName(Residue::Unannotated), "unannotated") TEST_EQUAL(Residue::SizeOfResidueType, Residue::names_of_residuetype.size()); // test that no entries in array are empty (the initializer of std::array<> can have less values than the std::array<>) for (size_t i = 0; i < Residue::names_of_residuetype.size(); ++i) { TEST_FALSE(Residue::getResidueTypeName(static_cast<Residue::ResidueType>(i)).empty()); } } END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // Hash tests ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] std::hash<Residue>)) { // Test 1: Equal objects have equal hashes Residue r1; r1.setName("TestResidue"); r1.setThreeLetterCode("TST"); r1.setOneLetterCode("T"); r1.setFormula(EmpiricalFormula("C4H8N2O3")); r1.setAverageWeight(132.0); r1.setMonoWeight(132.05); r1.setPka(2.1); r1.setPkb(9.0); r1.setPkc(4.5); r1.setSideChainBasicity(200.0); r1.setBackboneBasicityLeft(100.0); r1.setBackboneBasicityRight(110.0); Residue r2; r2.setName("TestResidue"); r2.setThreeLetterCode("TST"); r2.setOneLetterCode("T"); r2.setFormula(EmpiricalFormula("C4H8N2O3")); r2.setAverageWeight(132.0); r2.setMonoWeight(132.05); r2.setPka(2.1); r2.setPkb(9.0); r2.setPkc(4.5); r2.setSideChainBasicity(200.0); r2.setBackboneBasicityLeft(100.0); r2.setBackboneBasicityRight(110.0); TEST_EQUAL(r1 == r2, true) TEST_EQUAL(std::hash<Residue>{}(r1), std::hash<Residue>{}(r2)) // Test 2: Different objects may have different hashes (not guaranteed, but highly likely) Residue r3; r3.setName("DifferentResidue"); r3.setThreeLetterCode("DIF"); r3.setOneLetterCode("D"); r3.setFormula(EmpiricalFormula("C5H9N1O4")); TEST_EQUAL(r1 == r3, false) // Different residues should likely have different hashes (not guaranteed by hash contract) TEST_NOT_EQUAL(std::hash<Residue>{}(r1), std::hash<Residue>{}(r3)) // Test 3: Use in unordered_set std::unordered_set<Residue> residue_set; residue_set.insert(r1); residue_set.insert(r2); // Should not increase size (equal to r1) residue_set.insert(r3); TEST_EQUAL(residue_set.size(), 2) TEST_EQUAL(residue_set.count(r1), 1) TEST_EQUAL(residue_set.count(r2), 1) TEST_EQUAL(residue_set.count(r3), 1) // Test 4: Use in unordered_map std::unordered_map<Residue, int> residue_map; residue_map[r1] = 1; residue_map[r2] = 2; // Should overwrite r1's value residue_map[r3] = 3; TEST_EQUAL(residue_map.size(), 2) TEST_EQUAL(residue_map[r1], 2) TEST_EQUAL(residue_map[r2], 2) TEST_EQUAL(residue_map[r3], 3) // Test 5: Residues from ResidueDB ResidueDB* rdb = ResidueDB::getInstance(); const Residue* ala = rdb->getResidue("Ala"); const Residue* gly = rdb->getResidue("Gly"); const Residue* ala2 = rdb->getResidue("Alanine"); // Same as Ala // Same residue retrieved differently should have equal hash TEST_EQUAL(*ala == *ala2, true) TEST_EQUAL(std::hash<Residue>{}(*ala), std::hash<Residue>{}(*ala2)) // Different residues should likely have different hashes TEST_EQUAL(*ala == *gly, false) TEST_NOT_EQUAL(std::hash<Residue>{}(*ala), std::hash<Residue>{}(*gly)) // Test 6: Copy has same hash Residue r1_copy(r1); TEST_EQUAL(r1 == r1_copy, true) TEST_EQUAL(std::hash<Residue>{}(r1), std::hash<Residue>{}(r1_copy)) // Test 7: Hash changes when fields change std::size_t original_hash = std::hash<Residue>{}(r1_copy); r1_copy.setName("ChangedName"); TEST_NOT_EQUAL(std::hash<Residue>{}(r1_copy), original_hash) } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/NeighborSeq_test.cpp
.cpp
9,064
213
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow, Philipp Wang $ // $Authors: Chris Bielow, Philipp Wang $ // -------------------------------------------------------------------------- #include <OpenMS/FORMAT/FASTAFile.h> #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/ANALYSIS/ID/NeighborSeq.h> #include <vector> using namespace OpenMS; using namespace std; START_TEST(NeighborSeq, "$Id$") // NS()=delete; // Test section for the generateSpectrum function // The spectra were generated via TOPPView and contained b-and y-ion START_SECTION(MSSpectrum generateSpectrum(const String& peptide_sequence)) { NeighborSeq ns({AASequence::fromString("TEST")}); MSSpectrum spec_1 = ns.generateSpectrum(AASequence::fromString("PEPT")); MSSpectrum spec_2 = ns.generateSpectrum(AASequence::fromString("AR")); MSSpectrum spec_3 = ns.generateSpectrum(AASequence::fromString("VGLPINQR")); // Test "PEPT" TEST_REAL_SIMILAR(spec_1[0].getMZ(), 98.0600); TEST_REAL_SIMILAR(spec_1[1].getMZ(), 120.0655); TEST_REAL_SIMILAR(spec_1[2].getMZ(), 217.1182); TEST_REAL_SIMILAR(spec_1[3].getMZ(), 227.1026); TEST_REAL_SIMILAR(spec_1[4].getMZ(), 324.1553); TEST_REAL_SIMILAR(spec_1[5].getMZ(), 346.1608); // Test "AR" TEST_REAL_SIMILAR(spec_2[0].getMZ(), 72.04439); TEST_REAL_SIMILAR(spec_2[1].getMZ(), 175.1189); // Test "VGLPINQR" TEST_REAL_SIMILAR(spec_3[0].getMZ(), 100.0756); TEST_REAL_SIMILAR(spec_3[1].getMZ(), 157.0971); TEST_REAL_SIMILAR(spec_3[2].getMZ(), 175.1189); TEST_REAL_SIMILAR(spec_3[3].getMZ(), 270.1812); TEST_REAL_SIMILAR(spec_3[4].getMZ(), 303.1775); TEST_REAL_SIMILAR(spec_3[5].getMZ(), 367.2339); TEST_REAL_SIMILAR(spec_3[6].getMZ(), 417.2204); TEST_REAL_SIMILAR(spec_3[7].getMZ(), 480.3180); TEST_REAL_SIMILAR(spec_3[8].getMZ(), 530.3045); TEST_REAL_SIMILAR(spec_3[9].getMZ(), 594.3609); TEST_REAL_SIMILAR(spec_3[10].getMZ(), 627.3578); TEST_REAL_SIMILAR(spec_3[11].getMZ(), 722.4195); TEST_REAL_SIMILAR(spec_3[12].getMZ(), 740.4413); TEST_REAL_SIMILAR(spec_3[13].getMZ(), 797.4628); } END_SECTION // Test section for the compareSpectra function START_SECTION( static bool isNeighborSpectrum(const MSSpectrum& spec1, const MSSpectrum& spec2, const double min_shared_ion_fraction, const double mz_bin_size)) { MSSpectrum spec1({Peak1D(100.00, 1.0), Peak1D(200.00, 1.0), Peak1D(300.00, 1.0)}); MSSpectrum spec2({Peak1D(100.05, 1.0), Peak1D(200.05, 1.0), Peak1D(300.05, 1.0)}); MSSpectrum spec3({Peak1D(101.00, 1.0), Peak1D(201.00, 1.0), Peak1D(301.00, 1.0)}); MSSpectrum spec4({Peak1D(100.05, 1.0), Peak1D(201.00, 1.0), Peak1D(300.05, 1.0), Peak1D(301.00, 1.0)}); double min_shared_ion_fraction = 0.5; NeighborSeq ns({AASequence::fromString("TEST")}); // bin interval is from [a,b[ TEST_TRUE (ns.isNeighborSpectrum(spec1, spec2, min_shared_ion_fraction, 1.0)) TEST_FALSE(ns.isNeighborSpectrum(spec1, spec3, min_shared_ion_fraction, 1.0)) TEST_TRUE (ns.isNeighborSpectrum(spec1, spec4, min_shared_ion_fraction, 1.0)) TEST_FALSE(ns.isNeighborSpectrum(spec2, spec3, min_shared_ion_fraction, 1.0)) TEST_TRUE (ns.isNeighborSpectrum(spec2, spec4, min_shared_ion_fraction, 1.0)) TEST_TRUE (ns.isNeighborSpectrum(spec3, spec4, min_shared_ion_fraction, 1.0)) TEST_FALSE(ns.isNeighborSpectrum(spec1, spec2, min_shared_ion_fraction, 0.05)) TEST_FALSE(ns.isNeighborSpectrum(spec1, spec3, min_shared_ion_fraction, 0.05)) TEST_FALSE(ns.isNeighborSpectrum(spec1, spec4, min_shared_ion_fraction, 0.05)) TEST_FALSE(ns.isNeighborSpectrum(spec2, spec3, min_shared_ion_fraction, 0.05)) TEST_TRUE(ns.isNeighborSpectrum(spec2, spec4, min_shared_ion_fraction, 0.05)) TEST_TRUE(ns.isNeighborSpectrum(spec3, spec4, min_shared_ion_fraction, 0.05)) } END_SECTION // Test section for the findCandidatePositions function START_SECTION(static int computeSharedIonCount(const MSSpectrum& spec1, const MSSpectrum& spec2, const double& mz_bin_size)) { MSSpectrum spec1({Peak1D(100.00, 1.0), Peak1D(200.00, 1.0), Peak1D(300.00, 1.0)}); MSSpectrum spec2({Peak1D(100.05, 1.0), Peak1D(200.05, 1.0), Peak1D(300.05, 1.0)}); MSSpectrum spec3({Peak1D(101.00, 1.0), Peak1D(201.00, 1.0), Peak1D(301.00, 1.0)}); MSSpectrum spec4({Peak1D(100.05, 1.0), Peak1D(201.00, 1.0), Peak1D(300.05, 1.0), Peak1D(301.00, 1.0)}); NeighborSeq ns({AASequence::fromString("TEST")}); // bin interval is from [a,b[ TEST_EQUAL(ns.computeSharedIonCount(spec1, spec2, 2.0), 3) TEST_EQUAL(ns.computeSharedIonCount(spec1, spec3, 2.0), 3) TEST_EQUAL(ns.computeSharedIonCount(spec1, spec4, 2.0), 3) TEST_EQUAL(ns.computeSharedIonCount(spec2, spec3, 2.0), 3) TEST_EQUAL(ns.computeSharedIonCount(spec2, spec4, 2.0), 3) TEST_EQUAL(ns.computeSharedIonCount(spec3, spec4, 2.0), 3) TEST_EQUAL(ns.computeSharedIonCount(spec1, spec2, 1.0), 3) TEST_EQUAL(ns.computeSharedIonCount(spec1, spec3, 1.0), 0) TEST_EQUAL(ns.computeSharedIonCount(spec1, spec4, 1.0), 2) TEST_EQUAL(ns.computeSharedIonCount(spec2, spec3, 1.0), 0) TEST_EQUAL(ns.computeSharedIonCount(spec2, spec4, 1.0), 2) TEST_EQUAL(ns.computeSharedIonCount(spec3, spec4, 1.0), 2) TEST_EQUAL(ns.computeSharedIonCount(spec1, spec2, 0.1), 3) TEST_EQUAL(ns.computeSharedIonCount(spec1, spec3, 0.1), 0) TEST_EQUAL(ns.computeSharedIonCount(spec1, spec4, 0.1), 2) TEST_EQUAL(ns.computeSharedIonCount(spec2, spec3, 0.1), 0) TEST_EQUAL(ns.computeSharedIonCount(spec2, spec4, 0.1), 2) TEST_EQUAL(ns.computeSharedIonCount(spec3, spec4, 0.1), 2) } END_SECTION START_SECTION(bool isNeighborPeptide(const AASequence& neighbor_candidate, const double mass_tolerance_pc, const bool mass_tolerance_pc_ppm, const double min_shared_ion_fraction, const double mz_bin_size)) { const AASequence AA_VELQSK = AASequence::fromString("VELQSK"); const AASequence AA_SVQELK = AASequence::fromString("SVQELK"); const AASequence AA_TVDQLK = AASequence::fromString("TVDQLK"); const AASequence AA_VESQLK = AASequence::fromString("VESQLK"); std::vector<AASequence> seqs = {AASequence::fromString("VELQSK"), AASequence::fromString("SVQELK"), AASequence::fromString("TVDQLK"), AASequence::fromString("VGEFK")}; NeighborSeq ns(std::move(seqs)); // VELQSK has neighbor VESQLK // shares 6 ions // SVQELK has neighbor VESQLK // shares 4 ions // TVDQLK has neighbor VESQLK // shares 6 ions // VGEFK has neighbor GLDFK const double pc_tolerance = 0.01; const double mz_bin_size = 0.05; TEST_TRUE(std::abs(AA_VELQSK.getMonoWeight() - AA_VESQLK.getMonoWeight()) < pc_tolerance) TEST_EQUAL(ns.computeSharedIonCount(ns.generateSpectrum(AA_VELQSK), ns.generateSpectrum(AA_VESQLK), mz_bin_size), 6) TEST_EQUAL(ns.computeSharedIonCount(ns.generateSpectrum(AA_SVQELK), ns.generateSpectrum(AA_VESQLK), mz_bin_size), 4) TEST_EQUAL(ns.computeSharedIonCount(ns.generateSpectrum(AA_TVDQLK), ns.generateSpectrum(AA_VESQLK), mz_bin_size), 6) // test the overlap threshold: const double shared_ion_fraction = 6 * 2.0 / ( ((AA_VESQLK.size() - 1) * 2 /*b and y*/) * 2); TEST_FALSE(ns.isNeighborPeptide(AASequence::fromString("VESQLK"), pc_tolerance, false, shared_ion_fraction + 0.1, mz_bin_size)) // VESQLK matches VELQSK and TVDQLK (but not SVQELK since the overlap is insufficient) TEST_TRUE (ns.isNeighborPeptide(AASequence::fromString("VESQLK"), pc_tolerance, false, shared_ion_fraction - 0.1, mz_bin_size)) // GLDFK matches to VGEFK TEST_TRUE(ns.isNeighborPeptide(AASequence::fromString("GLDFK"), pc_tolerance, false, 0.25, mz_bin_size)) auto stats = ns.getNeighborStats(); TEST_EQUAL(stats.unfindable_peptides, 0) TEST_EQUAL(stats.findable_no_neighbors, 1) TEST_EQUAL(stats.findable_one_neighbor, 3) TEST_EQUAL(stats.findable_multiple_neighbors, 0) // test VESQLK again, which is a neighbor for 3 ref peptides at threshold 0.25 TEST_TRUE(ns.isNeighborPeptide(AASequence::fromString("VESQLK"), pc_tolerance, false, 0.25, mz_bin_size)) auto stats2 = ns.getNeighborStats(); TEST_EQUAL(stats2.unfindable_peptides, 0) TEST_EQUAL(stats2.findable_no_neighbors, 0) TEST_EQUAL(stats2.findable_one_neighbor, 2) TEST_EQUAL(stats2.findable_multiple_neighbors, 2) } END_SECTION START_SECTION(NeighborStats getNeighborStats() const) { NOT_TESTABLE // tested above } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/XMLValidator_test.cpp
.cpp
2,177
58
// 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/FORMAT/VALIDATORS/XMLValidator.h> /////////////////////////// START_TEST(XMLValidator, "XMLValidator") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; XMLValidator* ptr = nullptr; XMLValidator* nullPointer = nullptr; START_SECTION((XMLValidator())) ptr = new XMLValidator; TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(([EXTRA]~XMLValidator())) delete ptr; END_SECTION START_SECTION((bool isValid(const String &filename, const String &schema, std::ostream& os = std::cerr) )) XMLValidator v; TEST_EQUAL(v.isValid(OPENMS_GET_TEST_DATA_PATH("XMLValidator_valid.xml"),OPENMS_GET_TEST_DATA_PATH("XMLValidator.xsd")), true); TEST_EQUAL(v.isValid(OPENMS_GET_TEST_DATA_PATH("XMLValidator_missing_element.xml"),OPENMS_GET_TEST_DATA_PATH("XMLValidator.xsd")), false); TEST_EQUAL(v.isValid(OPENMS_GET_TEST_DATA_PATH("XMLValidator_missing_attribute.xml"),OPENMS_GET_TEST_DATA_PATH("XMLValidator.xsd")), false); TEST_EQUAL(v.isValid(OPENMS_GET_TEST_DATA_PATH("XMLValidator_syntax.xml"),OPENMS_GET_TEST_DATA_PATH("XMLValidator.xsd")), false); //check vaild fail again to make sure internal states are ok TEST_EQUAL(v.isValid(OPENMS_GET_TEST_DATA_PATH("XMLValidator_valid.xml"),OPENMS_GET_TEST_DATA_PATH("XMLValidator.xsd")), true); //test exception TEST_EXCEPTION(Exception::FileNotFound, v.isValid(OPENMS_GET_TEST_DATA_PATH("this_file_does_not_exist.for_sure"),OPENMS_GET_TEST_DATA_PATH("XMLValidator.xsd"))); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/OpenSwathScoring_test.cpp
.cpp
22,407
558
// 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 <memory> #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathScoring.h> /////////////////////////// // we don't want any inclusion of OpenMS Kernel classes here ... #ifdef OPENMS_KERNEL_MSSPECTRUM_H ThisShouldFailAtCompileTime = 0 #endif #ifdef OPENMS_KERNEL_MRMFEATURE_H ThisShouldFailAtCompileTime = 0 #endif #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h> #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> using namespace OpenMS; using namespace std; MSSpectrum generateImSpec(int k_min, int k_max, double rt) { MSSpectrum imSpec; DataArrays::FloatDataArray fda; imSpec.setRT(rt); for (int k = k_min; k < k_max; k++) { Peak1D p; p.setMZ(100. + k); p.setIntensity(1.); imSpec.push_back(p); fda.push_back((double) k); fda.setName("Ion Mobility"); } imSpec.getFloatDataArrays().push_back(fda); return imSpec; } START_TEST(OpenSwathScoring, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// OpenSwathScoring* ptr = nullptr; OpenSwathScoring* nullPointer = nullptr; START_SECTION(OpenSwathScoring()) { ptr = new OpenSwathScoring(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~OpenSwathScoring()) { delete ptr; } END_SECTION START_SECTION(( void initialize(double rt_normalization_factor, int add_up_spectra, double spacing_for_spectra_resampling, const OpenSwath_Scores_Usage & su, const std::string& spectrum_addition_method, bool use_ms1_ion_mobility) )) { ptr = new OpenSwathScoring(); OpenSwath_Scores_Usage su; TEST_NOT_EQUAL(ptr, nullPointer) ptr->initialize(100.0, 1, 0.01, 0.20, 0.0, su, "simple", "fixed", true, true); delete ptr; } END_SECTION START_SECTION((void calculateChromatographicScores( OpenSwath::IMRMFeature* imrmfeature, const std::vector<std::string>& native_ids, const std::vector<double>& normalized_library_intensity, std::vector<OpenSwath::ISignalToNoisePtr>& signal_noise_estimators, OpenSwath_Scores & scores) )) { NOT_TESTABLE // see MRMFeatureFinderScoring_test.cpp // - the OpenSwathScoring is a facade and thus does not need testing on its own } END_SECTION START_SECTION((void calculateChromatographicIdScores( OpenSwath::IMRMFeature* imrmfeature, const std::vector<std::string>& native_ids_identification,, const std::vector<std::string>& native_ids_detection, std::vector<OpenSwath::ISignalToNoisePtr>& signal_noise_estimators, OpenSwath_Scores & idscores) )) { NOT_TESTABLE // see MRMFeatureFinderScoring_test.cpp // - the OpenSwathScoring is a facade and thus does not need testing on its own } END_SECTION START_SECTION((void calculateLibraryScores( OpenSwath::IMRMFeature* imrmfeature, const std::vector<TransitionType> & transitions, const PeptideType& pep, const double normalized_feature_rt, OpenSwath_Scores & scores))) { NOT_TESTABLE // see MRMFeatureFinderScoring_test.cpp // - the OpenSwathScoring is a facade and thus does not need testing on its own } END_SECTION START_SECTION((void calculateDIAScores(OpenSwath::IMRMFeature* imrmfeature, const std::vector<TransitionType> & transitions, OpenSwath::SpectrumAccessPtr swath_map, OpenMS::DIAScoring & diascoring, const PeptideType& pep, OpenSwath_Scores & scores))) { NOT_TESTABLE // see MRMFeatureFinderScoring_test.cpp // - the OpenSwathScoring is a facade and thus does not need testing on its own } END_SECTION START_SECTION((void getNormalized_library_intensities_(const std::vector<TransitionType> & transitions, std::vector<double>& normalized_library_intensity))) { NOT_TESTABLE // see MRMFeatureFinderScoring_test.cpp // - the OpenSwathScoring is a facade and thus does not need testing on its own } END_SECTION START_SECTION((OpenSwath::SpectrumPtr OpenSwathScoring::fetchSpectrumSwath(std::vector<OpenSwath::SwathMap> swath_maps, double RT, int nr_spectra_to_add, RangeMobility im_range))) { OpenMS::RangeMobility im_range_empty; // use this empty im range as input for all examples // test result for empty map { std::shared_ptr<PeakMap > swath_map (new PeakMap); OpenSwath::SpectrumAccessPtr swath_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_map); OpenSwathScoring sc; std::vector<OpenSwath::SpectrumPtr> sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 1, im_range_empty); TEST_EQUAL(sp.empty(), true); } // test result for map with single spectrum { PeakMap* eptr = new PeakMap; MSSpectrum s; Peak1D p; p.setMZ(20.0); p.setIntensity(200.0); s.push_back(p); s.setRT(20.0); eptr->addSpectrum(s); std::shared_ptr<PeakMap > swath_map (eptr); OpenSwath::SpectrumAccessPtr swath_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_map); TEST_EQUAL(swath_ptr->getNrSpectra(), 1) OpenSwathScoring sc; OpenSwath_Scores_Usage su; sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "resample", "fixed", true, true); std::vector<OpenSwath::SpectrumPtr> sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 1, im_range_empty); TEST_EQUAL(sp.size(), 1); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 1); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 1); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 20.0); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 200.0); sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "simple", "fixed", true, true); sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 1, im_range_empty); TEST_EQUAL(sp.size(), 1); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 1); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 1); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 20.0); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 200.0); // delete eptr; } // test result for map with three spectra { PeakMap* eptr = new PeakMap; MSSpectrum s; Peak1D p; p.setMZ(20.0); p.setIntensity(200.0); s.push_back(p); s.setRT(10.0); eptr->addSpectrum(s); s.setRT(20.0); eptr->addSpectrum(s); s.setRT(30.0); eptr->addSpectrum(s); std::shared_ptr<PeakMap > swath_map (eptr); OpenSwath::SpectrumAccessPtr swath_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_map); TEST_EQUAL(swath_ptr->getNrSpectra(), 3) OpenSwathScoring sc; OpenSwath_Scores_Usage su; sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "resample", "fixed", true, true); std::vector<OpenSwath::SpectrumPtr> sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 3, im_range_empty); TEST_EQUAL(sp.size(), 1); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 1); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 1); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 20.0); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 600.0); sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "simple", "fixed", true, true); sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 3, im_range_empty); TEST_EQUAL(sp.size(), 3); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 1); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 1); TEST_EQUAL(sp[1]->getMZArray()->data.size(), 1); TEST_EQUAL(sp[1]->getIntensityArray()->data.size(), 1); TEST_EQUAL(sp[2]->getMZArray()->data.size(), 1); TEST_EQUAL(sp[2]->getIntensityArray()->data.size(), 1); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 20.0); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 200.0); TEST_REAL_SIMILAR(sp[1]->getMZArray()->data[0], 20.0); TEST_REAL_SIMILAR(sp[1]->getIntensityArray()->data[0], 200.0); TEST_REAL_SIMILAR(sp[2]->getMZArray()->data[0], 20.0); TEST_REAL_SIMILAR(sp[2]->getIntensityArray()->data[0], 200.0); // delete eptr; } // test result for map with uneven number of spectra { PeakMap* eptr = new PeakMap; { MSSpectrum s; s.emplace_back(20.0, 200.0); s.setRT(10.0); eptr->addSpectrum(s); } { MSSpectrum s; s.emplace_back(20.001, 200.0); s.setRT(20.0); eptr->addSpectrum(s); } { MSSpectrum s; s.emplace_back(250.001, 300.0); s.setRT(50.0); eptr->addSpectrum(s); } { MSSpectrum s; s.emplace_back(250.002, 500.0); s.setRT(60.0); eptr->addSpectrum(s); } std::shared_ptr<PeakMap > swath_map (eptr); OpenSwath::SpectrumAccessPtr swath_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_map); TEST_EQUAL(swath_ptr->getNrSpectra(), 4) OpenSwathScoring sc; OpenSwath_Scores_Usage su; sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "resample", "fixed", true, true); std::vector<OpenSwath::SpectrumPtr> sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 3, im_range_empty); TEST_EQUAL(sp.size(), 1); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 3); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 3); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 20.0); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 360.0); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[1], 20.005); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[1], 40.0); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[2], 250.0); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[2], 300.0); // in simple method all 3 spectra should be returned sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "simple", "fixed", true, true); sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 3, im_range_empty); TEST_EQUAL(sp.size(), 3); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 1); TEST_EQUAL(sp[1]->getMZArray()->data.size(), 1); TEST_EQUAL(sp[2]->getMZArray()->data.size(), 1); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 1); TEST_EQUAL(sp[1]->getIntensityArray()->data.size(), 1); TEST_EQUAL(sp[2]->getIntensityArray()->data.size(), 1); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 20.001); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 200.0); TEST_REAL_SIMILAR(sp[1]->getMZArray()->data[0], 20.0); TEST_REAL_SIMILAR(sp[1]->getIntensityArray()->data[0], 200.0); TEST_REAL_SIMILAR(sp[2]->getMZArray()->data[0], 250.0); TEST_REAL_SIMILAR(sp[2]->getIntensityArray()->data[0], 300.0); } } END_SECTION START_SECTION((OpenSwath::SpectrumPtr OpenSwathScoring::fetchSpectrumSwath(std::vector<OpenSwath::SwathMap> swath_maps, double RT, int nr_spectra_to_add, RangeMobility im_range))- extra) { // im range from 2-4 OpenMS::RangeMobility im_range(3); // use this empty im range as input for all examples im_range.minSpanIfSingular(2); // // test result for map with single spectrum, should filter by IM because resampling is set { PeakMap* eptr = new PeakMap; eptr->addSpectrum(generateImSpec(1,6,20.0)); std::shared_ptr<PeakMap > swath_map (eptr); OpenSwath::SpectrumAccessPtr swath_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_map); TEST_EQUAL(swath_ptr->getNrSpectra(), 1); OpenSwathScoring sc; OpenSwath_Scores_Usage su; // test resample - IM filtering should occur { sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "resample", "fixed", true, true); SpectrumSequence sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 1, im_range); TEST_EQUAL(sp.size(), 1); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 3); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 3); TEST_EQUAL(sp[0]->getDriftTimeArray()->data.size(), 3); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 102.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[1], 103.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[2], 104.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[1], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[2], 1.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[0], 2.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[1], 3.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[2], 4.); } // test simple, since downstream functions are IM aware no filtering needs to occur. { sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "simple", "fixed", true, true); SpectrumSequence sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 1, im_range); TEST_EQUAL(sp.size(), 1); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 5); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 5); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 101.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[1], 102.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[2], 103.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[3], 104.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[4], 105.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[1], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[2], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[3], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[4], 1.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[1], 2.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[2], 3.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[3], 4.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[4], 5.); } // delete eptr; } // Test result for 3 spectra { PeakMap* eptr = new PeakMap; eptr->addSpectrum(generateImSpec(1,3,19.0)); eptr->addSpectrum(generateImSpec(1,6,20.0)); eptr->addSpectrum(generateImSpec(3,6,21.0)); std::shared_ptr<PeakMap > swath_map (eptr); OpenSwath::SpectrumAccessPtr swath_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_map); TEST_EQUAL(swath_ptr->getNrSpectra(), 3); OpenSwathScoring sc; OpenSwath_Scores_Usage su; // test resample - IM filtering should occur, also IM information is not needed so is cleared { sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "resample", "fixed", true, true); SpectrumSequence sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 3, im_range); TEST_EQUAL(sp.size(), 1); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 3); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 3); TEST_TRUE( (sp[0]->getDriftTimeArray() == nullptr ) ); // for resampling we do not use IM array TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 102.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[1], 103.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[2], 104.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 2.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[1], 2.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[2], 2.); } // test simple, since downstream functions are IM aware no filtering needs to occur. Should just return all the original spectra { sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "simple", "fixed", true, true); SpectrumSequence sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 3, im_range); //test sizing TEST_EQUAL(sp.size(), 3); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 5); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 5); TEST_EQUAL(sp[0]->getDriftTimeArray()->data.size(), 5); TEST_EQUAL(sp[1]->getMZArray()->data.size(), 2); TEST_EQUAL(sp[1]->getIntensityArray()->data.size(), 2); TEST_EQUAL(sp[1]->getDriftTimeArray()->data.size(), 2); TEST_EQUAL(sp[2]->getMZArray()->data.size(), 3); TEST_EQUAL(sp[2]->getIntensityArray()->data.size(), 3); TEST_EQUAL(sp[2]->getDriftTimeArray()->data.size(), 3); // Spectrum #1 TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 101.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[1], 102.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[2], 103.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[3], 104.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[4], 105.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[1], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[2], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[3], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[4], 1.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[1], 2.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[2], 3.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[3], 4.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[4], 5.); // Spectrum #2 TEST_REAL_SIMILAR(sp[1]->getMZArray()->data[0], 101.); TEST_REAL_SIMILAR(sp[1]->getMZArray()->data[1], 102.); TEST_REAL_SIMILAR(sp[1]->getIntensityArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[1]->getIntensityArray()->data[1], 1.); TEST_REAL_SIMILAR(sp[1]->getDriftTimeArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[1]->getDriftTimeArray()->data[1], 2.); // Spectrum #3 TEST_REAL_SIMILAR(sp[2]->getMZArray()->data[0], 103.); TEST_REAL_SIMILAR(sp[2]->getMZArray()->data[1], 104.); TEST_REAL_SIMILAR(sp[2]->getIntensityArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[2]->getIntensityArray()->data[1], 1.); TEST_REAL_SIMILAR(sp[2]->getDriftTimeArray()->data[0], 3.); TEST_REAL_SIMILAR(sp[2]->getDriftTimeArray()->data[1], 4.); } // delete eptr; } // test result for map with 4 spectra (select 3) { PeakMap* eptr = new PeakMap; eptr->addSpectrum(generateImSpec(1,3,19.0)); eptr->addSpectrum(generateImSpec(1,6,20.0)); eptr->addSpectrum(generateImSpec(3,6,21.0)); eptr->addSpectrum(generateImSpec(1,6,250)); std::shared_ptr<PeakMap > swath_map (eptr); OpenSwath::SpectrumAccessPtr swath_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_map); TEST_EQUAL(swath_ptr->getNrSpectra(), 4); OpenSwathScoring sc; OpenSwath_Scores_Usage su; // Test resampling, IM filtering should occur and the 4th spectrum should not be selected { sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "resample", "fixed", true, true); SpectrumSequence sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 3, im_range); TEST_EQUAL(sp.size(), 1); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 3); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 3); TEST_TRUE( (sp[0]->getDriftTimeArray() == nullptr ) ); // for resampling we do not use IM array TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 102.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[1], 103.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[2], 104.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 2.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[1], 2.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[2], 2.); } // test simple, since downstream functions are IM aware no filtering needs to occur. Should just return all the original spectra, but the 4th spectrum should not be selected { sc.initialize(1.0, 1, 0.005, 0.20, 0.0, su, "simple", "fixed", true, true); SpectrumSequence sp = sc.fetchSpectrumSwath(swath_ptr, 20.0, 3, im_range); //test sizing TEST_EQUAL(sp.size(), 3); TEST_EQUAL(sp[0]->getMZArray()->data.size(), 5); TEST_EQUAL(sp[0]->getIntensityArray()->data.size(), 5); TEST_EQUAL(sp[0]->getDriftTimeArray()->data.size(), 5); TEST_EQUAL(sp[1]->getMZArray()->data.size(), 2); TEST_EQUAL(sp[1]->getIntensityArray()->data.size(), 2); TEST_EQUAL(sp[1]->getDriftTimeArray()->data.size(), 2); TEST_EQUAL(sp[2]->getMZArray()->data.size(), 3); TEST_EQUAL(sp[2]->getIntensityArray()->data.size(), 3); TEST_EQUAL(sp[2]->getDriftTimeArray()->data.size(), 3); // Spectrum #1 TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[0], 101.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[1], 102.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[2], 103.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[3], 104.); TEST_REAL_SIMILAR(sp[0]->getMZArray()->data[4], 105.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[1], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[2], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[3], 1.); TEST_REAL_SIMILAR(sp[0]->getIntensityArray()->data[4], 1.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[1], 2.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[2], 3.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[3], 4.); TEST_REAL_SIMILAR(sp[0]->getDriftTimeArray()->data[4], 5.); // Spectrum #2 TEST_REAL_SIMILAR(sp[1]->getMZArray()->data[0], 101.); TEST_REAL_SIMILAR(sp[1]->getMZArray()->data[1], 102.); TEST_REAL_SIMILAR(sp[1]->getIntensityArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[1]->getIntensityArray()->data[1], 1.); TEST_REAL_SIMILAR(sp[1]->getDriftTimeArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[1]->getDriftTimeArray()->data[1], 2.); // Spectrum #3 TEST_REAL_SIMILAR(sp[2]->getMZArray()->data[0], 103.); TEST_REAL_SIMILAR(sp[2]->getMZArray()->data[1], 104.); TEST_REAL_SIMILAR(sp[2]->getIntensityArray()->data[0], 1.); TEST_REAL_SIMILAR(sp[2]->getIntensityArray()->data[1], 1.); TEST_REAL_SIMILAR(sp[2]->getDriftTimeArray()->data[0], 3.); TEST_REAL_SIMILAR(sp[2]->getDriftTimeArray()->data[1], 4.); } // delete eptr; } } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConsensusMapNormalizerAlgorithmMedian_test.cpp
.cpp
1,524
63
// 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/ANALYSIS/MAPMATCHING/ConsensusMapNormalizerAlgorithmMedian.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ConsensusMapNormalizerAlgorithmMedian, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ConsensusMapNormalizerAlgorithmMedian* ptr = nullptr; ConsensusMapNormalizerAlgorithmMedian* null_ptr = nullptr; START_SECTION(ConsensusMapNormalizerAlgorithmMedian()) { ptr = new ConsensusMapNormalizerAlgorithmMedian(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~ConsensusMapNormalizerAlgorithmMedian()) { delete ptr; } END_SECTION START_SECTION((virtual ~ConsensusMapNormalizerAlgorithmMedian())) { // TODO } END_SECTION START_SECTION((static void normalizeMaps(ConsensusMap &map))) { // TODO } END_SECTION START_SECTION((static std::vector<double> computeNormalizationFactors(const ConsensusMap &map))) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MatrixEigen_test.cpp
.cpp
6,752
270
// 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> /////////////////////////// // This tests the internal MatrixEigen utilities. // NOTE: MatrixEigen.h is an internal header not part of the public API. #include <OpenMS/DATASTRUCTURES/MatrixEigen.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MatrixEigen, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION((eigenView - mutable Matrix)) { // Create a 3x4 matrix with distinct values Matrix<double> mat(3, 4, 0.0); for (Size i = 0; i < 3; ++i) { for (Size j = 0; j < 4; ++j) { mat(i, j) = static_cast<double>(i * 10 + j); } } // Get mutable Eigen view auto view = eigenView(mat); // Test dimensions TEST_EQUAL(view.rows(), 3) TEST_EQUAL(view.cols(), 4) // Test that view sees correct values for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) { TEST_REAL_SIMILAR(view(i, j), static_cast<double>(i * 10 + j)) } } // Test zero-copy: modify through view, check original view(1, 2) = 999.0; TEST_REAL_SIMILAR(mat(1, 2), 999.0) // Test zero-copy: modify original, check view mat(0, 3) = 888.0; TEST_REAL_SIMILAR(view(0, 3), 888.0) } END_SECTION START_SECTION((eigenView - const Matrix)) { Matrix<double> mat(2, 3, 0.0); mat(0, 0) = 1.0; mat(0, 1) = 2.0; mat(0, 2) = 3.0; mat(1, 0) = 4.0; mat(1, 1) = 5.0; mat(1, 2) = 6.0; const Matrix<double>& const_mat = mat; auto view = eigenView(const_mat); // Test dimensions TEST_EQUAL(view.rows(), 2) TEST_EQUAL(view.cols(), 3) // Test values TEST_REAL_SIMILAR(view(0, 0), 1.0) TEST_REAL_SIMILAR(view(0, 1), 2.0) TEST_REAL_SIMILAR(view(0, 2), 3.0) TEST_REAL_SIMILAR(view(1, 0), 4.0) TEST_REAL_SIMILAR(view(1, 1), 5.0) TEST_REAL_SIMILAR(view(1, 2), 6.0) } END_SECTION START_SECTION((eigenVectorView - mutable std::vector)) { std::vector<double> vec = {1.0, 2.0, 3.0, 4.0, 5.0}; auto view = eigenVectorView(vec); // Test size TEST_EQUAL(view.size(), 5) // Test values for (int i = 0; i < 5; ++i) { TEST_REAL_SIMILAR(view(i), static_cast<double>(i + 1)) } // Test zero-copy: modify through view view(2) = 99.0; TEST_REAL_SIMILAR(vec[2], 99.0) // Test zero-copy: modify original vec[4] = 88.0; TEST_REAL_SIMILAR(view(4), 88.0) } END_SECTION START_SECTION((eigenVectorView - const std::vector)) { const std::vector<double> vec = {10.0, 20.0, 30.0}; auto view = eigenVectorView(vec); TEST_EQUAL(view.size(), 3) TEST_REAL_SIMILAR(view(0), 10.0) TEST_REAL_SIMILAR(view(1), 20.0) TEST_REAL_SIMILAR(view(2), 30.0) } END_SECTION START_SECTION((eigenVectorView - raw pointer mutable)) { double data[4] = {1.5, 2.5, 3.5, 4.5}; auto view = eigenVectorView(data, 4); TEST_EQUAL(view.size(), 4) TEST_REAL_SIMILAR(view(0), 1.5) TEST_REAL_SIMILAR(view(3), 4.5) // Zero-copy test view(1) = 100.0; TEST_REAL_SIMILAR(data[1], 100.0) } END_SECTION START_SECTION((eigenVectorView - raw pointer const)) { const double data[3] = {7.0, 8.0, 9.0}; auto view = eigenVectorView(data, 3); TEST_EQUAL(view.size(), 3) TEST_REAL_SIMILAR(view(0), 7.0) TEST_REAL_SIMILAR(view(1), 8.0) TEST_REAL_SIMILAR(view(2), 9.0) } END_SECTION START_SECTION((eigenMatrixView - raw pointer mutable)) { // Column-major storage: 2x3 matrix // Layout: [col0_row0, col0_row1, col1_row0, col1_row1, col2_row0, col2_row1] double data[6] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0}; auto view = eigenMatrixView(data, 2, 3); TEST_EQUAL(view.rows(), 2) TEST_EQUAL(view.cols(), 3) // Column-major: data[0]=mat(0,0), data[1]=mat(1,0), data[2]=mat(0,1), etc. TEST_REAL_SIMILAR(view(0, 0), 1.0) TEST_REAL_SIMILAR(view(1, 0), 2.0) TEST_REAL_SIMILAR(view(0, 1), 3.0) TEST_REAL_SIMILAR(view(1, 1), 4.0) TEST_REAL_SIMILAR(view(0, 2), 5.0) TEST_REAL_SIMILAR(view(1, 2), 6.0) // Zero-copy test view(1, 1) = 999.0; TEST_REAL_SIMILAR(data[3], 999.0) // col1_row1 is at index 3 } END_SECTION START_SECTION((eigenMatrixView - raw pointer const)) { const double data[4] = {10.0, 20.0, 30.0, 40.0}; auto view = eigenMatrixView(data, 2, 2); TEST_EQUAL(view.rows(), 2) TEST_EQUAL(view.cols(), 2) TEST_REAL_SIMILAR(view(0, 0), 10.0) TEST_REAL_SIMILAR(view(1, 0), 20.0) TEST_REAL_SIMILAR(view(0, 1), 30.0) TEST_REAL_SIMILAR(view(1, 1), 40.0) } END_SECTION START_SECTION((Eigen operations on views)) { // Test that Eigen operations work correctly on views Matrix<double> mat(3, 3, 0.0); mat(0, 0) = 1.0; mat(0, 1) = 0.0; mat(0, 2) = 0.0; mat(1, 0) = 0.0; mat(1, 1) = 2.0; mat(1, 2) = 0.0; mat(2, 0) = 0.0; mat(2, 1) = 0.0; mat(2, 2) = 3.0; auto view = eigenView(mat); // Test isIdentity (should be false, it's diagonal but not identity) TEST_EQUAL(view.isIdentity(0.0), false) // Test isDiagonal TEST_EQUAL(view.isDiagonal(0.0), true) // Test sum TEST_REAL_SIMILAR(view.sum(), 6.0) // Test trace TEST_REAL_SIMILAR(view.trace(), 6.0) // Test matrix-vector multiplication std::vector<double> vec = {1.0, 1.0, 1.0}; auto vec_view = eigenVectorView(vec); Eigen::VectorXd result = view * vec_view; TEST_REAL_SIMILAR(result(0), 1.0) TEST_REAL_SIMILAR(result(1), 2.0) TEST_REAL_SIMILAR(result(2), 3.0) } END_SECTION START_SECTION((Matrix and view consistency with column-major storage)) { // Verify that OpenMS Matrix and Eigen view agree on element positions Matrix<double> mat(3, 4, 0.0); // Fill via Matrix interface for (Size i = 0; i < 3; ++i) { for (Size j = 0; j < 4; ++j) { mat(i, j) = static_cast<double>(i * 100 + j); } } auto view = eigenView(mat); // Both should agree on all elements for (Size i = 0; i < 3; ++i) { for (Size j = 0; j < 4; ++j) { double expected = static_cast<double>(i * 100 + j); TEST_REAL_SIMILAR(mat(i, j), expected) TEST_REAL_SIMILAR(view(i, j), expected) } } // Modify via Eigen, verify via Matrix view(2, 3) = 12345.0; TEST_REAL_SIMILAR(mat(2, 3), 12345.0) // Modify via Matrix, verify via Eigen mat(0, 0) = 54321.0; TEST_REAL_SIMILAR(view(0, 0), 54321.0) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/UnimodXMLFile_test.cpp
.cpp
2,033
69
// 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/DATASTRUCTURES/String.h> #include <OpenMS/FORMAT/UnimodXMLFile.h> #include <OpenMS/CHEMISTRY/ResidueModification.h> #include <vector> /////////////////////////// START_TEST(UnimodXMLFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; UnimodXMLFile xml_file; UnimodXMLFile* ptr; UnimodXMLFile* nullPointer = nullptr; START_SECTION((UnimodXMLFile())) ptr = new UnimodXMLFile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~UnimodXMLFile()) delete ptr; END_SECTION ptr = new UnimodXMLFile(); START_SECTION(void load(const String& filename, vector<ResidueModification*>& modifications)) vector<ResidueModification*> modifications; ptr->load("CHEMISTRY/unimod.xml", modifications); //cerr << "#modifications read: " << modifications.size() << endl; //for (vector<ResidueModification>::const_iterator it = modifications.begin(); it != modifications.end(); ++it) //{ // cerr << it->getTitle() << "\t" << it->getFullName() << "\t" << it->getAllowedPositionName() << "\t" << it->getSite() << "\t" << it->getClassification() << "\t" << it->getComposition() << "\t" << it->getMonoMass() << endl; //} TEST_EQUAL(modifications.size() > 1, true) // cleanup for (Size k = 0; k < modifications.size(); k++) { delete modifications[k]; } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BinnedSpectrum_test.cpp
.cpp
5,923
191
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Timo Sachsenberg$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/KERNEL/BinnedSpectrum.h> /////////////////////////// #include <Eigen/Sparse> #include <OpenMS/FORMAT/DTAFile.h> using namespace OpenMS; using namespace std; /// typedef for the index into the sparse vector using SparseVectorIndexType = Eigen::SparseVector<float>::Index; /// typedef for the index into the sparse vector using SparseVectorIteratorType = Eigen::SparseVector<float>::InnerIterator; START_TEST(BinnedSpectrum, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// BinnedSpectrum* ptr = nullptr; BinnedSpectrum* nullPointer = nullptr; START_SECTION(~BinnedSpectrum()) { delete ptr; } END_SECTION BinnedSpectrum* bs1; DTAFile dtafile; PeakSpectrum s1; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); START_SECTION((BinnedSpectrum(const PeakSpectrum & ps, float size, UInt spread, float offset))) { bs1 = new BinnedSpectrum(s1, 1.5, false, 2, 0.0); TEST_NOT_EQUAL(bs1, nullPointer) } END_SECTION START_SECTION((BinnedSpectrum(const BinnedSpectrum &source))) { BinnedSpectrum copy(*bs1); TEST_EQUAL(copy.getBinSize(), bs1->getBinSize()); TEST_EQUAL(copy.getPrecursors().size(), 1); TEST_EQUAL(bs1->getPrecursors().size(), 1); TEST_EQUAL((UInt)copy.getPrecursors()[0].getMZ(),(UInt)bs1->getPrecursors()[0].getMZ()); } END_SECTION START_SECTION((BinnedSpectrum& operator=(const BinnedSpectrum &source))) { BinnedSpectrum copy(*bs1); delete bs1; bs1 = new BinnedSpectrum(s1, 1.5, false, 2, 0.0); TEST_EQUAL(copy.getBinSize(), bs1->getBinSize()); TEST_EQUAL((UInt)copy.getPrecursors()[0].getMZ(),(UInt)bs1->getPrecursors()[0].getMZ()); } END_SECTION START_SECTION((bool operator==(const BinnedSpectrum &rhs) const )) { BinnedSpectrum copy = *bs1; TEST_EQUAL((*bs1 == copy), true) } END_SECTION START_SECTION((bool operator!=(const BinnedSpectrum &rhs) const )) { BinnedSpectrum copy = *bs1; TEST_EQUAL((*bs1!=copy),false) } END_SECTION START_SECTION((float getBinSize() const )) { TEST_EQUAL(bs1->getBinSize(),1.5) } END_SECTION START_SECTION((UInt getBinSpread() const )) { TEST_EQUAL(bs1->getBinSpread(),2) } END_SECTION delete bs1; START_SECTION((SparseVectorIndexType getBinIndex(double mz) const)) { bs1 = new BinnedSpectrum(s1, 10, true, 0, 0.0); // 10 ppm bins TEST_EQUAL(bs1->getBinIndex(1.0), 0); TEST_EQUAL(bs1->getBinIndex(10.0), 230259); TEST_EQUAL(bs1->getBinIndex(100.0), 460519); TEST_EQUAL(bs1->getBinIndex(1000.0), 690778); delete bs1; } END_SECTION START_SECTION((float getBinLowerMZ(size_t i) const)) { bs1 = new BinnedSpectrum(s1, 10, true, 0, 0); // 10 ppm bins TEST_REAL_SIMILAR(bs1->getBinLowerMZ(0), 1); // m/z = 1 corresponds to lowest index TEST_REAL_SIMILAR(bs1->getBinLowerMZ(1), 1 + 10 * 1e-6); // (1 + 10 ppm) TEST_REAL_SIMILAR(bs1->getBinLowerMZ(1000), pow(1 + 10 * 1e-6, 1000)); TEST_REAL_SIMILAR(bs1->getBinLowerMZ(bs1->getBinIndex(1.0)), 1); TEST_REAL_SIMILAR(bs1->getBinLowerMZ(bs1->getBinIndex(10.0)), 10.0); TEST_REAL_SIMILAR(bs1->getBinLowerMZ(bs1->getBinIndex(100.0)), 100.0); TEST_REAL_SIMILAR(bs1->getBinLowerMZ(bs1->getBinIndex(1000.0)), 1000.0); delete bs1; BinnedSpectrum* bs2 = new BinnedSpectrum(s1, 1.0, false, 0, 0.5); // 1.0 m/z bins with 0.5 offset // offset ensures that floats close to nominal masses fall into same bin TEST_EQUAL(bs2->getBinIndex(999.99), bs2->getBinIndex(1000.01)); TEST_EQUAL(bs2->getBinIndex(99.99), bs2->getBinIndex(100.01)); TEST_EQUAL(bs2->getBinIndex(9.99), bs2->getBinIndex(10.01)); TEST_EQUAL(bs2->getBinIndex(0.99), bs2->getBinIndex(1.01)); TEST_EQUAL(bs2->getBinIndex(0), bs2->getBinIndex(0.01)); TEST_REAL_SIMILAR(bs2->getBinLowerMZ(0), -0.5); // because of offset, bin starts at -0.5 TEST_REAL_SIMILAR(bs2->getBinLowerMZ(1), 0.5); TEST_REAL_SIMILAR(bs2->getBinLowerMZ(1000), 999.5); TEST_REAL_SIMILAR(bs2->getBinLowerMZ(bs2->getBinIndex(0.5)), 0.5); TEST_REAL_SIMILAR(bs2->getBinLowerMZ(bs2->getBinIndex(9.5)), 9.5); TEST_REAL_SIMILAR(bs2->getBinLowerMZ(bs2->getBinIndex(99.5)), 99.5); TEST_REAL_SIMILAR(bs2->getBinLowerMZ(bs2->getBinIndex(999.5)), 999.5); delete bs2; } END_SECTION START_SECTION((const SparseVectorType* getBins() const)) { bs1 = new BinnedSpectrum(s1, 1.5, false, 2, 0); // count non-zero elements before access TEST_EQUAL(bs1->getBins()->nonZeros(), 347) // access by bin index TEST_EQUAL(bs1->getBins()->coeffRef(658), 501645) // check if number of non-zero elements is still the same TEST_EQUAL(bs1->getBins()->nonZeros(), 347) // some additional tests for the underlying Eigen SparseVector UInt c = 0; for (SparseVectorIteratorType it(*bs1->getBins()); it; ++it) { ++c; } TEST_EQUAL(bs1->getBins()->nonZeros(), c) } END_SECTION START_SECTION((SparseVectorType* getBins())) { TEST_EQUAL(bs1->getBins()->coeffRef(658),501645) } END_SECTION START_SECTION((void setBinning())) { NOT_TESTABLE //tested within another test } END_SECTION // static START_SECTION((bool BinnedSpectrum::isCompatible(const BinnedSpectrum& a, const BinnedSpectrum& b))) { BinnedSpectrum bs2(s1, 1.234, false, 2, 0.0); TEST_EQUAL(BinnedSpectrum::isCompatible(*bs1, bs2), false) TEST_EQUAL(BinnedSpectrum::isCompatible(*bs1, *bs1), true) } END_SECTION delete bs1; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FeatureGroupingAlgorithm_test.cpp
.cpp
3,660
122
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm, Clemens Groepl $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithm.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmLabeled.h> #include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmUnlabeled.h> #include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmKD.h> using namespace OpenMS; using namespace std; namespace OpenMS { class FGA : public FeatureGroupingAlgorithm { public: void group(const vector< FeatureMap >&, ConsensusMap& map) override { map.getColumnHeaders()[0].filename = "bla"; map.getColumnHeaders()[0].size = 5; } }; } START_TEST(FeatureGroupingAlgorithm, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FGA* ptr = nullptr; FGA* nullPointer = nullptr; START_SECTION((FeatureGroupingAlgorithm())) ptr = new FGA(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~FeatureGroupingAlgorithm())) delete ptr; END_SECTION START_SECTION((virtual void group(const vector< FeatureMap > &maps, ConsensusMap &out)=0)) FGA fga; vector< FeatureMap > in; ConsensusMap map; fga.group(in,map); TEST_EQUAL(map.getColumnHeaders()[0].filename, "bla") END_SECTION START_SECTION((void transferSubelements(const vector<ConsensusMap>& maps, ConsensusMap& out) const)) { vector<ConsensusMap> maps(2); maps[0].getColumnHeaders()[0].filename = "file1"; maps[0].getColumnHeaders()[0].size = 1; maps[0].getColumnHeaders()[1].filename = "file2"; maps[0].getColumnHeaders()[1].size = 1; maps[1].getColumnHeaders()[0].filename = "file3"; maps[1].getColumnHeaders()[0].size = 1; maps[1].getColumnHeaders()[1].filename = "file4"; maps[1].getColumnHeaders()[1].size = 1; Feature feat1, feat2, feat3, feat4; FeatureHandle handle1(0, feat1), handle2(1, feat2), handle3(0, feat3), handle4(1, feat4); maps[0].resize(1); maps[0][0].insert(handle1); maps[0][0].insert(handle2); maps[0][0].setUniqueId(1); maps[1].resize(1); maps[1][0].insert(handle3); maps[1][0].insert(handle4); maps[1][0].setUniqueId(2); ConsensusMap out; FeatureHandle handle5(0, static_cast<BaseFeature>(maps[0][0])); FeatureHandle handle6(1, static_cast<BaseFeature>(maps[1][0])); out.resize(1); out[0].insert(handle5); out[0].insert(handle6); // need an instance of FeatureGroupingAlgorithm: FeatureGroupingAlgorithm* algo = new FeatureGroupingAlgorithmKD(); algo->transferSubelements(maps, out); TEST_EQUAL(out.getColumnHeaders().size(), 4); TEST_EQUAL(out.getColumnHeaders()[0].filename, "file1"); TEST_EQUAL(out.getColumnHeaders()[3].filename, "file4"); TEST_EQUAL(out.size(), 1); TEST_EQUAL(out[0].size(), 4); ConsensusFeature::HandleSetType group = out[0].getFeatures(); ConsensusFeature::HandleSetType::const_iterator it = group.begin(); handle3.setMapIndex(2); handle4.setMapIndex(3); TEST_EQUAL(*it++ == handle1, true); TEST_EQUAL(*it++ == handle2, true); TEST_EQUAL(*it++ == handle3, true); TEST_EQUAL(*it++ == handle4, true); delete algo; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TriqlerFile_test.cpp
.cpp
1,102
30
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Lukas Heumos $ // $Authors: Lukas Heumos $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/TriqlerFile.h> using namespace OpenMS; START_TEST(MSstatsFile, "$Id$") START_SECTION(void OpenMS::TriqlerFile::storeLFQ( const OpenMS::String &filename, ConsensusMap &consensus_map, const OpenMS::ExperimentalDesign& design, const StringList& reannotate_filenames, const String& condition, const String& retention_time_summarization_method)) { // tested via TriqlerConverter tool } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/XTandemXMLFile_test.cpp
.cpp
2,592
70
// 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/FORMAT/XTandemXMLFile.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <vector> /////////////////////////// START_TEST(XTandemXMLFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; XTandemXMLFile* ptr; XTandemXMLFile* nullPointer = nullptr; ProteinIdentification protein_identification; PeptideIdentificationList peptide_identifications; START_SECTION((XTandemXMLFile())) ptr = new XTandemXMLFile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~XTandemXMLFile()) delete ptr; END_SECTION XTandemXMLFile xml_file; START_SECTION(void load(const String& filename, ProteinIdentification& protein_identification, PeptideIdentificationList& id_data, ModificationDefinitionsSet& mod_def_set)) { ModificationDefinitionsSet mod_set(ListUtils::create<String>(""), ListUtils::create<String>("Carbamidomethyl (C),Oxidation (M),Carboxymethyl (C)")); xml_file.load(OPENMS_GET_TEST_DATA_PATH("XTandemXMLFile_test.xml"), protein_identification, peptide_identifications, mod_set); TEST_EQUAL(peptide_identifications.size(), 303); TEST_EQUAL(protein_identification.getHits().size(), 497); // should have picked up the default N-terminal modifications: TEST_EQUAL(mod_set.getNumberOfVariableModifications(), 6); TEST_EQUAL(mod_set.getNumberOfFixedModifications(), 0); mod_set.setModifications("", "Carbamidomethyl (C),Oxidation (M),Carboxymethyl (C)"); xml_file.load(OPENMS_GET_TEST_DATA_PATH("XTandemXMLFile_test_2.xml"), protein_identification, peptide_identifications, mod_set); TEST_EQUAL(peptide_identifications.size(), 2); TEST_EQUAL(protein_identification.getHits().size(), 21); // no additional modifications in this case: TEST_EQUAL(mod_set.getNumberOfVariableModifications(), 3); TEST_EQUAL(mod_set.getNumberOfFixedModifications(), 0); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ParameterInformation_test.cpp
.cpp
4,346
122
// 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 <OpenMS/APPLICATIONS/ParameterInformation.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/ListUtils.h> using namespace OpenMS; using namespace std; START_TEST(ParameterInformation, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ParameterInformation* ptr = nullptr; ParameterInformation* null_ptr = nullptr; START_SECTION(ParameterInformation()) { ptr = new ParameterInformation(); TEST_NOT_EQUAL(ptr, null_ptr) TEST_EQUAL(ptr->name, "") TEST_EQUAL(ptr->type, ParameterInformation::NONE) TEST_EQUAL(ptr->default_value, ParamValue()) TEST_EQUAL(ptr->description, "") TEST_EQUAL(ptr->argument, "") TEST_EQUAL(ptr->required, true) TEST_EQUAL(ptr->advanced, false) TEST_EQUAL(ptr->tags.size(), 0) TEST_EQUAL(ptr->valid_strings.size(), 0) TEST_EQUAL(ptr->min_int, -std::numeric_limits<Int>::max()) TEST_EQUAL(ptr->max_int, std::numeric_limits<Int>::max()) TEST_EQUAL(ptr->min_float, -std::numeric_limits<double>::max()) TEST_EQUAL(ptr->max_float, std::numeric_limits<double>::max()) } END_SECTION START_SECTION(~ParameterInformation()) { delete ptr; } END_SECTION START_SECTION((ParameterInformation(const String &n, ParameterTypes t, const String &arg, const DataValue &def, const String &desc, bool req, bool adv, const StringList &tag_values=StringList()))) { ParameterInformation pi1("pi1_name", ParameterInformation::STRING, "<STRING>", "def_value", "this is a description", false, true, ListUtils::create<String>("tag1,tag2")); TEST_EQUAL(pi1.name, "pi1_name") TEST_EQUAL(pi1.type, ParameterInformation::STRING) TEST_EQUAL(pi1.default_value, "def_value") TEST_EQUAL(pi1.description, "this is a description") TEST_EQUAL(pi1.argument, "<STRING>") TEST_EQUAL(pi1.required, false) TEST_EQUAL(pi1.advanced, true) TEST_EQUAL(pi1.tags.size(), 2) ABORT_IF(pi1.tags.size() != 2) TEST_EQUAL(pi1.tags[0], "tag1") TEST_EQUAL(pi1.tags[1], "tag2") TEST_EQUAL(pi1.valid_strings.size(), 0) TEST_EQUAL(pi1.min_int, -std::numeric_limits<Int>::max()) TEST_EQUAL(pi1.max_int, std::numeric_limits<Int>::max()) TEST_EQUAL(pi1.min_float, -std::numeric_limits<double>::max()) TEST_EQUAL(pi1.max_float, std::numeric_limits<double>::max()) } END_SECTION START_SECTION((ParameterInformation& operator=(const ParameterInformation &rhs))) { ParameterInformation pi1("pi1_name", ParameterInformation::STRING, "<STRING>", "def_value", "this is a description", false, true, ListUtils::create<String>("tag1,tag2")); TEST_EQUAL(pi1.name, "pi1_name") TEST_EQUAL(pi1.type, ParameterInformation::STRING) TEST_EQUAL(pi1.default_value, "def_value") TEST_EQUAL(pi1.description, "this is a description") TEST_EQUAL(pi1.argument, "<STRING>") TEST_EQUAL(pi1.required, false) TEST_EQUAL(pi1.advanced, true) TEST_EQUAL(pi1.tags.size(), 2) ABORT_IF(pi1.tags.size() != 2) TEST_EQUAL(pi1.tags[0], "tag1") TEST_EQUAL(pi1.tags[1], "tag2") TEST_EQUAL(pi1.valid_strings.size(), 0) TEST_EQUAL(pi1.min_int, -std::numeric_limits<Int>::max()) TEST_EQUAL(pi1.max_int, std::numeric_limits<Int>::max()) TEST_EQUAL(pi1.min_float, -std::numeric_limits<double>::max()) TEST_EQUAL(pi1.max_float, std::numeric_limits<double>::max()) ParameterInformation pi2; pi2 = pi1; TEST_EQUAL(pi2.name, "pi1_name") TEST_EQUAL(pi2.type, ParameterInformation::STRING) TEST_EQUAL(pi2.default_value, "def_value") TEST_EQUAL(pi2.description, "this is a description") TEST_EQUAL(pi2.argument, "<STRING>") TEST_EQUAL(pi2.required, false) TEST_EQUAL(pi2.advanced, true) TEST_EQUAL(pi2.tags.size(), 2) ABORT_IF(pi2.tags.size() != 2) TEST_EQUAL(pi2.tags[0], "tag1") TEST_EQUAL(pi2.tags[1], "tag2") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/KDTreeFeatureNode_test.cpp
.cpp
2,523
95
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Johannes Veit $ // $Authors: Johannes Veit $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureNode.h> #include <OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.h> #include <OpenMS/KERNEL/FeatureMap.h> using namespace OpenMS; using namespace std; START_TEST(KDTreeFeatureNode, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Feature f1; f1.setCharge(2); f1.setIntensity(100); f1.setMZ(400); f1.setRT(1000); Feature f2; f2.setCharge(3); f2.setIntensity(1000); f2.setMZ(500); f2.setRT(2000); FeatureMap fmap; fmap.push_back(f1); fmap.push_back(f2); vector<FeatureMap> fmaps; fmaps.push_back(fmap); Param p; p.setValue("rt_tol", 100); p.setValue("mz_tol", 10); p.setValue("mz_unit", "ppm"); KDTreeFeatureMaps* kd_data_ptr = new KDTreeFeatureMaps(fmaps, p); KDTreeFeatureNode* ptr = nullptr; KDTreeFeatureNode* nullPointer = nullptr; START_SECTION((KDTreeFeatureNode(KDTreeFeatureMaps* data, Size idx))) ptr = new KDTreeFeatureNode(kd_data_ptr, 0); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~KDTreeFeatureNode())) delete ptr; END_SECTION KDTreeFeatureNode node_1(kd_data_ptr, 1); START_SECTION((KDTreeFeatureNode(const KDTreeFeatureNode& rhs))) ptr = new KDTreeFeatureNode(node_1); TEST_NOT_EQUAL(ptr, nullPointer) TEST_EQUAL(ptr->getIndex(), node_1.getIndex()) TEST_REAL_SIMILAR((*ptr)[0], node_1[0]) TEST_REAL_SIMILAR((*ptr)[1], node_1[1]) delete ptr; END_SECTION START_SECTION((KDTreeFeatureNode& operator=(KDTreeFeatureNode const& rhs))) KDTreeFeatureNode node_2 = node_1; TEST_EQUAL(node_2.getIndex(), node_1.getIndex()) TEST_REAL_SIMILAR(node_2[0], node_1[0]) TEST_REAL_SIMILAR(node_2[1], node_1[1]) END_SECTION START_SECTION((Size getIndex() const)) TEST_EQUAL(node_1.getIndex(), 1) END_SECTION START_SECTION((value_type operator[](Size i) const)) TEST_REAL_SIMILAR(node_1[0], 2000) TEST_REAL_SIMILAR(node_1[1], 500) END_SECTION delete kd_data_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/OpenPepXLAlgorithm_test.cpp
.cpp
3,833
104
// 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/FORMAT/FASTAFile.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> /////////////////////////// #include <OpenMS/ANALYSIS/XLMS/OpenPepXLAlgorithm.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(OpenPepXLAlgorithm, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// OpenPepXLAlgorithm* ptr = 0; OpenPepXLAlgorithm* null_ptr = 0; START_SECTION(OpenPepXLAlgorithm()) { ptr = new OpenPepXLAlgorithm(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(virtual ~OpenPepXLAlgorithm()) { delete ptr; } END_SECTION START_SECTION(ExitCodes run(PeakMap& unprocessed_spectra, ConsensusMap& cfeatures, std::vector<FASTAFile::FASTAEntry>& fasta_db, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids, OPXLDataStructs::PreprocessedPairSpectra& preprocessed_pair_spectra, std::vector< std::pair<Size, Size> >& spectrum_pairs, std::vector< std::vector< OPXLDataStructs::CrossLinkSpectrumMatch > >& all_top_csms, PeakMap& spectra)) std::vector<FASTAFile::FASTAEntry> fasta_db; FASTAFile file; file.load(OPENMS_GET_TEST_DATA_PATH("OpenPepXL_input.fasta"), fasta_db); PeakMap unprocessed_spectra; MzMLFile f; PeakFileOptions options; options.clearMSLevels(); options.addMSLevel(2); f.getOptions() = options; f.load(OPENMS_GET_TEST_DATA_PATH("OpenPepXL_input.mzML"), unprocessed_spectra); // load linked features ConsensusMap cfeatures; ConsensusXMLFile cf; cf.load(OPENMS_GET_TEST_DATA_PATH("OpenPepXL_input.consensusXML"), cfeatures); // initialize solution vectors vector<ProteinIdentification> protein_ids(1); PeptideIdentificationList peptide_ids; OPXLDataStructs::PreprocessedPairSpectra preprocessed_pair_spectra(0); vector< pair<Size, Size> > spectrum_pairs; vector< vector< OPXLDataStructs::CrossLinkSpectrumMatch > > all_top_csms; PeakMap spectra; OpenPepXLAlgorithm search_algorithm; Param algo_param = search_algorithm.getParameters(); algo_param.setValue("modifications:fixed", std::vector<std::string>{"Carbamidomethyl (C)"}); algo_param.setValue("fragment:mass_tolerance", 0.2, "Fragment mass tolerance"); algo_param.setValue("fragment:mass_tolerance_xlinks", 0.3, "Fragment mass tolerance for cross-link ions"); algo_param.setValue("fragment:mass_tolerance_unit", "Da", "Unit of fragment m"); algo_param.setValue("algorithm:number_top_hits", 5, "Number of top hits reported for each spectrum pair"); search_algorithm.setParameters(algo_param); // run algorithm OpenPepXLAlgorithm::ExitCodes exit_code = search_algorithm.run(unprocessed_spectra, cfeatures, fasta_db, protein_ids, peptide_ids, preprocessed_pair_spectra, spectrum_pairs, all_top_csms, spectra); TEST_EQUAL(exit_code, OpenPepXLAlgorithm::ExitCodes::EXECUTION_OK) TEST_EQUAL(protein_ids.size(), 1) TEST_EQUAL(peptide_ids.size(), 12) TEST_EQUAL(spectra.size(), 217) TEST_EQUAL(spectrum_pairs.size(), 25) TEST_EQUAL(preprocessed_pair_spectra.spectra_linear_peaks.size(), 25) TEST_EQUAL(all_top_csms.size(), 12) for (Size i = 0; i < peptide_ids.size(); i += 10) { auto pep_hits = peptide_ids[i].getHits(); TEST_EQUAL(pep_hits[0].metaValueExists("xl_chain"), false) if (pep_hits[0].getMetaValue("xl_type") == "cross-link") { TEST_EQUAL(pep_hits[0].metaValueExists("BetaPepEv:pre"), true) } } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CVTermList_test.cpp
.cpp
12,706
344
// 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/CVTermList.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(CVTermList, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CVTermList* ptr = nullptr; CVTermList* nullPointer = nullptr; START_SECTION(CVTermList()) { ptr = new CVTermList(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~CVTermList()) { delete ptr; } END_SECTION START_SECTION((bool operator==(const CVTermList &cv_term_list) const )) { CVTermList 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 CVTermList &cv_term_list) const )) { CVTermList 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); CVTermList 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); CVTermList 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); CVTermList 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); 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); CVTermList 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); CVTermList 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); CVTermList 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 CVTermList with old "my_accession" CVTermList 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); CVTermList 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); CVTermList 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 */ ///////////////////////////////////////////////////////////// // Copy constructor, move constructor, assignment operator, move assignment operator, equality START_SECTION((CVTermList(const CVTermList &rhs))) { CVTermList cv_term_list; cv_term_list.setMetaValue("blubb", "blubber"); CVTermList 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); CVTermList cv_term_list3(cv_term_list); TEST_TRUE(cv_term_list == cv_term_list3) } END_SECTION START_SECTION((CVTermList(CVTermList &&rhs) noexcept)) { // Ensure that CVTermList has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(CVTermList(std::declval<CVTermList&&>())), true) CVTermList cv_term_list; cv_term_list.setMetaValue("blubb2", "blubbe"); CVTermList orig = cv_term_list; CVTermList 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; CVTermList 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((CVTermList& operator=(const CVTermList &rhs))) { CVTermList cv_term_list; cv_term_list.setMetaValue("blubb", "blubber"); CVTermList 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); CVTermList cv_term_list3; cv_term_list3 = cv_term_list; TEST_TRUE(cv_term_list == cv_term_list3) } END_SECTION START_SECTION((CVTermList& operator=(CVTermList &&rhs))) { CVTermList cv_term_list; cv_term_list.setMetaValue("blubb", "blubber"); CVTermList orig = cv_term_list; CVTermList cv_term_list2; cv_term_list2 = std::move(cv_term_list); TEST_TRUE(orig == cv_term_list2) } 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); CVTermList 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/NoopMSDataConsumer_test.cpp
.cpp
1,432
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/FORMAT/DATAACCESS/NoopMSDataConsumer.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(NoopMSDataConsumer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// NoopMSDataConsumer* ptr = nullptr; NoopMSDataConsumer* null_ptr = nullptr; START_SECTION(NoopMSDataConsumer()) { ptr = new NoopMSDataConsumer(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~NoopMSDataConsumer()) { delete ptr; } END_SECTION START_SECTION((void setExperimentalSettings(const ExperimentalSettings &))) { // TODO } END_SECTION START_SECTION((void setExpectedSize(Size, Size))) { // TODO } END_SECTION START_SECTION((void consumeSpectrum(SpectrumType &))) { // TODO } END_SECTION START_SECTION((void consumeChromatogram(ChromatogramType &))) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeakTypeEstimator_test.cpp
.cpp
2,231
62
// 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/StandardTypes.h> #include <OpenMS/FORMAT/PeakTypeEstimator.h> #include <OpenMS/FORMAT/DTAFile.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <iostream> #include <vector> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(String, "$Id$") ///////////////////////////////////////////////////////////// PeakTypeEstimator* ptr = nullptr; PeakTypeEstimator* nullPointer = nullptr; START_SECTION(([EXTRA]PeakTypeEstimator())) ptr = new PeakTypeEstimator(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(([EXTRA] ~PeakTypeEstimator())) delete ptr; END_SECTION START_SECTION((template<typename PeakConstIterator> SpectrumSettings::SpectrumType estimateType(const PeakConstIterator& begin, const PeakConstIterator& end) const)) DTAFile file; MSSpectrum spec; // raw data (with zeros) file.load(OPENMS_GET_TEST_DATA_PATH("PeakTypeEstimator_raw.dta"), spec); TEST_EQUAL(PeakTypeEstimator::estimateType(spec.begin(), spec.end()), SpectrumSettings::SpectrumType::PROFILE); // TOF raw data (without zeros) file.load(OPENMS_GET_TEST_DATA_PATH("PeakTypeEstimator_rawTOF.dta"), spec); TEST_EQUAL(PeakTypeEstimator::estimateType(spec.begin(), spec.end()), SpectrumSettings::SpectrumType::PROFILE); // peak data file.load(OPENMS_GET_TEST_DATA_PATH("PeakTypeEstimator_peak.dta"), spec); TEST_EQUAL(PeakTypeEstimator::estimateType(spec.begin(), spec.end()), SpectrumSettings::SpectrumType::CENTROID); // too few data points spec.resize(4); TEST_EQUAL(PeakTypeEstimator::estimateType(spec.begin(), spec.end()), SpectrumSettings::SpectrumType::UNKNOWN); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConsensusIDAlgorithmAverage_test.cpp
.cpp
4,436
143
// 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/ConsensusIDAlgorithmAverage.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(ConsensusIDAlgorithmAverage, "$Id$") ///////////////////////////////////////////////////////////// ConsensusIDAlgorithm* ptr = nullptr; ConsensusIDAlgorithm* null_pointer = nullptr; START_SECTION(ConsensusIDAlgorithmAverage()) { ptr = new ConsensusIDAlgorithmAverage(); TEST_NOT_EQUAL(ptr, null_pointer); } END_SECTION START_SECTION(~ConsensusIDAlgorithmAverage()) { 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) ConsensusIDAlgorithmAverage 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("F")); TEST_REAL_SIMILAR(hits[0].getScore(), 0.0); // the two "0.2" scores are not equal (due to floating-point number effects), // therefore the ranks of the hits differ: TEST_EQUAL(hits[1].getScore() < hits[2].getScore(), true); TEST_EQUAL(hits[1].getSequence(), AASequence::fromString("C")); TEST_REAL_SIMILAR(hits[1].getScore(), 0.2); TEST_EQUAL(hits[2].getSequence(), AASequence::fromString("G")); TEST_REAL_SIMILAR(hits[2].getScore(), 0.2); TEST_EQUAL(hits[3].getSequence(), AASequence::fromString("A")); TEST_REAL_SIMILAR(hits[3].getScore(), 0.25); TEST_EQUAL(hits[4].getSequence(), AASequence::fromString("D")); TEST_REAL_SIMILAR(hits[4].getScore(), 0.35); TEST_EQUAL(hits[5].getSequence(), AASequence::fromString("B")); TEST_REAL_SIMILAR(hits[5].getScore(), 0.4); TEST_EQUAL(hits[6].getSequence(), AASequence::fromString("E")); TEST_REAL_SIMILAR(hits[6].getScore(), 0.5); ids[2].setHigherScoreBetter(true); TEST_EXCEPTION(Exception::InvalidValue, consensus.apply(ids, empty)); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Fitter1D_test.cpp
.cpp
2,214
105
// 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/Fitter1D.h> #include <OpenMS/FEATUREFINDER/InterpolationModel.h> using namespace OpenMS; class TestModel : public Fitter1D { public: TestModel() : Fitter1D() { setName("TestModel"); check_defaults_ = false; defaultsToParam_(); } TestModel(const TestModel& source) : Fitter1D(source) { updateMembers_(); } ~TestModel() override { } virtual TestModel& operator = (const TestModel& source) { if (&source == this) return *this; Fitter1D::operator = (source); updateMembers_(); return *this; } void updateMembers_() override { Fitter1D::updateMembers_(); } QualityType fit1d(const RawDataArrayType& /*range*/, std::unique_ptr<InterpolationModel>& /*model*/) override { // double center = 0.0; // center = model->getCenter(); return 1.0; } }; START_TEST(Fitter1D, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using std::stringstream; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TestModel* ptr = nullptr; TestModel* nullPointer = nullptr; START_SECTION(Fitter1D()) { ptr = new TestModel(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((virtual ~Fitter1D())) delete ptr; END_SECTION START_SECTION((virtual QualityType fit1d(const RawDataArrayType &, InterpolationModel *&))) Fitter1D f1d; Fitter1D::RawDataArrayType rft; std::unique_ptr<InterpolationModel> ipm; TEST_EXCEPTION(Exception::NotImplemented,f1d.fit1d(rft,ipm)); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ToolDescription_test.cpp
.cpp
1,500
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/DATASTRUCTURES/ToolDescription.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ToolDescription, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ToolDescription* ptr = 0; ToolDescription* null_ptr = 0; START_SECTION(ToolDescription()) { ptr = new ToolDescription(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~ToolDescription()) { delete ptr; } END_SECTION START_SECTION((ToolDescription(const String &p_name, const String &p_category, const StringList &p_types=StringList()))) { // TODO } END_SECTION START_SECTION((void addExternalType(const String &type, const ToolExternalDetails &details))) { // TODO } END_SECTION START_SECTION((void append(const ToolDescription &other))) { // TODO } END_SECTION START_SECTION((ToolDescription& operator=(const ToolDescription &rhs))) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DIAPrescoring_test.cpp
.cpp
12,868
363
// 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/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/ANALYSIS/OPENSWATH/DIAPrescoring.h> #include "OpenMS/OPENSWATHALGO/DATAACCESS/MockObjects.h" #include <OpenMS/KERNEL/RangeManager.h> using namespace std; using namespace OpenMS; using namespace OpenSwath; START_TEST(DiaPrescore2, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// const std::string ION_MOBILITY_DESCRIPTION = "Ion Mobility"; DiaPrescore* ptr = nullptr; DiaPrescore* nullPointer = nullptr; START_SECTION(DiaPrescore()) { ptr = new DiaPrescore(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~DiaPrescore()) { delete ptr; } END_SECTION START_SECTION ( test score function with perfect first transition and ion mobility filtering ) { OpenSwath::LightTransition mock_tr1; mock_tr1.product_mz = 500.; mock_tr1.fragment_charge = 1; mock_tr1.transition_name = "group1"; mock_tr1.library_intensity = 5.; OpenSwath::LightTransition mock_tr2; mock_tr2.product_mz = 600.; mock_tr2.fragment_charge = 1; mock_tr2.transition_name = "group2"; mock_tr2.library_intensity = 5.; OpenSwath::SpectrumPtr sptr = (OpenSwath::SpectrumPtr)(new OpenSwath::Spectrum); std::vector<OpenSwath::BinaryDataArrayPtr> binaryDataArrayPtrs; OpenSwath::BinaryDataArrayPtr data1(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr data2(new OpenSwath::BinaryDataArray); OpenMS::RangeMobility im_range_empty; static const double arr1[] = { 10, 20, 50, 100, 50, 20, 10, // peak at 499 3, 7, 15, 30, 15, 7, 3, // peak at 500 1, 3, 9, 15, 9, 3, 1, // peak at 501 3, 9, 3, // peak at 502 10, 20, 50, 100, 50, 20, 10, // peak at 600 3, 7, 15, 30, 15, 7, 3, // peak at 601 1, 3, 9, 15, 9, 3, 1, // peak at 602 3, 9, 3 // peak at 603 }; std::vector<double> intensity (arr1, arr1 + sizeof(arr1) / sizeof(double) ); static const double arr2[] = { 499.97, 499.98, 499.99, 500.0, 500.01, 500.02, 500.03, 500.97, 500.98, 500.99, 501.0, 501.01, 501.02, 501.03, 501.97, 501.98, 501.99, 502.0, 502.01, 502.02, 502.03, 502.99, 503.0, 503.01, 599.97, 599.98, 599.99, 600.0, 600.01, 600.02, 600.03, 600.97, 600.98, 600.99, 601.0, 601.01, 601.02, 601.03, 601.97, 601.98, 601.99, 602.0, 602.01, 602.02, 602.03, 602.99, 603.0, 603.01, }; std::vector<double> mz (arr2, arr2 + sizeof(arr2) / sizeof(double) ); data1->data = mz; data2->data = intensity; sptr->setMZArray( data1); sptr->setIntensityArray( data2); std::vector<OpenSwath::LightTransition> transitions; transitions.push_back(mock_tr1); transitions.push_back(mock_tr2); DiaPrescore diaprescore(0.05); double manhattan = 0., dotprod = 0.; std::vector <OpenSwath::SpectrumPtr> sptrArr; sptrArr.push_back(sptr); diaprescore.score(sptrArr, transitions , im_range_empty, dotprod, manhattan); //std::cout << "dotprod : " << dotprod << std::endl; //std::cout << "manhattan : " << manhattan << std::endl; // >> exp = [240, 74, 39, 15, 0] // >> theo = [1, 0.325757771553019, 0.0678711748364005, 0.0105918703087134, 0.00134955223787482] // >> from scipy.stats.stats import pearsonr // >> pearsonr(exp, theo) // (0.99463189043051314, 0.00047175434098498532) // TEST_REAL_SIMILAR(dotprod, 0.916131286812994) TEST_REAL_SIMILAR(manhattan, 0.23670593984202) } END_SECTION START_SECTION ( test score function missing first transition ) { OpenSwath::LightTransition mock_tr1; mock_tr1.product_mz = 500.; mock_tr1.fragment_charge = 1; mock_tr1.transition_name = "group1"; mock_tr1.library_intensity = 5.; OpenSwath::LightTransition mock_tr2; mock_tr2.product_mz = 600.; mock_tr2.fragment_charge = 1; mock_tr2.transition_name = "group2"; mock_tr2.library_intensity = 5.; OpenSwath::SpectrumPtr sptr = (OpenSwath::SpectrumPtr)(new OpenSwath::Spectrum); std::vector<OpenSwath::BinaryDataArrayPtr> binaryDataArrayPtrs; OpenSwath::BinaryDataArrayPtr data1(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr data2(new OpenSwath::BinaryDataArray); static const double arr1[] = { /* 10, 20, 50, 100, 50, 20, 10, // peak at 499 3, 7, 15, 30, 15, 7, 3, // peak at 500 1, 3, 9, 15, 9, 3, 1, // peak at 501 3, 9, 3, // peak at 502 */ 10, 20, 50, 100, 50, 20, 10, // peak at 600 3, 7, 15, 30, 15, 7, 3, // peak at 601 1, 3, 9, 15, 9, 3, 1, // peak at 602 3, 9, 3 // peak at 603 }; std::vector<double> intensity (arr1, arr1 + sizeof(arr1) / sizeof(double) ); static const double arr2[] = { /* 498.97, 498.98, 498.99, 499.0, 499.01, 499.02, 499.03, 499.97, 499.98, 499.99, 500.0, 500.01, 500.02, 500.03, 500.97, 500.98, 500.99, 501.0, 501.01, 501.02, 501.03, 501.99, 502.0, 502.01, */ 599.97, 599.98, 599.99, 600.0, 600.01, 600.02, 600.03, 600.97, 600.98, 600.99, 601.0, 601.01, 601.02, 601.03, 601.97, 601.98, 601.99, 602.0, 602.01, 602.02, 602.03, 602.99, 603.0, 603.01 }; std::vector<double> mz (arr2, arr2 + sizeof(arr2) / sizeof(double) ); data1->data = mz; data2->data = intensity; sptr->setMZArray( data1); sptr->setIntensityArray( data2); std::vector<OpenSwath::LightTransition> transitions; transitions.push_back(mock_tr1); transitions.push_back(mock_tr2); DiaPrescore diaprescore(0.05); OpenMS::RangeMobility im_range_empty; double manhattan = 0., dotprod = 0.; std::vector <OpenSwath::SpectrumPtr> sptrArr; sptrArr.push_back(sptr); diaprescore.score(sptrArr, transitions, im_range_empty, dotprod, manhattan); //std::cout << "dotprod : " << dotprod << std::endl; //std::cout << "manhattan : " << manhattan << std::endl; // >> exp = [240, 74, 39, 15, 0] // >> theo = [1, 0.325757771553019, 0.0678711748364005, 0.0105918703087134, 0.00134955223787482] // >> from scipy.stats.stats import pearsonr // >> pearsonr(exp, theo) // (0.99463189043051314, 0.00047175434098498532) // TEST_REAL_SIMILAR(dotprod, 0.627263258948172) TEST_REAL_SIMILAR(manhattan, 0.984211129641047) } END_SECTION START_SECTION ( test score function with shifted first transition ) { OpenSwath::LightTransition mock_tr1; mock_tr1.product_mz = 500.; mock_tr1.fragment_charge = 1; mock_tr1.transition_name = "group1"; mock_tr1.library_intensity = 5.; OpenSwath::LightTransition mock_tr2; mock_tr2.product_mz = 600.; mock_tr2.fragment_charge = 1; mock_tr2.transition_name = "group2"; mock_tr2.library_intensity = 5.; OpenSwath::SpectrumPtr sptr = (OpenSwath::SpectrumPtr)(new OpenSwath::Spectrum); std::vector<OpenSwath::BinaryDataArrayPtr> binaryDataArrayPtrs; OpenSwath::BinaryDataArrayPtr data1(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr data2(new OpenSwath::BinaryDataArray); static const double arr1[] = { 10, 20, 50, 100, 50, 20, 10, // peak at 499 3, 7, 15, 30, 15, 7, 3, // peak at 500 1, 3, 9, 15, 9, 3, 1, // peak at 501 3, 9, 3, // peak at 502 10, 20, 50, 100, 50, 20, 10, // peak at 600 3, 7, 15, 30, 15, 7, 3, // peak at 601 1, 3, 9, 15, 9, 3, 1, // peak at 602 3, 9, 3 // peak at 603 }; std::vector<double> intensity (arr1, arr1 + sizeof(arr1) / sizeof(double) ); static const double arr2[] = { 498.97, 498.98, 498.99, 499.0, 499.01, 499.02, 499.03, 499.97, 499.98, 499.99, 500.0, 500.01, 500.02, 500.03, 500.97, 500.98, 500.99, 501.0, 501.01, 501.02, 501.03, 501.99, 502.0, 502.01, 599.97, 599.98, 599.99, 600.0, 600.01, 600.02, 600.03, 600.97, 600.98, 600.99, 601.0, 601.01, 601.02, 601.03, 601.97, 601.98, 601.99, 602.0, 602.01, 602.02, 602.03, 602.99, 603.0, 603.01 }; std::vector<double> mz (arr2, arr2 + sizeof(arr2) / sizeof(double) ); data1->data = mz; data2->data = intensity; sptr->setMZArray( data1); sptr->setIntensityArray( data2); std::vector<OpenSwath::LightTransition> transitions; transitions.push_back(mock_tr1); transitions.push_back(mock_tr2); DiaPrescore diaprescore(0.05); OpenMS::RangeMobility im_range_empty; double manhattan = 0., dotprod = 0.; std::vector <OpenSwath::SpectrumPtr> sptrArr; sptrArr.push_back(sptr); diaprescore.score(sptrArr, transitions, im_range_empty, dotprod, manhattan); //std::cout << "dotprod : " << dotprod << std::endl; //std::cout << "manhattan : " << manhattan << std::endl; // >> exp = [240, 74, 39, 15, 0] // >> theo = [1, 0.325757771553019, 0.0678711748364005, 0.0105918703087134, 0.00134955223787482] // >> from scipy.stats.stats import pearsonr // >> pearsonr(exp, theo) // (0.99463189043051314, 0.00047175434098498532) // TEST_REAL_SIMILAR(dotprod, 0.43738312515644) TEST_REAL_SIMILAR(manhattan, 0.557433222328531) } END_SECTION START_SECTION ( test score function missing first transition due to different ion mobility ) { OpenSwath::LightTransition mock_tr1; mock_tr1.product_mz = 500.; mock_tr1.fragment_charge = 1; mock_tr1.transition_name = "group1"; mock_tr1.library_intensity = 5.; OpenSwath::LightTransition mock_tr2; mock_tr2.product_mz = 600.; mock_tr2.fragment_charge = 1; mock_tr2.transition_name = "group2"; mock_tr2.library_intensity = 5.; double PRECURSOR_ION_MOBILITY = 7; double ION_MOBILITY_WIDTH = 2; OpenSwath::SpectrumPtr sptr = (OpenSwath::SpectrumPtr)(new OpenSwath::Spectrum); std::vector<OpenSwath::BinaryDataArrayPtr> binaryDataArrayPtrs; OpenSwath::BinaryDataArrayPtr data1(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr data2(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr data3(new OpenSwath::BinaryDataArray); std::vector<double> intensity { 10, 20, 50, 100, 50, 20, 10, // peak at 499 3, 7, 15, 30, 15, 7, 3, // peak at 500 1, 3, 9, 15, 9, 3, 1, // peak at 501 3, 9, 3, // peak at 502 10, 20, 50, 100, 50, 20, 10, // peak at 600 3, 7, 15, 30, 15, 7, 3, // peak at 601 1, 3, 9, 15, 9, 3, 1, // peak at 602 3, 9, 3 // peak at 603 }; std::vector<double> mz { 498.97, 498.98, 498.99, 499.0, 499.01, 499.02, 499.03, 499.97, 499.98, 499.99, 500.0, 500.01, 500.02, 500.03, 500.97, 500.98, 500.99, 501.0, 501.01, 501.02, 501.03, 501.99, 502.0, 502.01, 599.97, 599.98, 599.99, 600.0, 600.01, 600.02, 600.03, 600.97, 600.98, 600.99, 601.0, 601.01, 601.02, 601.03, 601.97, 601.98, 601.99, 602.0, 602.01, 602.02, 602.03, 602.99, 603.0, 603.01 }; std::vector<double> im { 1, 1, 3, 1, 1, 1, 1, // peak at 499 2, 2, 3, 1, 2, 1, 2, // peak at 500 1, 2, 1, 2, 3, 2, 2, // peak at 501 2, 2, 2, // peak at 502 7, 6, 7, 6, 8, 6, 8, // peak at 600 7, 7, 7, 8, 7, 7, 8, // peak at 601 8, 6, 8, 8, 6, 6, 6, // peak at 602 6, 8, 6 // peak at 603 }; data1->data = mz; data2->data = intensity; data3->data = im; sptr->setMZArray(data1); sptr->setIntensityArray(data2); data3->description = ION_MOBILITY_DESCRIPTION; sptr->getDataArrays().push_back(data3); std::vector<OpenSwath::LightTransition> transitions; transitions.push_back(mock_tr1); transitions.push_back(mock_tr2); DiaPrescore diaprescore(0.05); OpenMS::RangeMobility im_range(PRECURSOR_ION_MOBILITY); im_range.minSpanIfSingular(ION_MOBILITY_WIDTH); double manhattan = 0., dotprod = 0.; std::vector <OpenSwath::SpectrumPtr> sptrArr; sptrArr.push_back(sptr); diaprescore.score(sptrArr, transitions, im_range, dotprod, manhattan); //std::cout << "dotprod : " << dotprod << std::endl; //std::cout << "manhattan : " << manhattan << std::endl; // >> exp = [240, 74, 39, 15, 0] // >> theo = [1, 0.325757771553019, 0.0678711748364005, 0.0105918703087134, 0.00134955223787482] // >> from scipy.stats.stats import pearsonr // >> pearsonr(exp, theo) // (0.99463189043051314, 0.00047175434098498532) // TEST_REAL_SIMILAR(dotprod, 0.627263258948172) TEST_REAL_SIMILAR(manhattan, 0.984211129641047) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Feature_test.cpp
.cpp
14,173
452
// 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/Feature.h> /////////////////////////// START_TEST(Feature, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; typedef OpenMS::BaseFeature::QualityType QualityType; Feature* d_ptr = nullptr; Feature* nullPointer = nullptr; START_SECTION((Feature())) { d_ptr = new Feature; TEST_NOT_EQUAL(d_ptr, nullPointer); } END_SECTION START_SECTION((~Feature())) { delete d_ptr; } END_SECTION START_SECTION((QualityType getOverallQuality() const)) Feature p; TEST_REAL_SIMILAR(p.getOverallQuality(), 0.0) p.setOverallQuality((QualityType)123.456); TEST_REAL_SIMILAR(p.getOverallQuality(), 123.456) p.setOverallQuality((QualityType)-0.12345); TEST_REAL_SIMILAR(p.getOverallQuality(), -0.12345) p.setOverallQuality( (QualityType)0.0); TEST_REAL_SIMILAR(p.getOverallQuality(), 0.0) END_SECTION START_SECTION((void setOverallQuality(QualityType q))) Feature p; p.setOverallQuality((QualityType)123.456); TEST_REAL_SIMILAR(p.getOverallQuality(), 123.456) p.setOverallQuality( (QualityType)-0.12345); TEST_REAL_SIMILAR(p.getOverallQuality(), -0.12345) p.setOverallQuality( (QualityType)0.0); TEST_REAL_SIMILAR(p.getOverallQuality(), 0.0) END_SECTION START_SECTION((QualityType getQuality(Size index) const )) Feature p; TEST_REAL_SIMILAR(p.getQuality(0), 0.0) p.setQuality( 0, (QualityType)123.456); TEST_REAL_SIMILAR(p.getQuality(0), 123.456) p.setQuality( 0, (QualityType)-0.12345); TEST_REAL_SIMILAR(p.getQuality(0), -0.12345) p.setQuality( 0, (QualityType)0.0); TEST_REAL_SIMILAR(p.getQuality(0), 0.0) TEST_REAL_SIMILAR(p.getQuality(1), 0.0) TEST_PRECONDITION_VIOLATED(p.getQuality(10)) END_SECTION START_SECTION((void setQuality(Size index, QualityType q))) Feature p; p.setQuality( 1, (QualityType)123.456); TEST_REAL_SIMILAR(p.getQuality(1), 123.456) p.setQuality( 1, (QualityType)-0.12345); TEST_REAL_SIMILAR(p.getQuality(1), -0.12345) p.setQuality( 1, (QualityType)0.0); TEST_REAL_SIMILAR(p.getQuality(0), 0.0) TEST_REAL_SIMILAR(p.getQuality(1), 0.0) TEST_PRECONDITION_VIOLATED(p.setQuality( 10, (QualityType)1.0)) END_SECTION //do not change these datastructures, they are used in the following tests... std::vector< ConvexHull2D > hulls(2); hulls[0].addPoint(DPosition<2>(1.0,2.0)); hulls[0].addPoint(DPosition<2>(3.0,4.0)); hulls[1].addPoint(DPosition<2>(0.5,0.0)); hulls[1].addPoint(DPosition<2>(1.0,1.0)); START_SECTION((const vector<ConvexHull2D>& getConvexHulls() const)) Feature tmp; TEST_EQUAL(tmp.getConvexHulls().size(),0) END_SECTION START_SECTION((vector<ConvexHull2D>& getConvexHulls())) Feature tmp; tmp.setConvexHulls(hulls); TEST_EQUAL(tmp.getConvexHulls().size(),2) TEST_REAL_SIMILAR(tmp.getConvexHulls()[0].getHullPoints()[0][0],1.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[0].getHullPoints()[0][1],2.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[0].getHullPoints()[1][0],3.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[0].getHullPoints()[1][1],4.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[1].getHullPoints()[0][0],0.5) TEST_REAL_SIMILAR(tmp.getConvexHulls()[1].getHullPoints()[0][1],0.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[1].getHullPoints()[1][0],1.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[1].getHullPoints()[1][1],1.0) END_SECTION START_SECTION((void setConvexHulls(const vector<ConvexHull2D>& hulls))) Feature tmp; tmp.setConvexHulls(hulls); TEST_EQUAL(tmp.getConvexHulls().size(),2) TEST_REAL_SIMILAR(tmp.getConvexHulls()[0].getHullPoints()[0][0],1.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[0].getHullPoints()[0][1],2.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[0].getHullPoints()[1][0],3.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[0].getHullPoints()[1][1],4.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[1].getHullPoints()[0][0],0.5) TEST_REAL_SIMILAR(tmp.getConvexHulls()[1].getHullPoints()[0][1],0.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[1].getHullPoints()[1][0],1.0) TEST_REAL_SIMILAR(tmp.getConvexHulls()[1].getHullPoints()[1][1],1.0) END_SECTION START_SECTION((ConvexHull2D& getConvexHull() const)) Feature tmp; tmp.setConvexHulls(hulls); //check if the bounding box is ok DBoundingBox<2> bb = tmp.getConvexHull().getBoundingBox(); TEST_REAL_SIMILAR(bb.minPosition()[0],0.5) TEST_REAL_SIMILAR(bb.minPosition()[1],0.0) TEST_REAL_SIMILAR(bb.maxPosition()[0],3.0) TEST_REAL_SIMILAR(bb.maxPosition()[1],4.0) //check the convex hull points TEST_EQUAL(tmp.getConvexHull().getHullPoints().size(),4) TEST_REAL_SIMILAR(tmp.getConvexHull().getHullPoints()[0][0],0.5) TEST_REAL_SIMILAR(tmp.getConvexHull().getHullPoints()[0][1],0.0) TEST_REAL_SIMILAR(tmp.getConvexHull().getHullPoints()[1][0],3.0) TEST_REAL_SIMILAR(tmp.getConvexHull().getHullPoints()[1][1],0.0) TEST_REAL_SIMILAR(tmp.getConvexHull().getHullPoints()[2][0],3.0) TEST_REAL_SIMILAR(tmp.getConvexHull().getHullPoints()[2][1],4.0) TEST_REAL_SIMILAR(tmp.getConvexHull().getHullPoints()[3][0],0.5) TEST_REAL_SIMILAR(tmp.getConvexHull().getHullPoints()[3][1],4.0) END_SECTION hulls[0].addPoint(DPosition<2>(3.0,2.0)); hulls[1].addPoint(DPosition<2>(2.0,1.0)); START_SECTION((bool encloses(double rt, double mz) const)) Feature tmp; TEST_EQUAL(tmp.getConvexHull().getBoundingBox().isEmpty(), true) tmp.setConvexHulls(hulls); TEST_EQUAL(tmp.encloses(0.0,0.0), false); TEST_EQUAL(tmp.encloses(1.0,1.0), true); TEST_EQUAL(tmp.encloses(2.0,0.5), false); TEST_EQUAL(tmp.encloses(2.0,3.001), false); TEST_EQUAL(tmp.encloses(2.0,2.999), true); TEST_EQUAL(tmp.encloses(2.0,3.5), false); TEST_EQUAL(tmp.encloses(4.0,3.0), false); TEST_EQUAL(tmp.encloses(1.5,1.5), false); TEST_EQUAL(tmp.encloses(2.0,1.0), true); TEST_EQUAL(tmp.encloses(0.5,0.0), true); TEST_EQUAL(tmp.encloses(3.0,3.2), true); END_SECTION START_SECTION((Feature(const Feature &feature))) { Feature::PositionType pos; pos[0] = 21.21; pos[1] = 22.22; Feature p; p.setIntensity(123.456f); p.setPosition(pos); p.setMetaValue("cluster_id",4711); p.setOverallQuality( (QualityType)0.9); p.setQuality( 0, (QualityType)0.1); p.setQuality( 1, (QualityType)0.2); p.setConvexHulls(hulls); p.getConvexHull(); //this pre-calculates the overall convex hull Feature::PositionType pos2; Feature::IntensityType i2; Feature 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) TEST_EQUAL(copy_of_p.getMetaValue("cluster_id"), DataValue(4711)); Feature::QualityType q2; q2 = copy_of_p.getOverallQuality(); TEST_REAL_SIMILAR(q2, 0.9) q2 = copy_of_p.getQuality(0); TEST_REAL_SIMILAR(q2, 0.1) q2 = copy_of_p.getQuality(1); TEST_REAL_SIMILAR(q2, 0.2) TEST_EQUAL(copy_of_p.getConvexHull().getHullPoints().size(),p.getConvexHull().getHullPoints().size()) TEST_EQUAL(copy_of_p.getConvexHulls().size(),p.getConvexHulls().size()) } END_SECTION START_SECTION((Feature(const Feature&& source))) { // Ensure that Feature has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(Feature(std::declval<Feature&&>())), true) Feature::PositionType pos; pos[0] = 21.21; pos[1] = 22.22; Feature p; p.setIntensity(123.456f); p.setPosition(pos); p.setMetaValue("cluster_id",4711); p.setOverallQuality( (QualityType)0.9); p.setQuality( 0, (QualityType)0.1); p.setQuality( 1, (QualityType)0.2); p.setConvexHulls(hulls); p.getConvexHull(); //this pre-calculates the overall convex hull Feature::PositionType pos2; Feature::IntensityType i2; //copy p so we can move one of them Feature orig = p; Feature 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) TEST_EQUAL(copy_of_p.getMetaValue("cluster_id"), DataValue(4711)); Feature::QualityType q2; q2 = copy_of_p.getOverallQuality(); TEST_REAL_SIMILAR(q2, 0.9) q2 = copy_of_p.getQuality(0); TEST_REAL_SIMILAR(q2, 0.1) q2 = copy_of_p.getQuality(1); TEST_REAL_SIMILAR(q2, 0.2) TEST_EQUAL(copy_of_p.getConvexHull().getHullPoints().size(), orig.getConvexHull().getHullPoints().size()) TEST_EQUAL(copy_of_p.getConvexHulls().size(), orig.getConvexHulls().size()) TEST_EQUAL(p.getConvexHull().getHullPoints().size(), 0) TEST_EQUAL(p.getConvexHulls().size(), 0) } END_SECTION START_SECTION((Feature& operator = (const Feature& rhs))) Feature::PositionType pos; pos[0] = 21.21; pos[1] = 22.22; Feature p; p.setIntensity(123.456f); p.setPosition(pos); p.setOverallQuality( (QualityType)0.9); p.setQuality( 0, (QualityType)0.1); p.setQuality( 1, (QualityType)0.2); p.setMetaValue("cluster_id",4712); p.setConvexHulls(hulls); Feature::PositionType pos2; Feature::IntensityType i2; Feature copy_of_p; copy_of_p.getConvexHull(); //this pre-calculates the overall convex hull in order to check that the recalculation flag is copied correctly copy_of_p = p; i2 = copy_of_p.getIntensity(); pos2 = copy_of_p.getPosition(); Feature::QualityType q2; TEST_REAL_SIMILAR(i2, 123.456) TEST_REAL_SIMILAR(pos2[0], 21.21) TEST_REAL_SIMILAR(pos2[1], 22.22) q2 = copy_of_p.getOverallQuality(); TEST_REAL_SIMILAR(q2, 0.9) q2 = copy_of_p.getQuality(0); TEST_REAL_SIMILAR(q2, 0.1) q2 = copy_of_p.getQuality(1); TEST_REAL_SIMILAR(q2, 0.2) TEST_EQUAL(copy_of_p.getConvexHull().getHullPoints().size(),p.getConvexHull().getHullPoints().size()) TEST_EQUAL(copy_of_p.getConvexHulls().size(),p.getConvexHulls().size()) END_SECTION START_SECTION((bool operator==(const Feature &rhs) const)) Feature p1; Feature p2(p1); TEST_TRUE(p1 == p2) p1.setIntensity(5.0f); p1.setOverallQuality( (QualityType)0.9); p1.setQuality(0, (QualityType)0.1); TEST_EQUAL(p1==p2, false) p2.setIntensity(5.0f); p2.setOverallQuality( (QualityType)0.9); p2.setQuality(0, (QualityType)0.1); 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([EXTRA](Feature& operator != (const Feature& rhs))) Feature p1; Feature 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]meta info with copy constructor)) { Feature p; p.setMetaValue(2,String("bla")); Feature p2(p); TEST_EQUAL(p.getMetaValue(2), "bla") TEST_EQUAL(p2.getMetaValue(2), "bla") p.setMetaValue(2,String("bluff")); TEST_EQUAL(p.getMetaValue(2), "bluff") TEST_EQUAL(p2.getMetaValue(2), "bla") } END_SECTION START_SECTION(([EXTRA]meta info with assignment)) { Feature p; p.setMetaValue(2,String("bla")); Feature p2 = p; TEST_EQUAL(p.getMetaValue(2), "bla") TEST_EQUAL(p2.getMetaValue(2), "bla") p.setMetaValue(2,String("bluff")); TEST_EQUAL(p.getMetaValue(2), "bluff") TEST_EQUAL(p2.getMetaValue(2), "bla") } END_SECTION START_SECTION((std::vector<Feature>& getSubordinates())) { // see below NOT_TESTABLE; } END_SECTION START_SECTION((void setSubordinates(const std::vector<Feature>& rhs))) { // see below NOT_TESTABLE; } END_SECTION START_SECTION((const std::vector<Feature>& getSubordinates() const)) { Feature f1; f1.setRT(1001); f1.setMZ(1002); f1.setCharge(1003); Feature f1_cpy(f1); Feature f11; f11.setRT(1101); f11.setMZ(1102); Feature f12; f12.setRT(1201); f12.setMZ(1202); Feature f13; f13.setRT(1301); f13.setMZ(1302); TEST_EQUAL(f1.getSubordinates().empty(),true); f1.getSubordinates().push_back(f11); TEST_EQUAL(f1.getSubordinates().size(),1); f1.getSubordinates().push_back(f12); TEST_EQUAL(f1.getSubordinates().size(),2); f1.getSubordinates().push_back(f13); TEST_EQUAL(f1.getSubordinates().size(),3); TEST_EQUAL(f1.getRT(),1001); TEST_EQUAL(f1.getSubordinates()[0].getRT(),1101); TEST_EQUAL(f1.getSubordinates()[1].getRT(),1201); TEST_EQUAL(f1.getSubordinates()[2].getRT(),1301); const Feature &f1_cref = f1; TEST_EQUAL(f1_cref.getMZ(),1002); TEST_EQUAL(f1_cref.getSubordinates()[0].getMZ(),1102); TEST_EQUAL(f1_cref.getSubordinates()[1].getMZ(),1202); TEST_EQUAL(f1_cref.getSubordinates()[2].getMZ(),1302); TEST_NOT_EQUAL(f1_cref,f1_cpy); Feature f1_cpy2(f1); TEST_EQUAL(f1_cpy2,f1); f1.getSubordinates().clear(); TEST_EQUAL(f1_cref,f1_cpy); Feature f2; f2.setRT(1001); f2.setMZ(1002); f2.setCharge(1003); TEST_NOT_EQUAL(f1_cpy2.getSubordinates().empty(),true); f2.setSubordinates(f1_cpy2.getSubordinates()); TEST_EQUAL(f2,f1_cpy2); } END_SECTION START_SECTION((template < typename Type > Size applyMemberFunction( Size (Type::*member_function)() ))) { Feature f; TEST_EQUAL(f.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId), 1); f.setUniqueId(); TEST_EQUAL(f.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId), 0); } END_SECTION START_SECTION((template < typename Type > Size applyMemberFunction( Size (Type::*member_function)() const) const)) { Feature f; TEST_EQUAL(f.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId), 1); f.setUniqueId(); TEST_EQUAL(f.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId), 0); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MascotGenericFile_test.cpp
.cpp
8,789
272
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Andreas Bertsch, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/MascotGenericFile.h> #include <sstream> /////////////////////////// #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/CONCEPT/Constants.h> using namespace OpenMS; using namespace std; START_TEST(MascotGenericFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MascotGenericFile* ptr = nullptr; MascotGenericFile* nullPointer = nullptr; START_SECTION(MascotGenericFile()) { ptr = new MascotGenericFile(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~MascotGenericFile()) { delete ptr; } END_SECTION ptr = new MascotGenericFile(); START_SECTION((template < typename MapType > void load(const String &filename, MapType &exp))) { PeakMap exp; ptr->load(OPENMS_GET_TEST_DATA_PATH("MascotInfile_test.mascot_in"), exp); TEST_EQUAL(exp.size(), 1) TEST_EQUAL(exp.begin()->size(), 9) } END_SECTION START_SECTION((void store(std::ostream &os, const String &filename, const PeakMap &experiment, bool compact = false))) { PeakMap exp; ptr->load(OPENMS_GET_TEST_DATA_PATH("MascotInfile_test.mascot_in"), exp); // handling of modifications: Param params = ptr->getParameters(); params.setValue("fixed_modifications", std::vector<std::string>{"Carbamidomethyl (C)","Phospho (S)"}); params.setValue("variable_modifications", std::vector<std::string>{"Oxidation (M)","Deamidated (N)","Deamidated (Q)"}); ptr->setParameters(params); stringstream ss; ptr->store(ss, "test", exp); vector<String> strings; strings.push_back("BEGIN IONS\n" "TITLE=Testtitle_index=0\n" // different from input! "PEPMASS=1998.0\n" "RTINSECONDS=25.379000000000001\n" "SCANS=0"); strings.push_back("1.0 1.0\n" "2.0 4.0\n" "3.0 9.0\n" "4.0 16.0\n" "5.0 25.0\n" "6.0 36.0\n" "7.0 49.0\n" "8.0 64.0\n" "9.0 81.0\n" "END IONS\n"); strings.push_back("MODS=Carbamidomethyl (C)\n"); strings.push_back("MODS=Phospho (ST)\n"); strings.push_back("IT_MODS=Deamidated (NQ)"); strings.push_back("IT_MODS=Oxidation (M)"); String mgf_file(ss.str()); for (Size i = 0; i < strings.size(); ++i) { TEST_EQUAL(mgf_file.hasSubstring(strings[i]), true) } // test of making default TITLE exp[0].removeMetaValue("TITLE"); stringstream ss2; ptr->store(ss2, "test", exp); vector<String> strings2; strings2.push_back("BEGIN IONS\n" "TITLE=1998.0_25.379000000000001_index=0_test\n" // different from input! "PEPMASS=1998.0\n" "RTINSECONDS=25.379000000000001\n" "SCANS=0"); strings2.push_back("1.0 1.0\n" "2.0 4.0\n" "3.0 9.0\n" "4.0 16.0\n" "5.0 25.0\n" "6.0 36.0\n" "7.0 49.0\n" "8.0 64.0\n" "9.0 81.0\n" "END IONS\n"); strings2.push_back("MODS=Carbamidomethyl (C)\n"); strings2.push_back("MODS=Phospho (ST)\n"); strings2.push_back("IT_MODS=Deamidated (NQ)"); strings2.push_back("IT_MODS=Oxidation (M)"); String mgf_file2(ss2.str()); for (Size i = 0; i < strings2.size(); ++i) { TEST_EQUAL(mgf_file2.hasSubstring(strings2[i]), true) } ptr->setParameters(ptr->getDefaults()); // reset parameters // test compact format: MSSpectrum spec; spec.setNativeID("index=250"); spec.setMSLevel(2); spec.setRT(234.5678901); Precursor prec; prec.setMZ(901.2345678); spec.getPrecursors().push_back(prec); Peak1D peak; peak.setMZ(567.8901234); peak.setIntensity(0.0); spec.push_back(peak); // intensity zero -> not present in output peak.setMZ(890.1234567); peak.setIntensity(2345.678901); spec.push_back(peak); exp.clear(true); exp.addSpectrum(spec); ss.str(""); ptr->store(ss, "test", exp, true); mgf_file = ss.str(); String content = ("BEGIN IONS\n" "TITLE=901.23457_234.568_index=250_test\n" "PEPMASS=901.23457\n" "RTINSECONDS=234.568\n" "SCANS=250\n" "890.12346 2345.679\n" "END IONS"); TEST_EQUAL(mgf_file.hasSubstring(content), true); } END_SECTION START_SECTION((void store(const String &filename, const PeakMap &experiment, bool compact = false))) { String tmp_name("MascotGenericFile_1.tmp"); NEW_TMP_FILE(tmp_name) PeakMap exp; ptr->load(OPENMS_GET_TEST_DATA_PATH("MascotInfile_test.mascot_in"), exp); ptr->store(tmp_name, exp); PeakMap exp2; ptr->load(tmp_name, exp2); TEST_EQUAL(exp.size() == exp2.size(), true) TEST_EQUAL(exp.begin()->size() == exp2.begin()->size(), true) TEST_REAL_SIMILAR(exp.begin()->getRT(), exp2.begin()->getRT()) TEST_REAL_SIMILAR(exp.begin()->getPrecursors().begin()->getMZ(), exp2.begin()->getPrecursors().begin()->getMZ()) } END_SECTION START_SECTION((COMPOUND_NAME to Metabolite_Name mapping)) { // Test that COMPOUND_NAME in MGF is correctly mapped to Constants::UserParam::MSM_METABOLITE_NAME String mgf_content = "BEGIN IONS\n" "TITLE=Test spectrum\n" "PEPMASS=500.0\n" "CHARGE=1\n" "COMPOUND_NAME=Caffeine\n" "100.0 1000.0\n" "200.0 2000.0\n" "END IONS\n"; stringstream mgf_stream(mgf_content); PeakMap exp; MascotGenericFile mgf_file; // Create a temporary file to test the loading functionality String tmp_name("test_compound_name.mgf"); NEW_TMP_FILE(tmp_name) // Write MGF content to temporary file std::ofstream ofs(tmp_name.c_str()); ofs << mgf_content; ofs.close(); // Load the MGF file mgf_file.load(tmp_name, exp); // Test that we have one spectrum TEST_EQUAL(exp.size(), 1) // Test that the spectrum has the correct metabolite name metadata TEST_EQUAL(exp[0].metaValueExists(Constants::UserParam::MSM_METABOLITE_NAME), true) TEST_EQUAL(String(exp[0].getMetaValue(Constants::UserParam::MSM_METABOLITE_NAME)), "Caffeine") // Test that other expected properties are also parsed correctly TEST_EQUAL(exp[0].size(), 2) // Two peaks TEST_REAL_SIMILAR(exp[0].getPrecursors()[0].getMZ(), 500.0) TEST_EQUAL(exp[0].getPrecursors()[0].getCharge(), 1) } END_SECTION START_SECTION((GNPS MGF file - 3-Des-Microcystein_LR)) { // Test loading a real GNPS library spectrum with COMPOUND_NAME and SPECTRUMID metadata PeakMap exp; MascotGenericFile mgf_file; // Load the GNPS MGF file mgf_file.load(OPENMS_GET_TEST_DATA_PATH("MascotGenericFile_GNPS.mgf"), exp); // Test that we have one spectrum TEST_EQUAL(exp.size(), 1) // Test that SPECTRUMID was correctly parsed and stored as GNPS_Spectrum_ID TEST_EQUAL(exp[0].metaValueExists("GNPS_Spectrum_ID"), true) TEST_EQUAL(String(exp[0].getMetaValue("GNPS_Spectrum_ID")), "CCMSLIB00000001547") // Test that COMPOUND_NAME was correctly mapped to MSM_METABOLITE_NAME TEST_EQUAL(exp[0].metaValueExists(Constants::UserParam::MSM_METABOLITE_NAME), true) TEST_EQUAL(String(exp[0].getMetaValue(Constants::UserParam::MSM_METABOLITE_NAME)), "3-Des-Microcystein_LR") // Test precursor m/z TEST_REAL_SIMILAR(exp[0].getPrecursors()[0].getMZ(), 981.54) // Test charge state TEST_EQUAL(exp[0].getPrecursors()[0].getCharge(), 1) // Test that we have the expected number of peaks (43 peaks in the file) TEST_EQUAL(exp[0].size(), 43) // Test the base peak (m/z 599.352783 with intensity 764523.0) bool found_base_peak = false; for (Size i = 0; i < exp[0].size(); ++i) { if (std::abs(exp[0][i].getMZ() - 599.352783) < 0.001) { found_base_peak = true; TEST_REAL_SIMILAR(exp[0][i].getIntensity(), 764523.0) break; } } TEST_EQUAL(found_base_peak, true) } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MSDataCachedConsumer_test.cpp
.cpp
6,988
209
// 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/DATAACCESS/MSDataCachedConsumer.h> /////////////////////////// #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> #include <OpenMS/FORMAT/CachedMzML.h> START_TEST(MSDataCachedConsumer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; MSDataCachedConsumer* cached_consumer_ptr = nullptr; MSDataCachedConsumer* cached_consumer_nullPointer = nullptr; START_SECTION((MSDataCachedConsumer())) std::string tmp_filename; NEW_TMP_FILE(tmp_filename); cached_consumer_ptr = new MSDataCachedConsumer(tmp_filename); TEST_NOT_EQUAL(cached_consumer_ptr, cached_consumer_nullPointer) END_SECTION START_SECTION((~MSDataCachedConsumer())) delete cached_consumer_ptr; END_SECTION START_SECTION((void consumeSpectrum(SpectrumType & s))) { std::string tmp_filename; NEW_TMP_FILE(tmp_filename); MSDataCachedConsumer * cached_consumer = new MSDataCachedConsumer(tmp_filename, false); PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) cached_consumer->setExpectedSize(2,0); cached_consumer->consumeSpectrum(exp.getSpectrum(0)); cached_consumer->consumeSpectrum(exp.getSpectrum(1)); delete cached_consumer; // Check whether it was written to disk correctly... { // Create the index from the given file Internal::CachedMzMLHandler cache; cache.createMemdumpIndex(tmp_filename); std::vector<std::streampos> spectra_index = cache.getSpectraIndex(); std::ifstream ifs_(tmp_filename.c_str(), std::ios::binary); // retrieve the spectrum OpenSwath::BinaryDataArrayPtr mz_array(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity_array(new OpenSwath::BinaryDataArray); ifs_.seekg(spectra_index[0]); int ms_level = -1; double rt = -1.0; Internal::CachedMzMLHandler::readSpectrumFast(mz_array, intensity_array, ifs_, ms_level, rt); TEST_EQUAL(mz_array->data.size(), exp.getSpectrum(0).size()) TEST_EQUAL(intensity_array->data.size(), exp.getSpectrum(0).size()) // retrieve the spectrum ifs_.seekg(spectra_index[1]); Internal::CachedMzMLHandler::readSpectrumFast(mz_array, intensity_array, ifs_, ms_level, rt); TEST_EQUAL(mz_array->data.size(), exp.getSpectrum(1).size()) TEST_EQUAL(intensity_array->data.size(), exp.getSpectrum(1).size()) } } END_SECTION START_SECTION((void consumeChromatogram(ChromatogramType & c))) { std::string tmp_filename; NEW_TMP_FILE(tmp_filename); MSDataCachedConsumer * cached_consumer = new MSDataCachedConsumer(tmp_filename, false); PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrChromatograms() > 0, true) cached_consumer->setExpectedSize(0,1); cached_consumer->consumeChromatogram(exp.getChromatogram(0)); delete cached_consumer; // Check whether it was written to disk correctly... { // Create the index from the given file Internal::CachedMzMLHandler cache; cache.createMemdumpIndex(tmp_filename); std::vector<std::streampos> chrom_index = cache.getChromatogramIndex();; std::ifstream ifs_(tmp_filename.c_str(), std::ios::binary); // retrieve the chromatogram OpenSwath::BinaryDataArrayPtr time_array(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity_array(new OpenSwath::BinaryDataArray); ifs_.seekg(chrom_index[0]); Internal::CachedMzMLHandler::readChromatogramFast(time_array, intensity_array, ifs_); TEST_EQUAL(time_array->data.size(), exp.getChromatogram(0).size()) TEST_EQUAL(intensity_array->data.size(), exp.getChromatogram(0).size()) } } END_SECTION START_SECTION((MSDataCachedConsumer(String filename, bool clearData=true))) { { std::string tmp_filename; NEW_TMP_FILE(tmp_filename); MSDataCachedConsumer * cached_consumer = new MSDataCachedConsumer(tmp_filename, true); PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) MSSpectrum first_spectrum = exp.getSpectrum(0); cached_consumer->setExpectedSize(2,0); TEST_EQUAL(!exp.getSpectrum(0).empty(), true) cached_consumer->consumeSpectrum(exp.getSpectrum(0)); TEST_EQUAL(exp.getSpectrum(0).size(), 0) TEST_EQUAL(exp.getSpectrum(0) == first_spectrum, false) delete cached_consumer; } { std::string tmp_filename; NEW_TMP_FILE(tmp_filename); MSDataCachedConsumer * cached_consumer = new MSDataCachedConsumer(tmp_filename, false); PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) MSSpectrum first_spectrum = exp.getSpectrum(0); cached_consumer->setExpectedSize(2,0); TEST_EQUAL(!exp.getSpectrum(0).empty(), true) cached_consumer->consumeSpectrum(exp.getSpectrum(0)); TEST_EQUAL(!exp.getSpectrum(0).empty(), true) TEST_EQUAL(exp.getSpectrum(0) == first_spectrum, true) delete cached_consumer; } } END_SECTION START_SECTION((void setExpectedSize(Size expectedSpectra, Size expectedChromatograms))) NOT_TESTABLE // tested above END_SECTION START_SECTION([EXTRA] test empty file) { // try an empty file std::string tmp_filename; NEW_TMP_FILE(tmp_filename); MSDataCachedConsumer * cached_consumer = new MSDataCachedConsumer(tmp_filename, false); delete cached_consumer; // Check whether it was written to disk correctly... { // Create the index from the given file Internal::CachedMzMLHandler cache; cache.createMemdumpIndex(tmp_filename); std::vector<std::streampos> spectra_index = cache.getSpectraIndex(); TEST_EQUAL(cache.getSpectraIndex().size(), 0) TEST_EQUAL(cache.getChromatogramIndex().size(), 0) } } END_SECTION START_SECTION((void setExperimentalSettings(const ExperimentalSettings&))) { std::string tmp_filename; NEW_TMP_FILE(tmp_filename); MSDataCachedConsumer * cached_consumer = new MSDataCachedConsumer(tmp_filename, true); cached_consumer->setExpectedSize(2,0); ExperimentalSettings s; cached_consumer->setExperimentalSettings( s ); TEST_NOT_EQUAL(cached_consumer, cached_consumer_nullPointer) delete cached_consumer; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TransformationXMLFile_test.cpp
.cpp
7,968
207
// 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/FORMAT/TransformationXMLFile.h> /////////////////////////// START_TEST(FASTAFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; TransformationXMLFile* ptr = nullptr; TransformationXMLFile* nullPointer = nullptr; START_SECTION((TransformationXMLFile())) { ptr = new TransformationXMLFile(); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; } END_SECTION START_SECTION([EXTRA] static bool isValid(const String& filename)) { TransformationXMLFile f; TEST_EQUAL(f.isValid(OPENMS_GET_TEST_DATA_PATH("TransformationXMLFile_1.trafoXML"), std::cerr), true); TEST_EQUAL(f.isValid(OPENMS_GET_TEST_DATA_PATH("TransformationXMLFile_2.trafoXML"), std::cerr), true); TEST_EQUAL(f.isValid(OPENMS_GET_TEST_DATA_PATH("TransformationXMLFile_3.trafoXML"), std::cerr), false); TEST_EQUAL(f.isValid(OPENMS_GET_TEST_DATA_PATH("TransformationXMLFile_4.trafoXML"), std::cerr), true); } END_SECTION START_SECTION(void load(const String & filename, TransformationDescription & transformation, bool fit_model=true)) { TransformationDescription trafo; TransformationXMLFile trafo_xml; Param params; trafo_xml.load(OPENMS_GET_TEST_DATA_PATH("TransformationXMLFile_1.trafoXML"), trafo); TEST_STRING_EQUAL(trafo.getModelType(), "none"); params = trafo.getModelParameters(); TEST_EQUAL(params.empty(), true); trafo_xml.load(OPENMS_GET_TEST_DATA_PATH("TransformationXMLFile_2.trafoXML"), trafo); TEST_STRING_EQUAL(trafo.getModelType(), "linear"); params = trafo.getModelParameters(); TEST_EQUAL(params.size(), 2); TEST_REAL_SIMILAR(params.getValue("slope"), 3.141592653589793238); TEST_REAL_SIMILAR(params.getValue("intercept"), 2.718281828459045235); trafo_xml.load(OPENMS_GET_TEST_DATA_PATH("TransformationXMLFile_4.trafoXML"), trafo); TEST_STRING_EQUAL(trafo.getModelType(), "interpolated"); params = trafo.getModelParameters(); TEST_EQUAL(params.getValue("interpolation_type"), "linear"); TEST_EQUAL(trafo.getDataPoints().size(), 3); TEST_REAL_SIMILAR(trafo.getDataPoints()[0].first, 1.2); TEST_REAL_SIMILAR(trafo.getDataPoints()[1].first, 2.2); TEST_REAL_SIMILAR(trafo.getDataPoints()[2].first, 3.2); TEST_REAL_SIMILAR(trafo.getDataPoints()[0].second, 5.2); TEST_REAL_SIMILAR(trafo.getDataPoints()[1].second, 6.25); TEST_REAL_SIMILAR(trafo.getDataPoints()[2].second, 7.3); // also test the option of not performing the actual model fit trafo_xml.load(OPENMS_GET_TEST_DATA_PATH("TransformationXMLFile_2.trafoXML"), trafo, false); TEST_STRING_EQUAL(trafo.getModelType(), "none"); params = trafo.getModelParameters(); TEST_EQUAL(params.empty(), true); } END_SECTION START_SECTION(void store(String filename, const TransformationDescription& transformation)) { TransformationDescription trafo, trafo2; TransformationXMLFile trafo_xml; String tmp_file_none; Param params; trafo.fitModel("none", params); NEW_TMP_FILE(tmp_file_none); trafo_xml.store(tmp_file_none, trafo); trafo_xml.load(tmp_file_none, trafo2); TEST_STRING_EQUAL(trafo2.getModelType(), "none"); params = trafo2.getModelParameters(); TEST_EQUAL(params.empty(), true); { double pre_image = 234255132.43212; double image = trafo.apply(pre_image); STATUS("Here is an invocation of trafo.apply(): pre_image: " << pre_image << " image: " << image); } String tmp_file_linear; NEW_TMP_FILE(tmp_file_linear); params.setValue("slope", 3.141592653589793238); params.setValue("intercept", 2.718281828459045235); trafo.fitModel("linear", params); trafo_xml.store(tmp_file_linear, trafo); trafo_xml.load(tmp_file_linear, trafo2); TEST_STRING_EQUAL(trafo.getModelType(), "linear"); params.clear(); params = trafo2.getModelParameters(); TEST_EQUAL(params.size(), 2); TEST_REAL_SIMILAR(params.getValue("slope"), 3.141592653589793238); TEST_REAL_SIMILAR(params.getValue("intercept"), 2.718281828459045235); { double pre_image = 234255132.43212; double image = trafo.apply(pre_image); STATUS("Here is an invocation of trafo.apply(): pre_image: " << pre_image << " image: " << image); } String tmp_file_pairs; NEW_TMP_FILE(tmp_file_pairs); TransformationDescription::DataPoints pairs; pairs.push_back(make_pair(1.2, 5.2)); pairs.push_back(make_pair(2.2, 6.25)); pairs.push_back(make_pair(3.2, 7.3)); trafo.setDataPoints(pairs); params.clear(); params.setValue("interpolation_type", "linear"); trafo.fitModel("interpolated", params); trafo_xml.store(tmp_file_pairs, trafo); trafo_xml.load(tmp_file_pairs, trafo2); TEST_STRING_EQUAL(trafo2.getModelType(), "interpolated"); params = trafo2.getModelParameters(); TEST_EQUAL(params.size(), 2); TEST_STRING_EQUAL(params.getValue("interpolation_type"), "linear"); TEST_STRING_EQUAL(params.getValue("extrapolation_type"), "two-point-linear"); TEST_EQUAL(trafo2.getDataPoints().size(), 3); TEST_REAL_SIMILAR(trafo2.getDataPoints()[0].first, 1.2); TEST_REAL_SIMILAR(trafo2.getDataPoints()[1].first, 2.2); TEST_REAL_SIMILAR(trafo2.getDataPoints()[2].first, 3.2); TEST_REAL_SIMILAR(trafo2.getDataPoints()[0].second, 5.2); TEST_REAL_SIMILAR(trafo2.getDataPoints()[1].second, 6.25); TEST_REAL_SIMILAR(trafo2.getDataPoints()[2].second, 7.3); { double pre_image = 234255132.43212; double image = trafo.apply(pre_image); STATUS("Here is an invocation of trafo.apply(): pre_image: " << pre_image << " image: " << image); } TEST_EXCEPTION(Exception::IllegalArgument, trafo.fitModel("mumble_pfrwoarpfz")); #if 0 String tmp_file_bspline; NEW_TMP_FILE(tmp_file_bspline); pairs.clear(); pairs.push_back(make_pair(1.2, 5.2)); pairs.push_back(make_pair(3.2, 7.3)); pairs.push_back(make_pair(2.2, 6.25)); pairs.push_back(make_pair(2.2, 3.1)); pairs.push_back(make_pair(2.2, 7.25)); pairs.push_back(make_pair(3.0, 8.5)); pairs.push_back(make_pair(3.1, 4.7)); pairs.push_back(make_pair(1.7, 6.0)); pairs.push_back(make_pair(2.9, 4.7)); pairs.push_back(make_pair(4.2, 5.0)); pairs.push_back(make_pair(3.7, -2.4)); trafo.setDataPoints(pairs); params.clear(); params.setValue("num_breakpoints", 4); params.setValue("break_positions", "uniform"); trafo.fitModel("b_spline", params); trafo_xml.store(tmp_file_pairs, trafo); trafo_xml.load(tmp_file_pairs, trafo2); TEST_STRING_EQUAL(trafo2.getModelType(), "b_spline"); params.clear(); params = trafo2.getModelParameters(); TEST_EQUAL(params.getValue("num_breakpoints"), 4); TEST_EQUAL(params.getValue("break_positions"), "uniform"); TEST_EQUAL(params.size(), 8); TEST_EQUAL(trafo2.getDataPoints().size(), 11); TEST_REAL_SIMILAR(trafo2.getDataPoints()[0].first, 1.2); TEST_REAL_SIMILAR(trafo2.getDataPoints()[0].second, 5.2); TEST_REAL_SIMILAR(trafo2.getDataPoints()[10].first, 3.7); TEST_REAL_SIMILAR(trafo2.getDataPoints()[10].second, -2.4); for (Int breaks = 0; breaks < 10; ++breaks) { if (breaks == 1) continue; params.setValue("num_breakpoints", breaks); trafo.fitModel("b_spline", params); STATUS("breaks: " << breaks); double pre_image = 234255132.43212; double image = trafo.apply(pre_image); STATUS("Here is an invocation of trafo.apply(): pre_image: " << pre_image << " image: " << image); } #endif } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PoseClusteringShiftSuperimposer_test.cpp
.cpp
2,823
93
// 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/StandardTypes.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/PoseClusteringShiftSuperimposer.h> /////////////////////////// #include <OpenMS/KERNEL/Feature.h> using namespace OpenMS; using namespace std; typedef DPosition <2> PositionType; START_TEST(PoseClusteringShiftSuperimposer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PoseClusteringShiftSuperimposer* ptr = nullptr; PoseClusteringShiftSuperimposer* nullPointer = nullptr; START_SECTION((PoseClusteringShiftSuperimposer())) ptr = new PoseClusteringShiftSuperimposer(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~PoseClusteringShiftSuperimposer())) delete ptr; END_SECTION START_SECTION((virtual void run(const ConsensusMap& map_model, const ConsensusMap& map_scene, TransformationDescription& transformation))) std::vector<ConsensusMap> input(2); Feature feat1; Feature feat2; PositionType pos1(1,1); PositionType pos2(5,5); feat1.setPosition(pos1); feat1.setIntensity(100.0f); feat2.setPosition(pos2); feat2.setIntensity(100.0f); input[0].push_back(ConsensusFeature(feat1)); input[0].push_back(ConsensusFeature(feat2)); Feature feat3; Feature feat4; PositionType pos3(21.4,1.02); PositionType pos4(25.4,5.02); feat3.setPosition(pos3); feat3.setIntensity(100.0f); feat4.setPosition(pos4); feat4.setIntensity(100.0f); input[1].push_back(ConsensusFeature(feat3)); input[1].push_back(ConsensusFeature(feat4)); input[0].updateRanges(); input[1].updateRanges(); TransformationDescription transformation; PoseClusteringShiftSuperimposer pcat; Param params; #if 0 // switch this on for debugging params.setValue("dump_buckets","tmp_PoseClusteringShiftSuperimposer_buckets"); params.setValue("dump_pairs","tmp_PoseClusteringShiftSuperimposer_pairs"); pcat.setParameters(params); #endif pcat.run(input[0], input[1], transformation); TEST_STRING_EQUAL(transformation.getModelType(), "linear") params = transformation.getModelParameters(); TEST_EQUAL(params.size(), 2) TEST_REAL_SIMILAR(params.getValue("slope"), 1.0) TEST_REAL_SIMILAR(params.getValue("intercept"), -20.4) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DataValue_test.cpp
.cpp
30,375
1,119
// 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/DATASTRUCTURES/DataValue.h> #include <OpenMS/DATASTRUCTURES/ParamValue.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/DATASTRUCTURES/ListUtilsIO.h> #include <QString> #include <sstream> #include <iostream> // we ignore the -Wunused-value warning here, since we do not want the compiler // to report problems like // DataValue_test.cpp:285:3: warning: expression result unused [-Wunused-value] // TEST_EXCEPTION(Exception::ConversionError, (StringList)DataValue("abc,ab")) #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-value" #endif /////////////////////////// START_TEST(DataValue, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; // default ctor DataValue* dv_ptr = nullptr; DataValue* dv_nullPointer = nullptr; START_SECTION((DataValue())) // Just as a sanity check, the size of DataValue should be exactly 16 bytes // on a 64 bit system: // - 1 byte for the data type // - 1 byte for the unit type // - 4 bytes for the unit identifier (32bit integer) // - 1 byte padding // - 8 bytes for the actual data / pointers to data std::cout << "\n\n --- Size of DataValue " << sizeof(DataValue) << std::endl; dv_ptr = new DataValue; TEST_NOT_EQUAL(dv_ptr, dv_nullPointer) END_SECTION // destructor START_SECTION((virtual ~DataValue())) delete dv_ptr; END_SECTION // ctor for all supported types a DataValue object can hold START_SECTION((DataValue(long double))) long double x = -3.4L; DataValue d(x); // Note: The implementation uses typedef double (as opposed to float, double, long double.) TEST_REAL_SIMILAR((double)d, -3.4L) END_SECTION START_SECTION((DataValue(double))) double x = -3.0; DataValue d(x); // Note: The implementation uses typedef double (as opposed to float, double, long double.) TEST_REAL_SIMILAR((double)d, -3.0); END_SECTION START_SECTION((DataValue(float))) float x = 3.0; DataValue d(x); // Note: The implementation uses typedef double (as opposed to float, double, long double.) TEST_REAL_SIMILAR((double)d, 3.0); END_SECTION START_SECTION((DataValue(short int))) short int n = -3000; DataValue d(n); TEST_EQUAL((short int)d, -3000) END_SECTION START_SECTION((DataValue(unsigned short int))) unsigned short int n = 3000u; DataValue d(n); TEST_EQUAL((unsigned short)d, 3000u) END_SECTION START_SECTION((DataValue(int))) int n = -3000; DataValue d(n); TEST_EQUAL((int)d, -3000) END_SECTION START_SECTION((DataValue(unsigned))) unsigned int n = 3000u; DataValue d(n); TEST_EQUAL((unsigned int)d, 3000u) END_SECTION START_SECTION((DataValue(long int))) long int n = -3000; DataValue d(n); TEST_EQUAL((long int)d, -3000) END_SECTION START_SECTION((DataValue(unsigned long))) unsigned long int n = 3000u; DataValue d(n); TEST_EQUAL((unsigned long int)d, 3000u) END_SECTION START_SECTION((DataValue(long long))) long long n = -3000; DataValue d(n); TEST_EQUAL((long long) d, -3000) END_SECTION START_SECTION((DataValue(unsigned long long))) unsigned long long n = 3000; DataValue d(n); TEST_EQUAL((unsigned long long) d, 3000) END_SECTION START_SECTION((DataValue(const char*))) const char* s = "test char"; DataValue d(s); TEST_EQUAL((std::string)d, "test char") END_SECTION START_SECTION((DataValue(const std::string&))) string s = "test string"; DataValue d(s); TEST_EQUAL((String)d, "test string") END_SECTION START_SECTION((DataValue(const QString&))) QString s = "test string"; DataValue d(s); TEST_EQUAL((String)d, "test string") END_SECTION START_SECTION((DataValue(const String&))) String s = "test string"; DataValue d(s); TEST_EQUAL((String)d, "test string") END_SECTION START_SECTION((DataValue(const StringList &))) StringList sl; sl << "test string" << "test String 2"; DataValue d(sl); TEST_TRUE(d == sl) END_SECTION START_SECTION((DataValue(const IntList &))) IntList il; il.push_back(1); il.push_back(2); DataValue d(il); TEST_TRUE(d == il) END_SECTION START_SECTION((DataValue(const DoubleList &))) DoubleList dl; dl.push_back(1.2); dl.push_back(22.3333); DataValue d(dl); DoubleList dldv = d; TEST_TRUE(dldv == dl); END_SECTION // copy ctor START_SECTION((DataValue(const DataValue&))) { DataValue p1((double) 1.23); DataValue p3((float) 1.23); DataValue p4((Int) -3); DataValue p5((UInt) 123); DataValue p6("test char"); DataValue p7(std::string("test string")); DataValue p8(ListUtils::create<String>("test string,string2,last string")); DataValue p9; DataValue p10(ListUtils::create<Int>("1,2,3,4,5")); DataValue p11(ListUtils::create<double>("1.2,2.3,3.4")); DataValue copy_of_p1(p1); DataValue copy_of_p3(p3); DataValue copy_of_p4(p4); DataValue copy_of_p5(p5); DataValue copy_of_p6(p6); DataValue copy_of_p7(p7); DataValue copy_of_p8(p8); DataValue copy_of_p9(p9); DataValue copy_of_p10(p10); DataValue copy_of_p11(p11); TEST_REAL_SIMILAR( (double) copy_of_p1, 1.23) TEST_REAL_SIMILAR( (float) copy_of_p3, 1.23) TEST_EQUAL( (Int) copy_of_p4, -3) TEST_EQUAL( (UInt) copy_of_p5, 123) TEST_EQUAL( (std::string) copy_of_p6, "test char") TEST_EQUAL( (std::string) copy_of_p7, "test string") TEST_EQUAL( copy_of_p8 == ListUtils::create<String>("test string,string2,last string"), true) TEST_EQUAL( (copy_of_p9.isEmpty()), true) TEST_EQUAL( copy_of_p10 == ListUtils::create<Int>("1,2,3,4,5"), true) TEST_EQUAL( copy_of_p11 == ListUtils::create<double>("1.2,2.3,3.4"), true) DataValue val; { DataValue p1((double) 1.23); p1.setUnit(8); val = DataValue(p1); } DataValue val2(val); TEST_REAL_SIMILAR( (double) val, 1.23) TEST_EQUAL( val.getUnit(), 8) TEST_REAL_SIMILAR( (double) val2, 1.23) TEST_EQUAL( val2.getUnit(), 8) } END_SECTION // move ctor START_SECTION((DataValue(DataValue&&) noexcept)) { // Ensure that DataValue has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(DataValue(std::declval<DataValue&&>())), true) DataValue empty; DataValue p1((double) 1.23); DataValue p3((float) 1.23); DataValue p4((Int) -3); DataValue p5((UInt) 123); DataValue p6("test char"); DataValue p7(std::string("test string")); DataValue p8(ListUtils::create<String>("test string,string2,last string")); DataValue p9; DataValue p10(ListUtils::create<Int>("1,2,3,4,5")); DataValue p11(ListUtils::create<double>("1.2,2.3,3.4")); DataValue copy_of_p1(std::move(p1)); DataValue copy_of_p3(std::move(p3)); DataValue copy_of_p4(std::move(p4)); DataValue copy_of_p5(std::move(p5)); DataValue copy_of_p6(std::move(p6)); DataValue copy_of_p7(std::move(p7)); DataValue copy_of_p8(std::move(p8)); DataValue copy_of_p9(std::move(p9)); DataValue copy_of_p10(std::move(p10)); DataValue copy_of_p11(std::move(p11)); TEST_REAL_SIMILAR( (double) copy_of_p1, 1.23) TEST_REAL_SIMILAR( (float) copy_of_p3, 1.23) TEST_EQUAL( (Int) copy_of_p4, -3) TEST_EQUAL( (UInt) copy_of_p5, 123) TEST_EQUAL( (std::string) copy_of_p6, "test char") TEST_EQUAL( (std::string) copy_of_p7, "test string") TEST_EQUAL( copy_of_p8 == ListUtils::create<String>("test string,string2,last string"), true) TEST_EQUAL( (copy_of_p9.isEmpty()), true) TEST_EQUAL( copy_of_p10 == ListUtils::create<Int>("1,2,3,4,5"), true) TEST_EQUAL( copy_of_p11 == ListUtils::create<double>("1.2,2.3,3.4"), true) TEST_TRUE(p1 == empty) TEST_TRUE(p3 == empty) TEST_TRUE(p4 == empty) TEST_TRUE(p5 == empty) TEST_TRUE(p6 == empty) TEST_TRUE(p7 == empty) TEST_TRUE(p8 == empty) TEST_TRUE(p9 == empty) TEST_TRUE(p10 == empty) TEST_TRUE(p11 == empty) DataValue val; { DataValue p1((double) 1.23); p1.setUnit(8); val = DataValue(p1); } DataValue val2(std::move(val)); TEST_TRUE(val == empty) TEST_REAL_SIMILAR( (double) val2, 1.23) TEST_EQUAL( val2.getUnit(), 8) } END_SECTION // assignment operator START_SECTION((DataValue& operator=(const DataValue&))) { DataValue p1((double) 1.23); DataValue p3((float) 1.23); DataValue p4((Int) -3); DataValue p5((UInt) 123); DataValue p6("test char"); DataValue p7(std::string("test string")); DataValue p8(ListUtils::create<String>("test string,string2,last string")); DataValue p9; DataValue p10(ListUtils::create<Int>("1,2,3,4,5")); DataValue p11(ListUtils::create<double>("1.2,2.3,3.4")); DataValue copy_of_p; copy_of_p = p1; TEST_REAL_SIMILAR( (double) copy_of_p, 1.23) copy_of_p = p3; TEST_REAL_SIMILAR( (float) copy_of_p, 1.23) copy_of_p = p4; TEST_EQUAL( (Int) copy_of_p, -3) copy_of_p = p5; TEST_EQUAL( (UInt) copy_of_p, 123) copy_of_p = p6; TEST_EQUAL( (std::string) copy_of_p, "test char") copy_of_p = p7; TEST_EQUAL( (std::string) copy_of_p, "test string") copy_of_p = p8; TEST_EQUAL( copy_of_p == ListUtils::create<String>("test string,string2,last string"), true) copy_of_p = p9; TEST_EQUAL( (copy_of_p.isEmpty()), true) copy_of_p = p10; TEST_EQUAL(copy_of_p == ListUtils::create<Int>("1,2,3,4,5"), true) copy_of_p = p11; TEST_EQUAL(copy_of_p == ListUtils::create<double>("1.2,2.3,3.4"), true) DataValue val; { DataValue p1((double) 1.23); p1.setUnit(9); val = p1; } DataValue val2 = val; TEST_REAL_SIMILAR( (double) val, 1.23) TEST_EQUAL( val.getUnit(), 9) TEST_REAL_SIMILAR( (double) val2, 1.23) TEST_EQUAL( val2.getUnit(), 9) } END_SECTION // move assignment operator START_SECTION(( DataValue& operator=(DataValue&&) noexcept )) { // Ensure that DataValue has a no-except move assignment operator. TEST_EQUAL(noexcept(declval<DataValue&>() = declval<DataValue &&>()), true) DataValue empty; DataValue p1((double) 1.23); DataValue p3((float) 1.23); DataValue p4((Int) -3); DataValue p5((UInt) 123); DataValue p6("test char"); DataValue p7(std::string("test string")); DataValue p8(ListUtils::create<String>("test string,string2,last string")); DataValue p9; DataValue p10(ListUtils::create<Int>("1,2,3,4,5")); DataValue p11(ListUtils::create<double>("1.2,2.3,3.4")); DataValue copy_of_p; copy_of_p = std::move(p1); TEST_REAL_SIMILAR( (double) copy_of_p, 1.23) copy_of_p = std::move(p3); TEST_REAL_SIMILAR( (float) copy_of_p, 1.23) copy_of_p = std::move(p4); TEST_EQUAL( (Int) copy_of_p, -3) copy_of_p = std::move(p5); TEST_EQUAL( (UInt) copy_of_p, 123) copy_of_p = std::move(p6); TEST_EQUAL( (std::string) copy_of_p, "test char") copy_of_p = std::move(p7); TEST_EQUAL( (std::string) copy_of_p, "test string") copy_of_p = std::move(p8); TEST_EQUAL( copy_of_p == ListUtils::create<String>("test string,string2,last string"), true) copy_of_p = std::move(p9); TEST_EQUAL( (copy_of_p.isEmpty()), true) copy_of_p = std::move(p10); TEST_EQUAL(copy_of_p == ListUtils::create<Int>("1,2,3,4,5"), true) copy_of_p = std::move(p11); TEST_EQUAL(copy_of_p == ListUtils::create<double>("1.2,2.3,3.4"), true) TEST_TRUE(p1 == empty) TEST_TRUE(p3 == empty) TEST_TRUE(p4 == empty) TEST_TRUE(p5 == empty) TEST_TRUE(p6 == empty) TEST_TRUE(p7 == empty) TEST_TRUE(p8 == empty) TEST_TRUE(p9 == empty) TEST_TRUE(p10 == empty) TEST_TRUE(p11 == empty) DataValue val; { DataValue p1((double) 1.23); p1.setUnit(8); val = p1; } DataValue val2 = std::move(val); TEST_TRUE(val == empty) TEST_REAL_SIMILAR( (double) val2, 1.23) TEST_EQUAL( val2.getUnit(), 8) } END_SECTION // Is DataValue object empty? START_SECTION((bool isEmpty() const)) { DataValue p1; TEST_EQUAL(p1.isEmpty(), true); DataValue p2((float)1.2); TEST_EQUAL(p2.isEmpty(), false); TEST_REAL_SIMILAR((float) p2, 1.2); DataValue p3(""); TEST_EQUAL(p3.isEmpty(), false); // empty string does not count as empty! DataValue p4("2"); TEST_EQUAL(p4.isEmpty(), false) TEST_EQUAL((std::string) p4, "2"); } END_SECTION // conversion operators START_SECTION((operator ParamValue() const)) { int i = 12; double d = 3.41; String s = "test"; IntList i_l = {1, 2}; DoubleList d_l = {2.71, 3.41}; StringList s_l = {"test", "list"}; vector<std::string> std_s_l = {"test", "list"}; DataValue d_i(i); ParamValue p_i = d_i; TEST_EQUAL(p_i, ParamValue(i)) DataValue d_d(d); ParamValue p_d = d_d; TEST_EQUAL(p_d, ParamValue(d)) DataValue d_s(s); ParamValue p_s = d_s; TEST_EQUAL(p_s, ParamValue(s)) DataValue d_i_l(i_l); ParamValue p_i_l = d_i_l; TEST_EQUAL(p_i_l, ParamValue(i_l)) DataValue d_d_l(d_l); ParamValue p_d_l = d_d_l; TEST_EQUAL(p_d_l, ParamValue(d_l)) DataValue d_s_l(s_l); ParamValue p_s_l = d_s_l; TEST_EQUAL(p_s_l, ParamValue(std_s_l)) } END_SECTION START_SECTION((operator std::string() const)) DataValue d((std::string) "test string"); std::string k = d; TEST_EQUAL(k,"test string") END_SECTION START_SECTION((operator StringList() const)) StringList sl; sl << "test string list"; DataValue d(sl); StringList sl_op = d; TEST_TRUE(sl_op == d) END_SECTION START_SECTION((StringList toStringList() const)) StringList sl; sl << "test string list"; DataValue d(sl); StringList sl_op = d.toStringList(); TEST_TRUE(sl_op == d) END_SECTION START_SECTION((operator IntList() const)) IntList il; il.push_back(1); il.push_back(2); DataValue d(il); IntList il_op = d; TEST_TRUE(il_op == il) TEST_EXCEPTION(Exception::ConversionError, StringList sl = DataValue("abc,ab");) END_SECTION START_SECTION((IntList toIntList() const)) IntList il; il.push_back(1); il.push_back(2); DataValue d(il); IntList il_op = d.toIntList(); TEST_TRUE(il_op == il) TEST_EXCEPTION(Exception::ConversionError, StringList sl = DataValue("abc,ab").toStringList();) END_SECTION START_SECTION((operator DoubleList() const)) DoubleList dl; dl.push_back(1.2); dl.push_back(22.34455); DataValue d(dl); DoubleList dl_op = d; TEST_TRUE(dl_op == d); END_SECTION START_SECTION((DoubleList toDoubleList() const)) DoubleList dl; dl.push_back(1.2); dl.push_back(22.34455); DataValue d(dl); DoubleList dl_op = d.toDoubleList(); TEST_TRUE(dl_op == d); END_SECTION START_SECTION((operator long double() const)) DataValue d(5.4L); long double k = d; TEST_REAL_SIMILAR(k,5.4L) END_SECTION START_SECTION((operator double() const)) DataValue d(5.4); double k = d; TEST_REAL_SIMILAR(k,5.4) END_SECTION START_SECTION((operator float() const)) DataValue d(5.4f); float k = d; TEST_REAL_SIMILAR(k,5.4f) END_SECTION START_SECTION((operator int() const )) DataValue d((Int) -55); int k = d; TEST_EQUAL(k,-55) TEST_EXCEPTION(Exception::ConversionError, (int)DataValue(55.4)) END_SECTION START_SECTION((operator unsigned int() const )) DataValue d((Int) 55); unsigned int k = d; TEST_EQUAL(k,55) TEST_EXCEPTION(Exception::ConversionError, (unsigned int)DataValue(-55)) TEST_EXCEPTION(Exception::ConversionError, (unsigned int)DataValue(55.4)) END_SECTION START_SECTION((operator short int() const)) DataValue d((short int) -55); short int k = d; TEST_EQUAL(k,-55) TEST_EXCEPTION(Exception::ConversionError, (short int)DataValue(55.4)) END_SECTION START_SECTION((operator unsigned short int() const)) DataValue d((short int) 55); unsigned short int k = d; TEST_EQUAL(k,55) TEST_EXCEPTION(Exception::ConversionError, (unsigned short int)DataValue(-55)) TEST_EXCEPTION(Exception::ConversionError, (unsigned short int)DataValue(55.4)) END_SECTION START_SECTION((operator long int() const)) DataValue d((long int) -55); long int k = d; TEST_EQUAL(k,-55) TEST_EXCEPTION(Exception::ConversionError, (long int)DataValue(55.4)) END_SECTION START_SECTION((operator unsigned long int() const)) DataValue d((long int) 55); unsigned long int k = d; TEST_EQUAL(k,55) TEST_EXCEPTION(Exception::ConversionError, (unsigned long int)DataValue(-55)) TEST_EXCEPTION(Exception::ConversionError, (unsigned long int)DataValue(55.4)) END_SECTION START_SECTION((operator long long() const)) { { DataValue d((long long) 55); long long k = d; TEST_EQUAL(k,55) } { DataValue d((long long) -1); long long k = d; TEST_EQUAL(k,-1) } { DataValue d((SignedSize) -55); SignedSize k = d; TEST_EQUAL(k,-55) } TEST_EXCEPTION(Exception::ConversionError, (long int)DataValue(55.4)) } END_SECTION START_SECTION((operator unsigned long long() const)) { { DataValue d((unsigned long long) 55); unsigned long long k = d; TEST_EQUAL(k,55) } { DataValue d((Size) 55); Size k = d; TEST_EQUAL(k,55) } TEST_EXCEPTION(Exception::ConversionError, (unsigned long int)DataValue(-55)) TEST_EXCEPTION(Exception::ConversionError, (unsigned long int)DataValue(55.4)) } END_SECTION START_SECTION(([EXTRA] friend bool operator==(const DataValue&, const DataValue&))) { DataValue a(5.0); DataValue b(5.0); TEST_EQUAL(a==b,true); a = DataValue((double)15.13); b = DataValue((double)15.13); TEST_EQUAL(a==b,true); a = DataValue((float)15.13); b = DataValue((float)(17-1.87)); TEST_EQUAL(a==b,true); a = DataValue((Int)5); b = DataValue((Int)5); TEST_EQUAL(a==b,true); a = DataValue((UInt)5000); b = DataValue((UInt)5000); TEST_EQUAL(a==b,true); a = DataValue("hello"); b = DataValue(std::string("hello")); TEST_EQUAL(a==b,true); a = DataValue((float)15.13); b = DataValue((float)(15.13001)); TEST_EQUAL(a==b,false); a = DataValue("hello"); b = DataValue(std::string("hello")); TEST_EQUAL(a==b,true); a.setUnitType(DataValue::UnitType::MS_ONTOLOGY); TEST_EQUAL(a==b,false); b.setUnitType(DataValue::UnitType::MS_ONTOLOGY); TEST_EQUAL(a==b,true); a.setUnit(1); TEST_EQUAL(a==b,false); b.setUnit(1); TEST_EQUAL(a==b,true); } END_SECTION START_SECTION(([EXTRA] friend bool operator!=(const DataValue&, const DataValue&))) { DataValue a(5.0); DataValue b(5.1); TEST_EQUAL(a!=b,true); a = DataValue((double)15.13001); b = DataValue((double)15.13); TEST_EQUAL(a!=b,true); a = DataValue("hello"); b = DataValue(std::string("hello")); TEST_EQUAL(a!=b,false); } END_SECTION START_SECTION((const char* toChar() const)) DataValue a; TEST_EQUAL(a.toChar() == nullptr, true) a = DataValue("hello"); TEST_STRING_EQUAL(a.toChar(),"hello") a = DataValue(5); TEST_EXCEPTION(Exception::ConversionError, a.toChar() ) END_SECTION START_SECTION((String toString(bool full_precision) const)) DataValue a; TEST_EQUAL(a.toString(), "") a = DataValue("hello"); TEST_EQUAL(a.toString(),"hello") a = DataValue(5); TEST_EQUAL(a.toString(), "5") a = DataValue(47.11); TEST_EQUAL(a.toString(), "47.109999999999999") TEST_EQUAL(a.toString(false), "47.11") a = DataValue(-23456.78); TEST_EQUAL(a.toString(), "-2.345678e04") a = DataValue(ListUtils::create<String>("test string,string2,last string")); TEST_EQUAL(a.toString(), "[test string, string2, last string]") a = DataValue(ListUtils::create<Int>("1,2,3,4,5")); TEST_EQUAL(a.toString(),"[1, 2, 3, 4, 5]") a = DataValue(ListUtils::create<double>("1.2,47.11,1.2345678e05")); TEST_EQUAL(a.toString(),"[1.2, 47.109999999999999, 1.2345678e05]") TEST_EQUAL(a.toString(false), "[1.2, 47.11, 1.235e05]") END_SECTION START_SECTION((bool toBool() const)) //valid cases DataValue a("true"); TEST_EQUAL(a.toBool(),true) a = DataValue("false"); TEST_EQUAL(a.toBool(),false) //invalid cases a = DataValue(); TEST_EXCEPTION(Exception::ConversionError, a.toBool() ) a = DataValue("bla"); TEST_EXCEPTION(Exception::ConversionError, a.toBool() ) a = DataValue(12); TEST_EXCEPTION(Exception::ConversionError, a.toBool() ) a = DataValue(34.45); TEST_EXCEPTION(Exception::ConversionError, a.toBool() ) END_SECTION START_SECTION((QString toQString() const)) DataValue a; TEST_EQUAL(a.toQString().toStdString(), "") a = DataValue("hello"); TEST_EQUAL(a.toQString().toStdString(),"hello") a = DataValue(5); TEST_EQUAL(a.toQString().toStdString(), "5") a = DataValue(47.11); TEST_EQUAL(a.toQString().toStdString(), "47.109999999999999") a = DataValue(-23456.78); TEST_EQUAL(a.toQString().toStdString(), "-2.345678e04") a = DataValue(ListUtils::create<String>("test string,string2,last string")); TEST_EQUAL(a.toQString().toStdString(), "[test string, string2, last string]") a =DataValue(ListUtils::create<Int>("1,2,3")); TEST_EQUAL(a.toQString().toStdString(), "[1, 2, 3]") a = DataValue(ListUtils::create<double>("1.22,43.23232")); TEST_EQUAL(a.toQString().toStdString(),"[1.22, 43.232320000000001]") END_SECTION START_SECTION(([EXTRA] friend std::ostream& operator<<(std::ostream&, const DataValue&))) DataValue a((Int)5), b((UInt)100), c((double)1.111), d((double)1.1), e("hello "), f(std::string("world")), g; std::ostringstream os; os << a << b << c << d << e << f << g; TEST_EQUAL(os.str(),"51001.1111.1hello world") END_SECTION START_SECTION((DataType valueType() const)) DataValue a; TEST_EQUAL(a.valueType(), DataValue::EMPTY_VALUE); DataValue a1(1.45); TEST_EQUAL(a1.valueType(), DataValue::DOUBLE_VALUE); DataValue a2(1.34f); TEST_EQUAL(a2.valueType(), DataValue::DOUBLE_VALUE); DataValue a3(123); TEST_EQUAL(a3.valueType(), DataValue::INT_VALUE); DataValue a4("bla"); TEST_EQUAL(a4.valueType(), DataValue::STRING_VALUE); DataValue a5(ListUtils::create<String>("test string,string2,last string")); TEST_EQUAL(a5.valueType(), DataValue::STRING_LIST) DataValue a6(UInt(2)); TEST_EQUAL(a6.valueType(), DataValue::INT_VALUE); DataValue a7(ListUtils::create<Int>("1,2,3")); TEST_EQUAL(a7.valueType(),DataValue::INT_LIST) DataValue a8(ListUtils::create<double>("1.2,32.4567")); TEST_EQUAL(a8.valueType(),DataValue::DOUBLE_LIST); END_SECTION START_SECTION((bool hasUnit() const)) { DataValue a; TEST_EQUAL(a.hasUnit(), false) DataValue a1("bla"); TEST_EQUAL(a1.hasUnit(), false) DataValue a2(1.45); TEST_EQUAL(a2.hasUnit(), false) a2.setUnit(16); // "millimeters" TEST_EQUAL(a2.hasUnit(), true) } END_SECTION START_SECTION((const String& getUnit() const)) { DataValue a; TEST_EQUAL(a.getUnit(), -1) DataValue a1(2.2); TEST_EQUAL(a1.getUnit(), -1) a1.setUnit(169); // id: UO:0000169 name: parts per million TEST_EQUAL(a1.getUnit(), 169) } END_SECTION START_SECTION((void setUnit(const String& unit))) { DataValue a1(2.2); TEST_EQUAL(a1.getUnit(), -1) a1.setUnit(169); // id: UO:0000169 name: parts per million TEST_EQUAL(a1.getUnit(), 169) a1.setUnit(9); // id: UO:0000009 name: kilogram TEST_EQUAL(a1.getUnit(), 9) a1.setUnit(a1.getUnit()); TEST_EQUAL(a1.hasUnit(), true) TEST_EQUAL(a1.getUnit(), 9) } END_SECTION START_SECTION((inline UnitType getUnitType() const)) { DataValue a("v"); TEST_EQUAL(a.getUnitType(), DataValue::UnitType::OTHER) } END_SECTION START_SECTION((inline void setUnitType(const UnitType & u))) { DataValue a("v"); a.setUnitType(DataValue::UnitType::MS_ONTOLOGY); TEST_EQUAL(a.getUnitType(), DataValue::UnitType::MS_ONTOLOGY) a.setUnitType(DataValue::UnitType::UNIT_ONTOLOGY); TEST_EQUAL(a.getUnitType(), DataValue::UnitType::UNIT_ONTOLOGY) } END_SECTION START_SECTION((DataValue& operator=(const char*))) { const char * v = "value"; DataValue a("v"); a = v; TEST_EQUAL((String)a, "value") } END_SECTION START_SECTION((DataValue& operator=(const std::string&))) { std::string v = "value"; DataValue a("v"); a = v; TEST_EQUAL((String)a, "value") } END_SECTION START_SECTION((DataValue& operator=(const String&))) { String v = "value"; DataValue a("v"); a = v; TEST_EQUAL((String)a, "value") } END_SECTION START_SECTION((DataValue& operator=(const QString&))) { QString v = "value"; DataValue a("v"); a = v; TEST_EQUAL((String)a, "value") } END_SECTION START_SECTION((DataValue& operator=(const StringList&))) { StringList v = ListUtils::create<String>("value,value2"); DataValue a("v"); a = v; StringList sla = a; TEST_EQUAL(sla.size(), 2) ABORT_IF(sla.size() != 2) TEST_EQUAL(sla[0], "value") TEST_EQUAL(sla[1], "value2") } END_SECTION START_SECTION((DataValue& operator=(const IntList&))) { IntList v = ListUtils::create<Int>("2,-3"); DataValue a("v"); a = v; IntList dv = a; TEST_EQUAL(dv.size(), 2) ABORT_IF(dv.size() != 2) TEST_EQUAL(dv[0], 2) TEST_EQUAL(dv[1], -3) } END_SECTION START_SECTION((DataValue& operator=(const DoubleList&))) { DoubleList v = ListUtils::create<double>("2.14,-3.45"); DataValue a("v"); a = v; DoubleList adl = a; TEST_EQUAL(adl.size(), 2) ABORT_IF(adl.size() != 2) TEST_EQUAL(adl[0], 2.14) TEST_EQUAL(adl[1], -3.45) } END_SECTION START_SECTION((DataValue& operator=(const long double))) { const long double v = 2.44; DataValue a("v"); a = v; TEST_EQUAL((long double)a, 2.44) } END_SECTION START_SECTION((DataValue& operator=(const double))) { const double v = 2.44; DataValue a("v"); a = v; TEST_EQUAL((double)a, 2.44) } END_SECTION START_SECTION((DataValue& operator=(const float))) { const float v = 2.44f; DataValue a("v"); a = v; TEST_EQUAL((float)a, 2.44f) } END_SECTION START_SECTION((DataValue& operator=(const short int))) { const short int v = 2; DataValue a("v"); a = v; TEST_EQUAL((short int)a, 2) } END_SECTION START_SECTION((DataValue& operator=(const unsigned short int))) { const unsigned short int v = 2; DataValue a("v"); a = v; TEST_EQUAL((unsigned short int)a, 2) } END_SECTION START_SECTION((DataValue& operator=(const int))) { const int v = 2; DataValue a("v"); a = v; TEST_EQUAL((int)a, 2) } END_SECTION START_SECTION((DataValue& operator=(const unsigned))) { const unsigned v = 2; DataValue a("v"); a = v; TEST_EQUAL((unsigned)a, 2) } END_SECTION START_SECTION((DataValue& operator=(const long int))) { const long int v = 2; DataValue a("v"); a = v; TEST_EQUAL((long int)a, 2) } END_SECTION START_SECTION((DataValue& operator=(const unsigned long))) { const unsigned long v = 2; DataValue a("v"); a = v; TEST_EQUAL((unsigned long)a, 2) } END_SECTION START_SECTION((DataValue& operator=(const long long))) { const long long v = 2; DataValue a("v"); a = v; TEST_EQUAL((long long)a, 2) } END_SECTION START_SECTION((DataValue& operator=(const unsigned long long))) { const unsigned long long v = 2; DataValue a("v"); a = v; TEST_EQUAL((unsigned long long)a, 2) } END_SECTION START_SECTION([EXTRA] Test improved error messages for EMPTY_VALUE conversions) { DataValue empty_val; // Test EMPTY to double - should include type 'Empty' TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (double)empty_val, "Could not convert DataValue of type 'Empty' to double") // Test EMPTY to float - should include type 'Empty' TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (float)empty_val, "Could not convert DataValue of type 'Empty' to float") // Test EMPTY to long double - should include type 'Empty' TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (long double)empty_val, "Could not convert DataValue of type 'Empty' to long double") } END_SECTION START_SECTION([EXTRA] Test improved error messages for negative to unsigned conversions) { // Test negative int to unsigned int - should include the value DataValue neg_val(-42); TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (unsigned int)neg_val, "Could not convert negative integer DataValue with value '-42' to unsigned int") // Test negative int to unsigned short - should include the value DataValue neg_short(-100); TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (unsigned short)neg_short, "Could not convert negative integer DataValue with value '-100' to unsigned short int") // Test negative int to unsigned long - should include the value DataValue neg_long(-999); TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (unsigned long)neg_long, "Could not convert negative integer DataValue with value '-999' to unsigned long int") // Test negative int to unsigned long long - should include the value DataValue neg_longlong(-1234); TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (unsigned long long)neg_longlong, "Could not convert negative integer DataValue with value '-1234' to unsigned long long") } END_SECTION START_SECTION([EXTRA] Test improved error messages for type mismatch conversions) { // Test double to int - should include type and value DataValue double_val(3.14159); TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (int)double_val, "Could not convert non-integer DataValue of type 'Double' and value '3.14159' to int") // Test string to int - should include type and value DataValue string_val("hello"); TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (int)string_val, "Could not convert non-integer DataValue of type 'String' and value 'hello' to int") // Test int to string - should include type and value DataValue int_val(42); TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (std::string)int_val, "Could not convert non-string DataValue of type 'Int' and value '42' to string") // Test double to unsigned int - should include type and value DataValue double_val2(5.5); TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, (unsigned int)double_val2, "Could not convert non-integer DataValue of type 'Double' and value '5.5' to unsigned int") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST #ifdef __clang__ #pragma clang diagnostic pop #endif
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/RangeUtils_test.cpp
.cpp
12,019
434
// 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/KERNEL/RangeUtils.h> #include <OpenMS/KERNEL/MSSpectrum.h> /////////////////////////// START_TEST(RangeUtils<D>, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; //InRTRange InRTRange<MSSpectrum>* ptr = nullptr; InRTRange<MSSpectrum>* nullPointer = nullptr; START_SECTION((InRTRange(double min, double max, bool reverse = false))) ptr = new InRTRange<MSSpectrum>(5,10,false); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(([EXTRA]~InRTRange())) delete ptr; END_SECTION START_SECTION((bool operator()(const SpectrumType& s) const)) InRTRange<MSSpectrum> r(5,10,false); InRTRange<MSSpectrum> r2(5,10,true); MSSpectrum s; s.setRT(4.9); TEST_EQUAL(r(s), false); TEST_EQUAL(r2(s), true); s.setRT(5.0); TEST_EQUAL(r(s), true); TEST_EQUAL(r2(s), false); s.setRT(7.5); TEST_EQUAL(r(s), true); TEST_EQUAL(r2(s), false); s.setRT(10.0); TEST_EQUAL(r(s), true); TEST_EQUAL(r2(s), false); s.setRT(10.1); TEST_EQUAL(r(s), false); TEST_EQUAL(r2(s), true); END_SECTION //MSLevelRange InMSLevelRange<MSSpectrum>* ptr2 = nullptr; InMSLevelRange<MSSpectrum>* nullPointer2 = nullptr; START_SECTION((MSLevelRange(const IntList& levels, bool reverse = false))) IntList tmp; ptr2 = new InMSLevelRange<MSSpectrum>(tmp,false); TEST_NOT_EQUAL(ptr2, nullPointer2) END_SECTION START_SECTION(([EXTRA]~InMSLevelRange())) delete ptr2; END_SECTION START_SECTION((bool operator()(const SpectrumType& s) const)) IntList tmp; tmp.push_back(2); tmp.push_back(3); tmp.push_back(4); InMSLevelRange<MSSpectrum> r(tmp,false); InMSLevelRange<MSSpectrum> r2(tmp,true); MSSpectrum s; s.setMSLevel(1); TEST_EQUAL(r(s), false); TEST_EQUAL(r2(s), true); s.setMSLevel(2); TEST_EQUAL(r(s), true); TEST_EQUAL(r2(s), false); s.setMSLevel(3); TEST_EQUAL(r(s), true); TEST_EQUAL(r2(s), false); s.setMSLevel(4); TEST_EQUAL(r(s), true); TEST_EQUAL(r2(s), false); s.setMSLevel(5); TEST_EQUAL(r(s), false); TEST_EQUAL(r2(s), true); END_SECTION //HasScanMode HasScanMode<MSSpectrum>* ptr2_1 = nullptr; HasScanMode<MSSpectrum>* nullPointer2_1 = nullptr; START_SECTION((HasScanMode(Int mode, bool reverse = false))) ptr2_1 = new HasScanMode<MSSpectrum>(1,false); TEST_NOT_EQUAL(ptr2_1, nullPointer2_1) END_SECTION START_SECTION(([EXTRA]~HasScanMode())) delete ptr2_1; END_SECTION START_SECTION((bool operator()(const SpectrumType& s) const)) HasScanMode<MSSpectrum> r(static_cast<Int>(InstrumentSettings::ScanMode::SIM),false); HasScanMode<MSSpectrum> r2(static_cast<Int>(InstrumentSettings::ScanMode::MASSSPECTRUM),true); MSSpectrum s; s.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SIM); TEST_EQUAL(r(s), true); TEST_EQUAL(r2(s), true); s.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM); TEST_EQUAL(r(s), false); TEST_EQUAL(r2(s), false); END_SECTION //InMzRange InMzRange<Peak1D >* ptr3 = nullptr; InMzRange<Peak1D >* nullPointer3 = nullptr; START_SECTION((InMzRange(double min, double max, bool reverse = false))) ptr3 = new InMzRange<Peak1D >(5.0,10.0,false); TEST_NOT_EQUAL(ptr3, nullPointer3) END_SECTION START_SECTION(([EXTRA]~InMzRange())) delete ptr3; END_SECTION START_SECTION((bool operator()(const PeakType& p) const)) InMzRange<Peak1D > r(5.0,10.0,false); InMzRange<Peak1D > r2(5.0,10.0,true); Peak1D p; p.getPosition()[0] = 4.9; TEST_EQUAL(r(p), false); TEST_EQUAL(r2(p), true); p.getPosition()[0] = 5.0; TEST_EQUAL(r(p), true); TEST_EQUAL(r2(p), false); p.getPosition()[0] = 7.5; TEST_EQUAL(r(p), true); TEST_EQUAL(r2(p), false); p.getPosition()[0] = 10.0; TEST_EQUAL(r(p), true); TEST_EQUAL(r2(p), false); p.getPosition()[0] = 10.1; TEST_EQUAL(r(p), false); TEST_EQUAL(r2(p), true); END_SECTION //IntensityRange InIntensityRange<Peak1D >* ptr4 = nullptr; InIntensityRange<Peak1D >* nullPointer4 = nullptr; START_SECTION((IntensityRange(double min, double max, bool reverse = false))) ptr4 = new InIntensityRange<Peak1D >(5.0,10.0,false); TEST_NOT_EQUAL(ptr4, nullPointer4) END_SECTION START_SECTION(([EXTRA]~InIntensityRange())) delete ptr4; END_SECTION START_SECTION((bool operator()(const PeakType& p) const)) InIntensityRange<Peak1D > r(5.0,10.0,false); InIntensityRange<Peak1D > r2(5.0,10.0,true); Peak1D p; p.setIntensity(4.9f); TEST_EQUAL(r(p), false); TEST_EQUAL(r2(p), true); p.setIntensity(5.0f); TEST_EQUAL(r(p), true); TEST_EQUAL(r2(p), false); p.setIntensity(7.5f); TEST_EQUAL(r(p), true); TEST_EQUAL(r2(p), false); p.setIntensity(10.0f); TEST_EQUAL(r(p), true); TEST_EQUAL(r2(p), false); p.setIntensity(10.1f); TEST_EQUAL(r(p), false); TEST_EQUAL(r2(p), true); END_SECTION //IsEmptySpectrum IsEmptySpectrum<MSSpectrum>* ptr47 = nullptr; IsEmptySpectrum<MSSpectrum>* nullPointer47 = nullptr; START_SECTION((IsEmptySpectrum(bool reverse = false))) ptr47 = new IsEmptySpectrum<MSSpectrum>(); TEST_NOT_EQUAL(ptr47, nullPointer47) END_SECTION START_SECTION(([EXTRA]~IsEmptySpectrum())) delete ptr47; END_SECTION START_SECTION((bool operator()(const SpectrumType& s) const)) IsEmptySpectrum<MSSpectrum> s; IsEmptySpectrum<MSSpectrum> s2(true); MSSpectrum spec; TEST_EQUAL(s(spec), true); TEST_EQUAL(s2(spec), false); spec.resize(5); TEST_EQUAL(s(spec), false); TEST_EQUAL(s2(spec), true); END_SECTION //IsZoomSpectrum IsZoomSpectrum<MSSpectrum>* ptr48 = nullptr; IsZoomSpectrum<MSSpectrum>* nullPointer48 = nullptr; START_SECTION((IsZoomSpectrum(bool reverse = false))) ptr48 = new IsZoomSpectrum<MSSpectrum>(); TEST_NOT_EQUAL(ptr48, nullPointer48) END_SECTION START_SECTION(([EXTRA]~IsZoomSpectrum())) delete ptr48; END_SECTION START_SECTION((bool operator()(const SpectrumType& s) const)) IsZoomSpectrum<MSSpectrum> s; IsZoomSpectrum<MSSpectrum> s2(true); MSSpectrum spec; TEST_EQUAL(s(spec), false); TEST_EQUAL(s2(spec), true); spec.getInstrumentSettings().setZoomScan(true); TEST_EQUAL(s(spec), true); TEST_EQUAL(s2(spec), false); END_SECTION //HasActivationMethod HasActivationMethod<MSSpectrum>* ptr49 = nullptr; HasActivationMethod<MSSpectrum>* nullPointer49 = nullptr; START_SECTION((HasActivationMethod(const StringList& methods, bool reverse = false))) ptr49 = new HasActivationMethod<MSSpectrum>(ListUtils::create<String>("")); TEST_NOT_EQUAL(ptr49, nullPointer49) END_SECTION START_SECTION(([EXTRA]~HasActivationMethod())) delete ptr49; END_SECTION START_SECTION((bool operator()(const SpectrumType& s) const)) HasActivationMethod<MSSpectrum> s(ListUtils::create<String>(Precursor::NamesOfActivationMethod[1]+","+Precursor::NamesOfActivationMethod[2])); HasActivationMethod<MSSpectrum> s2(ListUtils::create<String>(Precursor::NamesOfActivationMethod[1]+","+Precursor::NamesOfActivationMethod[2]),true); MSSpectrum spec; std::vector<Precursor> pc; Precursor p; set <Precursor::ActivationMethod> sa1; sa1.insert( Precursor::ActivationMethod::PSD ); //occurs sa1.insert( Precursor::ActivationMethod::BIRD );//just a dummy p.setActivationMethods(sa1); pc.push_back(p); spec.setPrecursors(pc); TEST_EQUAL(s(spec), true); TEST_EQUAL(s2(spec), false); // does not occur as activation method set <Precursor::ActivationMethod> sa2; sa2.insert( Precursor::ActivationMethod::BIRD ); p.setActivationMethods(sa2); pc[0] = p; spec.setPrecursors(pc); TEST_EQUAL(s(spec), false); TEST_EQUAL(s2(spec), true); // multiple precursors: // adding another dummy set <Precursor::ActivationMethod> sa3; sa3.insert( Precursor::ActivationMethod::LCID ); p.setActivationMethods(sa3); pc.push_back(p); spec.setPrecursors(pc); TEST_EQUAL(s(spec), false); TEST_EQUAL(s2(spec), true); // adding a matching precursor set <Precursor::ActivationMethod> sa4; sa4.insert( Precursor::ActivationMethod::PD ); p.setActivationMethods(sa4); pc.push_back(p); spec.setPrecursors(pc); TEST_EQUAL(s(spec), true); TEST_EQUAL(s2(spec), false); END_SECTION //InPrecursorMZRange InPrecursorMZRange<MSSpectrum>* ptr50 = nullptr; InPrecursorMZRange<MSSpectrum>* nullPointer50 = nullptr; START_SECTION((InPrecursorMZRange(const double& mz_left, const double& mz_right, bool reverse = false))) ptr50 = new InPrecursorMZRange<MSSpectrum>(100.0, 200.0); TEST_NOT_EQUAL(ptr50, nullPointer50) END_SECTION START_SECTION(([EXTRA]~InPrecursorMZRange())) delete ptr50; END_SECTION START_SECTION((bool operator()(const SpectrumType& s) const)) InPrecursorMZRange<MSSpectrum> s(100.0, 200.0); InPrecursorMZRange<MSSpectrum> s2(100.0, 200.0,true); MSSpectrum spec; std::vector<Precursor> pc; Precursor p; p.setMZ(150.0); pc.push_back(p); spec.setPrecursors(pc); TEST_EQUAL(s(spec), true); TEST_EQUAL(s2(spec), false); // outside of allowed window p.setMZ(444.0); pc[0] = p; spec.setPrecursors(pc); TEST_EQUAL(s(spec), false); TEST_EQUAL(s2(spec), true); // multiple precursors: // adding second which is within limits... but we require all of them to be... p.setMZ(150.0); pc.push_back(p); spec.setPrecursors(pc); TEST_EQUAL(s(spec), false); TEST_EQUAL(s2(spec), true); END_SECTION //InPrecursorMZRange IsInIsolationWindow<MSSpectrum>* ptr500 = nullptr; IsInIsolationWindow<MSSpectrum>* nullPointer500 = nullptr; START_SECTION((IsInIsolationWindow(const double& mz_left, const double& mz_right, bool reverse = false))) ptr500 = new IsInIsolationWindow<MSSpectrum>(ListUtils::create<double>("100.0, 200.0")); TEST_NOT_EQUAL(ptr500, nullPointer500) END_SECTION START_SECTION(([EXTRA]~IsInIsolationWindow())) delete ptr500; END_SECTION START_SECTION((bool operator()(const SpectrumType& s) const)) IsInIsolationWindow<MSSpectrum> s(ListUtils::create<double>("300.0, 100.0, 200.0, 400.0")); // unsorted on purpose IsInIsolationWindow<MSSpectrum> s2(ListUtils::create<double>("300.0, 100.0, 200.0, 400.0"), true); MSSpectrum spec; spec.setMSLevel(2); std::vector<Precursor> pc; Precursor p; p.setMZ(200.3); p.setIsolationWindowLowerOffset(0.5); p.setIsolationWindowUpperOffset(0.5); pc.push_back(p); spec.setPrecursors(pc); TEST_EQUAL(s(spec), true); TEST_EQUAL(s2(spec), false); // outside of allowed window p.setMZ(201.1); pc[0] = p; spec.setPrecursors(pc); TEST_EQUAL(s(spec), false); TEST_EQUAL(s2(spec), true); // multiple precursors: // adding second which is within limits... so it's a hit (any PC must match) p.setMZ(299.9); pc.push_back(p); spec.setPrecursors(pc); TEST_EQUAL(s(spec), true); TEST_EQUAL(s2(spec), false); END_SECTION //HasScanPolarity HasScanPolarity<MSSpectrum>* ptr51 = nullptr; HasScanPolarity<MSSpectrum>* nullPointer51 = nullptr; START_SECTION((HasScanPolarity(IonSource::Polarity polarity,bool reverse = false))) ptr51 = new HasScanPolarity<MSSpectrum>(IonSource::Polarity::POLNULL); TEST_NOT_EQUAL(ptr48, nullPointer51) END_SECTION START_SECTION(([EXTRA]~HasScanPolarity())) delete ptr51; END_SECTION START_SECTION((bool operator()(const SpectrumType& s) const)) HasScanPolarity<MSSpectrum> s(IonSource::Polarity::POSITIVE); HasScanPolarity<MSSpectrum> s2(IonSource::Polarity::POSITIVE, true); MSSpectrum spec; TEST_EQUAL(s(spec), false); TEST_EQUAL(s2(spec), true); spec.getInstrumentSettings().setPolarity(IonSource::Polarity::POSITIVE); TEST_EQUAL(s(spec), true); TEST_EQUAL(s2(spec), false); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PercolatorInfile_test.cpp
.cpp
2,098
65
// 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/FORMAT/PercolatorInfile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(PercolatorInfile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PercolatorInfile* ptr = nullptr; PercolatorInfile* null_pointer = nullptr; START_SECTION(PercolatorInfile()) { ptr = new PercolatorInfile(); TEST_NOT_EQUAL(ptr, null_pointer); } END_SECTION START_SECTION(~PercolatorInfile()) { delete ptr; } END_SECTION START_SECTION(PeptideIdentificationList PercolatorInfile::load(const String& pin_file, bool higher_score_better, const String& score_name, String decoy_prefix)) { StringList filenames; // test loading of pin file with automatic update of target/decoy annotation based on decoy prefix in protein accessions // test some extra scores StringList extra_scores = {"ln(delta_next)", "ln(delta_best)", "matched_peaks"}; auto pids = PercolatorInfile::load(OPENMS_GET_TEST_DATA_PATH("sage.pin"), true, "ln(hyperscore)", extra_scores, filenames, "DECOY_"); TEST_EQUAL(pids.size(), 9) TEST_EQUAL(filenames.size(), 2) TEST_EQUAL(pids[0].getSpectrumReference(), "30381") TEST_EQUAL(pids[6].getSpectrumReference(), "spectrum=2041") TEST_EQUAL(pids[7].getHits()[0].getMetaValue("target_decoy"),"decoy") // 8th entry is annotated as target in pin file but only maps to decoy proteins with prefix "DECOY_" -> set to decoy } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TransformationModel_test.cpp
.cpp
13,545
423
// 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> /////////////////////////// START_TEST(TransformationModel, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; TransformationModel* ptr = nullptr; TransformationModel* nullPointer = nullptr; TransformationModel::DataPoints data, empty; TransformationModel::DataPoint point; point.first = 0.0; point.second = 1.0; data.push_back(point); point.first = 1.0; point.second = 2.0; data.push_back(point); point.first = 1.0; point.second = 4.0; data.push_back(point); START_SECTION((TransformationModel())) { ptr = new TransformationModel(); TEST_NOT_EQUAL(ptr, nullPointer) delete ptr; } END_SECTION START_SECTION((TransformationModel(const DataPoints&, const Param&))) { ptr = new TransformationModel(TransformationModel::DataPoints(), Param()); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((~TransformationModel())) { delete ptr; } END_SECTION START_SECTION((virtual double evaluate(double value) const)) { // null model (identity): TransformationModel tm; TEST_REAL_SIMILAR(tm.evaluate(-3.14159), -3.14159); TEST_REAL_SIMILAR(tm.evaluate(0.0), 0.0); TEST_REAL_SIMILAR(tm.evaluate(12345678.9), 12345678.9); } END_SECTION START_SECTION((void getParameters(Param& params) const)) { TransformationModel tm; Param p = tm.getParameters(); TEST_EQUAL(p.empty(), true) } END_SECTION START_SECTION(([EXTRA] static void getDefaultParameters(Param& params))) { Param param; param.setValue("some-value", 12.3); TransformationModel::getDefaultParameters(param); TEST_EQUAL(param.empty(), true) } END_SECTION START_SECTION((bool checkValidWeight(const string& weight, const vector<string>& valid_weights) const)) { Param param; TransformationModel dw(data, param); string test; test = "ln(x)"; TEST_EQUAL(dw.checkValidWeight(test,dw.getValidXWeights()), true); test = "1/y"; TEST_EQUAL(dw.checkValidWeight(test,dw.getValidYWeights()), true); test = "1/x2"; TEST_EQUAL(dw.checkValidWeight(test,dw.getValidXWeights()), true); test = "x"; TEST_EQUAL(dw.checkValidWeight(test,dw.getValidXWeights()), true); test = "y"; TEST_EQUAL(dw.checkValidWeight(test,dw.getValidYWeights()), true); test = "none"; TEST_EQUAL(dw.checkValidWeight(test,dw.getValidXWeights()), false); test = "x2"; TEST_EQUAL(dw.checkValidWeight(test,dw.getValidXWeights()), false); } END_SECTION START_SECTION((double weightDatum(double& datum, const string& weight) const)) { Param param; TransformationModel dw(data, param); string test; test = "x"; double inf = std::numeric_limits<double>::infinity(); TEST_REAL_SIMILAR(dw.weightDatum(0.0,test), 0.0); TEST_REAL_SIMILAR(dw.weightDatum(2.0,test), 2.0); test = "none"; TEST_REAL_SIMILAR(dw.weightDatum(0.0,test), 0.0); TEST_REAL_SIMILAR(dw.weightDatum(2.0,test), 2.0); test = "ln(x)"; TEST_REAL_SIMILAR(dw.weightDatum(0.0,test), -inf); TEST_REAL_SIMILAR(dw.weightDatum(2.0,test), std::log(2.0)); test = "1/x"; TEST_REAL_SIMILAR(dw.weightDatum(0.0,test), inf); TEST_REAL_SIMILAR(dw.weightDatum(2.0,test), 1/std::abs(2.0)); test = "1/x2"; TEST_REAL_SIMILAR(dw.weightDatum(0.0,test), inf); TEST_REAL_SIMILAR(dw.weightDatum(2.0,test), 1/std::abs(std::pow(2.0,2))); test = "ln(y)"; TEST_REAL_SIMILAR(dw.weightDatum(0.0,test), -inf); TEST_REAL_SIMILAR(dw.weightDatum(2.0,test), std::log(2.0)); test = "1/y"; TEST_REAL_SIMILAR(dw.weightDatum(0.0,test), inf); TEST_REAL_SIMILAR(dw.weightDatum(2.0,test), 1/std::abs(2.0)); test = "1/y2"; TEST_REAL_SIMILAR(dw.weightDatum(0.0,test), inf); TEST_REAL_SIMILAR(dw.weightDatum(2.0,test), 1/std::abs(std::pow(2.0,2))); } END_SECTION START_SECTION((double checkDatumRange(const double& datum, const double& datum_min, const double& datum_max))) //new { Param param; TransformationModel dw(data, param); double dmin = 10e-6; double dmax = 10e9; TEST_REAL_SIMILAR(dw.checkDatumRange(10e-7, dmin, dmax), dmin); TEST_REAL_SIMILAR(dw.checkDatumRange(10e12, dmin, dmax), dmax); TEST_REAL_SIMILAR(dw.checkDatumRange(100, dmin, dmax), 100); } END_SECTION START_SECTION((double weightDatum(double& datum, const string& weight) const)) { Param param; TransformationModel dw(data, param); string test; test = "x"; TEST_REAL_SIMILAR(dw.weightDatum(0.0,test), 0.0); TEST_REAL_SIMILAR(dw.weightDatum(2.0,test), 2.0); TEST_REAL_SIMILAR(dw.weightDatum(10e13,test), 10e13); double xmin = 10e-5; double xmax = 10e12; TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(0.0, xmin, xmax),test), xmin); TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(2.0, xmin, xmax),test), 2.0); TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(10e13, xmin, xmax),test), xmax); test = "none"; TEST_REAL_SIMILAR(dw.weightDatum(0.0,test), 0.0); TEST_REAL_SIMILAR(dw.weightDatum(2.0,test), 2.0); test = "ln(x)"; TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(0.0, xmin, xmax),test), std::log(xmin)); TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(2.0, xmin, xmax),test), std::log(2.0)); test = "1/x"; TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(0.0, xmin, xmax),test), 1/xmin); TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(2.0, xmin, xmax),test), 1/std::abs(2.0)); test = "1/x2"; TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(0.0, xmin, xmax),test), 1/std::pow(xmin,2)); TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(2.0, xmin, xmax),test), 1/std::abs(std::pow(2.0,2))); test = "ln(y)"; double ymin = 10e-8; double ymax = 10e12; TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(0.0, ymin, ymax),test), std::log(ymin)); TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(2.0, ymin, ymax),test), std::log(2.0)); test = "1/y"; TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(0.0, ymin, ymax),test), 1/ymin); TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(2.0, ymin, ymax),test), 1/std::abs(2.0)); test = "1/y2"; TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(0.0, ymin, ymax),test), 1/std::pow(ymin,2)); TEST_REAL_SIMILAR(dw.weightDatum(dw.checkDatumRange(2.0, ymin, ymax),test), 1/std::abs(std::pow(2.0,2))); } END_SECTION START_SECTION((virtual void weightData(DataPoints& data, const Param& params))) { TransformationModel::DataPoints data1; TransformationModel::DataPoints test1; TransformationModel::DataPoint point; Param param; TransformationModel::getDefaultParameters(param); { double xmin = 10e-5; double xmax = 10e12; double ymin = 10e-8; double ymax = 10e12; param.setValue("x_weight", "ln(x)"); param.setValue("y_weight", "y"); TransformationModel dw(data, param); test1.clear(); point.first = std::log(xmin); point.second = 1.0; test1.push_back(point); point.first = std::log(1.0); point.second = 2.0; test1.push_back(point); point.first = std::log(2.0); point.second = 4.0; test1.push_back(point); data1.clear(); point.first = dw.checkDatumRange(0.0, xmin, xmax); point.second = dw.checkDatumRange(1.0, ymin, ymax); data1.push_back(point); point.first = dw.checkDatumRange(1.0, xmin, xmax); point.second = dw.checkDatumRange(2.0, ymin, ymax); data1.push_back(point); point.first = dw.checkDatumRange(2.0, xmin, xmax); point.second = dw.checkDatumRange(4.0, ymin, ymax); data1.push_back(point); dw.weightData(data1); for (size_t i = 0; i < data1.size(); ++i) { TEST_REAL_SIMILAR(data1[i].first,test1[i].first); TEST_REAL_SIMILAR(data1[i].second,test1[i].second); } } { param.setValue("x_weight", "x"); param.setValue("y_weight", "ln(y)"); TransformationModel dw(data, param); test1.clear(); point.first = 0.0; point.second = std::log(1.0); test1.push_back(point); point.first = 1.0; point.second = std::log(2.0); test1.push_back(point); point.first = 2.0; point.second = std::log(4.0); test1.push_back(point); data1.clear(); point.first = 0.0; point.second = 1.0; data1.push_back(point); point.first = 1.0; point.second = 2.0; data1.push_back(point); point.first = 2.0; point.second = 4.0; data1.push_back(point); dw.weightData(data1); for (size_t i = 0; i < data1.size(); ++i) { TEST_REAL_SIMILAR(data1[i].first,test1[i].first); TEST_REAL_SIMILAR(data1[i].second,test1[i].second); } } } END_SECTION START_SECTION((double unWeightDatum(double& datum, const string& weight) const)) { Param param; TransformationModel dw(data, param); string test; test = "x"; TEST_REAL_SIMILAR(dw.unWeightDatum(0.0,test), 0.0); TEST_REAL_SIMILAR(dw.unWeightDatum(2.0,test), 2.0); test = "none"; TEST_REAL_SIMILAR(dw.unWeightDatum(0.0,test), 0.0); TEST_REAL_SIMILAR(dw.unWeightDatum(2.0,test), 2.0); test = "ln(x)"; TEST_REAL_SIMILAR(dw.unWeightDatum(std::log(11.0e5),test), 11e5); TEST_REAL_SIMILAR(dw.unWeightDatum(2.0,test), std::exp(2.0)); test = "1/x"; TEST_REAL_SIMILAR(dw.unWeightDatum(1/std::abs(9.0e-5),test), 9.0e-5); TEST_REAL_SIMILAR(dw.unWeightDatum(2.0,test), 1/std::abs(2.0)); test = "1/x2"; TEST_REAL_SIMILAR(dw.unWeightDatum(1/std::pow(9.0e-5,2),test), 9.0e-5); TEST_REAL_SIMILAR(dw.unWeightDatum(2.0,test), std::sqrt(1/std::abs(2.0))); test = "ln(y)"; TEST_REAL_SIMILAR(dw.unWeightDatum(std::log(11.0e8),test), 11.0e8); TEST_REAL_SIMILAR(dw.unWeightDatum(2.0,test), std::abs(std::exp(2.0))); test = "1/y"; TEST_REAL_SIMILAR(dw.unWeightDatum(1/std::abs(9.0e-8),test), 9e-8); TEST_REAL_SIMILAR(dw.unWeightDatum(2.0,test), 1/std::abs(2.0)); test = "1/y2"; TEST_REAL_SIMILAR(dw.unWeightDatum(1/std::pow(9.0e-8,2),test), 9e-8); TEST_REAL_SIMILAR(dw.unWeightDatum(2.0,test), std::sqrt(1/std::abs(2.0))); } END_SECTION START_SECTION((virtual void unWeightData(DataPoints& data, const Param& params))) { TransformationModel::DataPoints data1; TransformationModel::DataPoints test1; TransformationModel::DataPoint point; { Param param; TransformationModel::getDefaultParameters(param); param.setValue("x_weight", "ln(x)"); param.setValue("y_weight", "y"); TransformationModel dw(data, param); test1.clear(); point.first = std::exp(0.0); point.second = 1.0; test1.push_back(point); point.first = std::exp(1.0); point.second = 2.0; test1.push_back(point); point.first = std::exp(2.0); point.second = 4.0; test1.push_back(point); data1.clear(); point.first = 0.0; point.second = 1.0; data1.push_back(point); point.first = 1.0; point.second = 2.0; data1.push_back(point); point.first = 2.0; point.second = 4.0; data1.push_back(point); dw.unWeightData(data1); for (size_t i = 0; i < data1.size(); ++i) { TEST_REAL_SIMILAR(data1[i].first,test1[i].first); TEST_REAL_SIMILAR(data1[i].second,test1[i].second); } } { Param param; TransformationModel::getDefaultParameters(param); param.setValue("x_weight", "x"); param.setValue("y_weight", "ln(y)"); TransformationModel dw(data, param); test1.clear(); point.first = 0.0; point.second = std::exp(1.0); test1.push_back(point); point.first = 1.0; point.second = std::exp(2.0); test1.push_back(point); point.first = 2.0; point.second = std::exp(4.0); test1.push_back(point); data1.clear(); point.first = 0.0; point.second = 1.0; data1.push_back(point); point.first = 1.0; point.second = 2.0; data1.push_back(point); point.first = 2.0; point.second = 4.0; data1.push_back(point); dw.unWeightData(data1); for (size_t i = 0; i < data1.size(); ++i) { TEST_REAL_SIMILAR(data1[i].first,test1[i].first); TEST_REAL_SIMILAR(data1[i].second,test1[i].second); } } } END_SECTION START_SECTION(([EXTRA] DataPoint::DataPoint(double, double, const String&))) { NOT_TESTABLE // tested below } END_SECTION START_SECTION(([EXTRA] DataPoint::DataPoint(const pair<double, double>&))) { NOT_TESTABLE // tested below } END_SECTION START_SECTION(([EXTRA] bool DataPoint::operator<(const DataPoint& other) const)) { TransformationModel::DataPoint p1(1.0, 2.0, "abc"); TransformationModel::DataPoint p2(make_pair(1.0, 2.0)); TEST_EQUAL(p1 < p2, false); TEST_EQUAL(p2 < p1, true); p2.note = "def"; TEST_EQUAL(p1 < p2, true); TEST_EQUAL(p2 < p1, false); p1.first = 1.5; TEST_EQUAL(p1 < p2, false); TEST_EQUAL(p2 < p1, true); } END_SECTION START_SECTION(([EXTRA] bool DataPoint::operator==(const DataPoint& other) const)) { TransformationModel::DataPoint p1(1.0, 2.0, "abc"); TransformationModel::DataPoint p2(make_pair(1.0, 2.0)); TEST_EQUAL(p1 == p2, false); p2.note = "abc"; TEST_TRUE(p1 == p2); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ScanWindow_test.cpp
.cpp
2,878
107
// 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/ScanWindow.h> /////////////////////////// using namespace OpenMS; using namespace std; // static_assert(OpenMS::Test::fulfills_rule_of_5<ScanWindow>(), "Must fulfill rule of 5"); // static_assert(OpenMS::Test::fulfills_rule_of_6<ScanWindow>(), "Must fulfill rule of 6"); // static_assert(OpenMS::Test::fulfills_fast_vector<ScanWindow>(), "Must have fast vector semantics"); // static_assert(std::is_nothrow_move_constructible<ScanWindow>::value, "Must have nothrow move constructible"); START_TEST(ScanWindow, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ScanWindow* ptr = nullptr; ScanWindow* nullPointer = nullptr; START_SECTION((ScanWindow())) ptr = new ScanWindow(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~ScanWindow())) delete ptr; END_SECTION START_SECTION((ScanWindow(const ScanWindow& source))) ScanWindow tmp; tmp.begin = 1.0; tmp.end = 2.0; tmp.setMetaValue("label",String("label")); ScanWindow tmp2(tmp); TEST_REAL_SIMILAR(tmp2.begin, 1.0) TEST_REAL_SIMILAR(tmp2.end, 2.0) TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); END_SECTION START_SECTION((ScanWindow& operator= (const ScanWindow& source))) ScanWindow tmp; tmp.begin = 1.0; tmp.end = 2.0; tmp.setMetaValue("label",String("label")); ScanWindow tmp2; tmp2 = tmp; TEST_REAL_SIMILAR(tmp2.begin, 1.0) TEST_REAL_SIMILAR(tmp2.end, 2.0) TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); END_SECTION START_SECTION((bool operator==(const ScanWindow &source) const )) ScanWindow edit, empty; TEST_EQUAL(edit==empty,true); edit.begin = 1.0; TEST_EQUAL(edit==empty,false); edit = empty; edit.end = 1.0; TEST_EQUAL(edit==empty,false); edit = empty; edit.setMetaValue("label",String("label")); TEST_EQUAL(edit==empty,false); END_SECTION START_SECTION((bool operator!=(const ScanWindow &source) const )) ScanWindow edit, empty; TEST_EQUAL(edit!=empty,false); edit.begin = 1.0; TEST_EQUAL(edit!=empty,true); edit = empty; edit.end = 1.0; TEST_EQUAL(edit!=empty,true); edit = empty; edit.setMetaValue("label",String("label")); TEST_EQUAL(edit!=empty,true); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ReactionMonitoringTransition_test.cpp
.cpp
13,102
465
// 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/ANALYSIS/MRM/ReactionMonitoringTransition.h> /////////////////////////// #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; START_TEST(ReactionMonitoringTransition, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ReactionMonitoringTransition* ptr = nullptr; ReactionMonitoringTransition* nullPointer = nullptr; START_SECTION(ReactionMonitoringTransition()) { ptr = new ReactionMonitoringTransition(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~ReactionMonitoringTransition()) { delete ptr; } END_SECTION OpenMS::ReactionMonitoringTransition transition = ReactionMonitoringTransition(); CVTerm charge_cv; String charge_cv_acc = "MS:1000041"; charge_cv.setCVIdentifierRef("MS"); charge_cv.setAccession(charge_cv_acc); charge_cv.setName("charge state"); charge_cv.setValue(3); ///////////////////////////////////////////////////////////// // Copy constructor, move constructor, assignment operator, move assignment operator, equality START_SECTION((ReactionMonitoringTransition(const ReactionMonitoringTransition &rhs))) { ReactionMonitoringTransition tr1, tr2, tr3; tr1.addPrecursorCVTerm(charge_cv); tr1.setPrecursorMZ(42.0); tr2 = ReactionMonitoringTransition(tr1); TEST_TRUE(tr1 == tr2) ReactionMonitoringTransition::Prediction p; p.contact_ref = "dummy"; tr1.setPrediction(p); tr1.setIdentifyingTransition(false); tr1.setDetectingTransition(false); tr1.setQuantifyingTransition(false); tr3 = ReactionMonitoringTransition(tr1); TEST_TRUE(tr1 == tr3) TEST_EQUAL(tr1 == tr2, false) } END_SECTION START_SECTION((ReactionMonitoringTransition(ReactionMonitoringTransition &&rhs))) { // Ensure that ReactionMonitoringTransition has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(ReactionMonitoringTransition(std::declval<ReactionMonitoringTransition&&>())), true) ReactionMonitoringTransition tr1, tr2, tr3; ReactionMonitoringTransition::Prediction pred; pred.contact_ref = "dummy"; tr1.setPrediction(pred); tr1.addPrecursorCVTerm(charge_cv); tr1.setPrecursorMZ(42.0); tr1.setCompoundRef("test_ref"); auto orig = tr1; tr2 = ReactionMonitoringTransition(std::move(tr1)); TEST_TRUE(orig == tr2); TEST_EQUAL(tr2.hasPrecursorCVTerms(), true); TEST_EQUAL(tr2.hasPrediction(), true); TEST_EQUAL(tr2.getPrediction().contact_ref, "dummy"); TEST_EQUAL(tr2.getPrecursorCVTermList().hasCVTerm(charge_cv_acc), true) TEST_EQUAL(tr2.getCompoundRef(), "test_ref") TEST_EQUAL(tr1.hasPrecursorCVTerms(), false); // its gone TEST_EQUAL(tr1.hasPrediction(), false); // its gone TEST_EQUAL(tr1.getCompoundRef(), "") // its gone ReactionMonitoringTransition::Prediction p; p.contact_ref = "dummy"; orig.setPrediction(p); orig.setIdentifyingTransition(false); orig.setDetectingTransition(false); orig.setQuantifyingTransition(false); tr1 = orig; tr3 = ReactionMonitoringTransition(std::move(tr1)); TEST_TRUE(orig == tr3) TEST_EQUAL(orig == tr2, false) } END_SECTION START_SECTION((ReactionMonitoringTransition& operator=(const ReactionMonitoringTransition &rhs))) { ReactionMonitoringTransition tr1, tr2, tr3; tr1.addPrecursorCVTerm(charge_cv); tr1.setPrecursorMZ(42.0); tr2 = tr1; TEST_TRUE(tr1 == tr2) ReactionMonitoringTransition::Prediction p; p.contact_ref = "dummy"; tr1.setPrediction(p); tr3 = tr1; TEST_TRUE(tr1 == tr3) TEST_EQUAL(tr1 == tr2, false) tr1.setDetectingTransition(false); TEST_EQUAL(tr1 == tr3, false) tr1.setIdentifyingTransition(true); tr1.setQuantifyingTransition(false); TEST_EQUAL(tr1 == tr3, false) tr3 = tr1; TEST_TRUE(tr1 == tr3) } END_SECTION START_SECTION((void setName(const String &name))) { OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setName("test_tr"); TEST_EQUAL(tr.getName(), "test_tr") } END_SECTION START_SECTION((const String& getName() const )) { TEST_EQUAL(transition.getName(), "") } END_SECTION START_SECTION((void setPeptideRef(const String &peptide_ref))) { OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setPeptideRef("test_ref"); TEST_EQUAL(tr.getPeptideRef(), "test_ref") } END_SECTION START_SECTION((const String& getPeptideRef() const )) { TEST_EQUAL(transition.getPeptideRef(), "") } END_SECTION START_SECTION((void setCompoundRef(const String &compound_ref))) { OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setCompoundRef("test_ref"); TEST_EQUAL(tr.getCompoundRef(), "test_ref") } END_SECTION START_SECTION((const String& getCompoundRef() const )) { TEST_EQUAL(transition.getCompoundRef(), "") } END_SECTION START_SECTION((void setPrecursorMZ(double mz))) { OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setPrecursorMZ(42.0); TEST_REAL_SIMILAR(tr.getPrecursorMZ(), 42.0) } END_SECTION START_SECTION((double getPrecursorMZ() const )) { TEST_REAL_SIMILAR(transition.getPrecursorMZ(), 0.0) } END_SECTION START_SECTION((void setPrecursorCVTermList(const CVTermList &list))) { CVTermList list; list.addCVTerm(charge_cv); OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setPrecursorCVTermList(list); TEST_EQUAL(tr.getPrecursorCVTermList().hasCVTerm(charge_cv_acc ), true) } END_SECTION START_SECTION((bool hasPrecursorCVTerms() const)) { CVTermList list; list.addCVTerm(charge_cv); OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); TEST_EQUAL(tr.hasPrecursorCVTerms(), false) tr.setPrecursorCVTermList(list); TEST_EQUAL(tr.hasPrecursorCVTerms(), true) } END_SECTION START_SECTION((void addPrecursorCVTerm(const CVTerm &cv_term))) { OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); TEST_EQUAL(tr.hasPrecursorCVTerms(), false) tr.addPrecursorCVTerm(charge_cv); TEST_EQUAL(tr.hasPrecursorCVTerms(), true) TEST_EQUAL(tr.getPrecursorCVTermList().hasCVTerm(charge_cv_acc ), true) } END_SECTION START_SECTION((const CVTermList& getPrecursorCVTermList() const )) { CVTermList list; list.addCVTerm(charge_cv); OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setPrecursorCVTermList(list); TEST_EQUAL(tr.getPrecursorCVTermList() == list, true) } END_SECTION START_SECTION((void setProductMZ(double mz))) { OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setProductMZ(42.0); TEST_REAL_SIMILAR(tr.getProductMZ(), 42.0) } END_SECTION START_SECTION((double getProductMZ() const )) { TEST_REAL_SIMILAR(transition.getProductMZ(), 0.0) } END_SECTION START_SECTION((void setProduct(Product product))) { auto product = OpenMS::ReactionMonitoringTransition::Product(); OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setProduct(product); TEST_EQUAL(tr.getProduct() == product, true) } END_SECTION START_SECTION((const Product & getProduct() const)) { TEST_EQUAL(transition.getProduct() == OpenMS::ReactionMonitoringTransition::Product(), true) } END_SECTION START_SECTION((void addProductCVTerm(const CVTerm &cv_term))) { // TODO } END_SECTION START_SECTION((ReactionMonitoringTransition::isDetectingTransition() const)) { TEST_EQUAL(transition.isDetectingTransition(), true) } END_SECTION START_SECTION((ReactionMonitoringTransition::setDetectingTransition(bool val))) { OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setDetectingTransition(false); TEST_EQUAL(tr.isDetectingTransition(), false) tr.setDetectingTransition(true); TEST_EQUAL(tr.isDetectingTransition(), true) } END_SECTION START_SECTION((ReactionMonitoringTransition::isIdentifyingTransition() const)) { TEST_EQUAL(transition.isIdentifyingTransition(), false) } END_SECTION START_SECTION((ReactionMonitoringTransition::setIdentifyingTransition(bool val))) { OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setIdentifyingTransition(true); TEST_EQUAL(tr.isIdentifyingTransition(), true) tr.setIdentifyingTransition(false); TEST_EQUAL(tr.isIdentifyingTransition(), false) } END_SECTION START_SECTION((ReactionMonitoringTransition::isQuantifyingTransition() const)) { TEST_EQUAL(transition.isQuantifyingTransition(), true) } END_SECTION START_SECTION((ReactionMonitoringTransition::setQuantifyingTransition(bool val))) { OpenMS::ReactionMonitoringTransition tr = ReactionMonitoringTransition(); tr.setQuantifyingTransition(false); TEST_EQUAL(tr.isQuantifyingTransition(), false) tr.setQuantifyingTransition(true); TEST_EQUAL(tr.isQuantifyingTransition(), true) } END_SECTION START_SECTION((bool operator==(const ReactionMonitoringTransition &rhs) const )) { ReactionMonitoringTransition tr1, tr2; TEST_TRUE(tr1 == tr2) tr1.addPrecursorCVTerm(charge_cv); TEST_EQUAL(tr1 == tr2, false) tr2.addPrecursorCVTerm(charge_cv); TEST_TRUE(tr1 == tr2) tr1.setDetectingTransition(false); TEST_EQUAL(tr1 == tr2, false) tr2.setDetectingTransition(false); TEST_TRUE(tr1 == tr2) } END_SECTION START_SECTION((bool operator!=(const ReactionMonitoringTransition &rhs) const )) { ReactionMonitoringTransition tr1, tr2; TEST_EQUAL(tr1 != tr2, false) tr1.addPrecursorCVTerm(charge_cv); TEST_FALSE(tr1 == tr2) } END_SECTION ///////////////////////////////////////////////////////////// // Hash function tests ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] std::hash<ReactionMonitoringTransition>)) { // Test that equal objects have equal hashes ReactionMonitoringTransition tr1, tr2; std::hash<ReactionMonitoringTransition> hasher; // Default constructed objects should have equal hashes TEST_EQUAL(hasher(tr1), hasher(tr2)) // Modify both identically and verify hashes still match tr1.setName("test_transition"); tr2.setName("test_transition"); TEST_EQUAL(hasher(tr1), hasher(tr2)) tr1.setPeptideRef("peptide_ref_1"); tr2.setPeptideRef("peptide_ref_1"); TEST_EQUAL(hasher(tr1), hasher(tr2)) tr1.setPrecursorMZ(500.0); tr2.setPrecursorMZ(500.0); TEST_EQUAL(hasher(tr1), hasher(tr2)) tr1.setProductMZ(250.0); tr2.setProductMZ(250.0); TEST_EQUAL(hasher(tr1), hasher(tr2)) // Test with CV terms CVTerm cv_term; cv_term.setCVIdentifierRef("MS"); cv_term.setAccession("MS:1000041"); cv_term.setName("charge state"); cv_term.setValue(2); tr1.addPrecursorCVTerm(cv_term); tr2.addPrecursorCVTerm(cv_term); TEST_EQUAL(hasher(tr1), hasher(tr2)) // Test with prediction ReactionMonitoringTransition::Prediction pred; pred.contact_ref = "contact_1"; pred.software_ref = "software_1"; tr1.setPrediction(pred); tr2.setPrediction(pred); TEST_EQUAL(hasher(tr1), hasher(tr2)) // Test with transition flags tr1.setDetectingTransition(false); tr2.setDetectingTransition(false); TEST_EQUAL(hasher(tr1), hasher(tr2)) tr1.setIdentifyingTransition(true); tr2.setIdentifyingTransition(true); TEST_EQUAL(hasher(tr1), hasher(tr2)) // Test that different objects have different hashes (not guaranteed but expected) ReactionMonitoringTransition tr3; tr3.setName("different_name"); TEST_NOT_EQUAL(hasher(tr1), hasher(tr3)) ReactionMonitoringTransition tr4; tr4.setPrecursorMZ(999.0); TEST_NOT_EQUAL(hasher(tr1), hasher(tr4)) // Test use in unordered_set std::unordered_set<ReactionMonitoringTransition> transition_set; transition_set.insert(tr1); transition_set.insert(tr2); // Should not insert (equal to tr1) transition_set.insert(tr3); transition_set.insert(tr4); TEST_EQUAL(transition_set.size(), 3) // tr1 and tr2 are equal, so only 3 unique // Test use in unordered_map std::unordered_map<ReactionMonitoringTransition, int> transition_map; transition_map[tr1] = 1; transition_map[tr2] = 2; // Should overwrite value for tr1 transition_map[tr3] = 3; TEST_EQUAL(transition_map.size(), 2) TEST_EQUAL(transition_map[tr1], 2) // Value should be 2 (overwritten) TEST_EQUAL(transition_map[tr3], 3) // Test lookup TEST_EQUAL(transition_set.count(tr1), 1) TEST_EQUAL(transition_set.count(tr2), 1) // Equal to tr1 TEST_EQUAL(transition_set.count(tr3), 1) ReactionMonitoringTransition tr5; tr5.setName("not_in_set"); TEST_EQUAL(transition_set.count(tr5), 0) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CVMappings_test.cpp
.cpp
5,206
210
// 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/DATASTRUCTURES/CVMappings.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/CVMappingRule.h> #include <OpenMS/DATASTRUCTURES/CVReference.h> using namespace OpenMS; using namespace std; START_TEST(CVMappings, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CVMappings* ptr = nullptr; CVMappings* nullPointer = nullptr; START_SECTION(CVMappings()) { ptr = new CVMappings(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~CVMappings()) { delete ptr; } END_SECTION ptr = new CVMappings(); START_SECTION((CVMappings(const CVMappings &rhs))) { CVMappings cvm; CVMappingRule r1, r2; vector<CVMappingRule> rules; rules.push_back(r1); rules.push_back(r2); cvm.setMappingRules(rules); TEST_EQUAL(CVMappings(cvm).getMappingRules() == rules, true) CVReference ref1, ref2; ref1.setIdentifier("Ref1"); ref2.setIdentifier("Ref2"); vector<CVReference> refs; refs.push_back(ref1); refs.push_back(ref2); cvm.setCVReferences(refs); TEST_EQUAL(CVMappings(cvm).getCVReferences() == refs, true) } END_SECTION START_SECTION((CVMappings& operator=(const CVMappings &rhs))) { CVMappings cvm, cvm_copy; CVMappingRule r1, r2; vector<CVMappingRule> rules; rules.push_back(r1); rules.push_back(r2); cvm.setMappingRules(rules); cvm_copy = cvm; TEST_EQUAL(cvm_copy.getMappingRules() == rules, true) CVReference ref1, ref2; ref1.setIdentifier("Ref1"); ref2.setIdentifier("Ref2"); vector<CVReference> refs; refs.push_back(ref1); refs.push_back(ref2); cvm.setCVReferences(refs); cvm_copy = cvm; TEST_EQUAL(cvm_copy.getCVReferences() == refs, true) } END_SECTION START_SECTION((bool operator == (const CVMappings& rhs) const)) { CVMappings cvm, cvm_copy; CVMappingRule r1, r2; vector<CVMappingRule> rules; rules.push_back(r1); rules.push_back(r2); cvm.setMappingRules(rules); TEST_EQUAL(cvm == cvm_copy, false) cvm_copy = cvm; TEST_TRUE(cvm == cvm_copy) CVReference ref1, ref2; ref1.setIdentifier("Ref1"); ref2.setIdentifier("Ref2"); vector<CVReference> refs; refs.push_back(ref1); refs.push_back(ref2); cvm.setCVReferences(refs); TEST_EQUAL(cvm == cvm_copy, false) cvm_copy = cvm; TEST_TRUE(cvm == cvm_copy) } END_SECTION START_SECTION((bool operator != (const CVMappings& rhs) const)) { CVMappings cvm, cvm_copy; CVMappingRule r1, r2; vector<CVMappingRule> rules; rules.push_back(r1); rules.push_back(r2); cvm.setMappingRules(rules); TEST_FALSE(cvm == cvm_copy) cvm_copy = cvm; TEST_EQUAL(cvm != cvm_copy, false) CVReference ref1, ref2; ref1.setIdentifier("Ref1"); ref2.setIdentifier("Ref2"); vector<CVReference> refs; refs.push_back(ref1); refs.push_back(ref2); cvm.setCVReferences(refs); TEST_FALSE(cvm == cvm_copy) cvm_copy = cvm; TEST_EQUAL(cvm != cvm_copy, false) } END_SECTION START_SECTION((void setMappingRules(const std::vector< CVMappingRule > &cv_mapping_rules))) { CVMappingRule r1, r2; vector<CVMappingRule> rules; rules.push_back(r1); rules.push_back(r2); TEST_EQUAL(ptr->getMappingRules().size(), 0) ptr->setMappingRules(rules); TEST_EQUAL(ptr->getMappingRules() == rules, true) } END_SECTION START_SECTION((const std::vector<CVMappingRule>& getMappingRules() const )) { NOT_TESTABLE } END_SECTION START_SECTION((void addMappingRule(const CVMappingRule &cv_mapping_rule))) { CVMappingRule r1; TEST_EQUAL(ptr->getMappingRules().size(), 2) ptr->addMappingRule(r1); TEST_EQUAL(ptr->getMappingRules().size(), 3) } END_SECTION START_SECTION((void setCVReferences(const std::vector< CVReference > &cv_references))) { CVReference r1, r2; r1.setIdentifier("Ref1"); r2.setIdentifier("Ref2"); vector<CVReference> refs; refs.push_back(r1); refs.push_back(r2); TEST_EQUAL(ptr->getCVReferences().size(), 0) ptr->setCVReferences(refs); TEST_EQUAL(ptr->getCVReferences() == refs, true) } END_SECTION START_SECTION((const std::vector<CVReference>& getCVReferences() const)) NOT_TESTABLE END_SECTION START_SECTION((void addCVReference(const CVReference &cv_reference))) { CVReference r1; r1.setIdentifier("Ref2,5"); TEST_EQUAL(ptr->getCVReferences().size(), 2) ptr->addCVReference(r1); TEST_EQUAL(ptr->getCVReferences().size(), 3) } END_SECTION START_SECTION((bool hasCVReference(const String &identifier))) { TEST_EQUAL(ptr->hasCVReference("Ref1"), true) TEST_EQUAL(ptr->hasCVReference("Ref2"), true) TEST_EQUAL(ptr->hasCVReference("Ref2,5"), true) TEST_EQUAL(ptr->hasCVReference("Ref3"), false) } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ParamXMLFile_test.cpp
.cpp
18,185
453
// 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 <OpenMS/FORMAT/ParamXMLFile.h> #include <OpenMS/DATASTRUCTURES/Param.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/FORMAT/TextFile.h> /////////////////////////// #include <fstream> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshadow" #endif using namespace OpenMS; using namespace std; START_TEST(ParamXMLFile, "$Id") ParamXMLFile* ptr = nullptr; ParamXMLFile* nullPtr = nullptr; START_SECTION((ParamXMLFile())) { ptr = new ParamXMLFile(); TEST_NOT_EQUAL(ptr, nullPtr) delete ptr; } END_SECTION START_SECTION((void load(const String& filename, Param& param))) Param p2; ParamXMLFile paramFile; TEST_EXCEPTION(Exception::FileNotFound, paramFile.load("FileDoesNotExist.xml",p2)) END_SECTION Param p; p.setValue("test:float",17.4f,"floatdesc"); p.setValue("test:string","test,test,test","stringdesc"); p.setValue("test:int",17,"intdesc"); p.setValue("test2:float",17.5f); p.setValue("test2:string","test2"); p.setValue("test2:int",18); p.setSectionDescription("test","sectiondesc"); p.addTags("test:float", {"a","b","c"}); START_SECTION((void store(const String& filename, const Param& param) const)) ParamXMLFile paramFile; Param p2(p); p2.setValue("test:a:a1", 47.1,"a1desc\"<>\nnewline"); p2.setValue("test:b:b1", 47.1); p2.setSectionDescription("test:b","bdesc\"<>\nnewline"); p2.setValue("test2:a:a1", 47.1); p2.setValue("test2:b:b1", 47.1,"",{"advanced"}); p2.setSectionDescription("test2:a","adesc"); //exception Param p300; TEST_EXCEPTION(Exception::UnableToCreateFile, paramFile.store("/does/not/exist/FileDoesNotExist.xml",p300)) String filename; NEW_TMP_FILE(filename); paramFile.store(filename,p2); Param p3; paramFile.load(filename,p3); TEST_REAL_SIMILAR(float(p2.getValue("test:float")), float(p3.getValue("test:float"))) TEST_EQUAL(p2.getValue("test:string"), p3.getValue("test:string")) TEST_EQUAL(p2.getValue("test:int"), p3.getValue("test:int")) TEST_REAL_SIMILAR(float(p2.getValue("test2:float")), float(p3.getValue("test2:float"))) TEST_EQUAL(p2.getValue("test2:string"), p3.getValue("test2:string")) TEST_EQUAL(p2.getValue("test2:int"), p3.getValue("test2:int")) TEST_STRING_EQUAL(p2.getDescription("test:float"), p3.getDescription("test:float")) TEST_STRING_EQUAL(p2.getDescription("test:string"), p3.getDescription("test:string")) TEST_STRING_EQUAL(p2.getDescription("test:int"), p3.getDescription("test:int")) TEST_EQUAL(p3.getSectionDescription("test"),"sectiondesc") TEST_EQUAL(p3.getDescription("test:a:a1"),"a1desc\"<>\nnewline") TEST_EQUAL(p3.getSectionDescription("test:b"),"bdesc\"<>\nnewline") TEST_EQUAL(p3.getSectionDescription("test2:a"),"adesc") TEST_EQUAL(p3.hasTag("test2:b:b1","advanced"),true) TEST_EQUAL(p3.hasTag("test2:a:a1","advanced"),false) TEST_EQUAL(ParamXMLFile().isValid(filename, std::cerr),true) // advanced NEW_TMP_FILE(filename); Param p7; p7.setValue("true",5,"",{"advanced"}); p7.setValue("false",5,""); paramFile.store(filename,p7); TEST_EQUAL(ParamXMLFile().isValid(filename, std::cerr),true) Param p8; paramFile.load(filename,p8); TEST_EQUAL(p8.getEntry("true").tags.count("advanced")==1, true) TEST_EQUAL(p8.getEntry("false").tags.count("advanced")==1, false) //restrictions NEW_TMP_FILE(filename); Param p5; p5.setValue("int",5); p5.setValue("int_min",5); p5.setMinInt("int_min",4); p5.setValue("int_max",5); p5.setMaxInt("int_max",6); p5.setValue("int_min_max",5); p5.setMinInt("int_min_max",0); p5.setMaxInt("int_min_max",10); p5.setValue("float",5.1); p5.setValue("float_min",5.1); p5.setMinFloat("float_min",4.1); p5.setValue("float_max",5.1); p5.setMaxFloat("float_max",6.1); p5.setValue("float_min_max",5.1); p5.setMinFloat("float_min_max",0.1); p5.setMaxFloat("float_min_max",10.1); vector<std::string> strings; p5.setValue("string","bli"); strings.push_back("bla"); strings.push_back("bluff"); p5.setValue("string_2","bla"); p5.setValidStrings("string_2",strings); //list restrictions vector<std::string> strings2 = {"xml", "txt"}; p5.setValue("stringlist2",std::vector<std::string>{"a.txt","b.xml","c.pdf"}); p5.setValue("stringlist",std::vector<std::string>{"aa.C","bb.h","c.doxygen"}); p5.setValidStrings("stringlist2",strings2); p5.setValue("intlist",ListUtils::create<Int>("2,5,10")); p5.setValue("intlist2",ListUtils::create<Int>("2,5,10")); p5.setValue("intlist3",ListUtils::create<Int>("2,5,10")); p5.setValue("intlist4",ListUtils::create<Int>("2,5,10")); p5.setMinInt("intlist2",1); p5.setMaxInt("intlist3",11); p5.setMinInt("intlist4",0); p5.setMaxInt("intlist4",15); p5.setValue("doublelist",ListUtils::create<double>("1.2,3.33,4.44")); p5.setValue("doublelist2",ListUtils::create<double>("1.2,3.33,4.44")); p5.setValue("doublelist3",ListUtils::create<double>("1.2,3.33,4.44")); p5.setValue("doublelist4",ListUtils::create<double>("1.2,3.33,4.44")); p5.setMinFloat("doublelist2",1.1); p5.setMaxFloat("doublelist3",4.45); p5.setMinFloat("doublelist4",0.1); p5.setMaxFloat("doublelist4",5.8); paramFile.store(filename,p5); TEST_EQUAL(paramFile.isValid(filename, std::cerr),true) Param p6; paramFile.load(filename,p6); TEST_EQUAL(p6.getEntry("int").min_int, -numeric_limits<Int>::max()) TEST_EQUAL(p6.getEntry("int").max_int, numeric_limits<Int>::max()) TEST_EQUAL(p6.getEntry("int_min").min_int, 4) TEST_EQUAL(p6.getEntry("int_min").max_int, numeric_limits<Int>::max()) TEST_EQUAL(p6.getEntry("int_max").min_int, -numeric_limits<Int>::max()) TEST_EQUAL(p6.getEntry("int_max").max_int, 6) TEST_EQUAL(p6.getEntry("int_min_max").min_int, 0) TEST_EQUAL(p6.getEntry("int_min_max").max_int, 10) TEST_REAL_SIMILAR(p6.getEntry("float").min_float, -numeric_limits<double>::max()) TEST_REAL_SIMILAR(p6.getEntry("float").max_float, numeric_limits<double>::max()) TEST_REAL_SIMILAR(p6.getEntry("float_min").min_float, 4.1) TEST_REAL_SIMILAR(p6.getEntry("float_min").max_float, numeric_limits<double>::max()) TEST_REAL_SIMILAR(p6.getEntry("float_max").min_float, -numeric_limits<double>::max()) TEST_REAL_SIMILAR(p6.getEntry("float_max").max_float, 6.1) TEST_REAL_SIMILAR(p6.getEntry("float_min_max").min_float, 0.1) TEST_REAL_SIMILAR(p6.getEntry("float_min_max").max_float, 10.1) TEST_EQUAL(p6.getEntry("string").valid_strings.size(), 0) TEST_EQUAL(p6.getEntry("string_2").valid_strings.size(), 2) TEST_EQUAL(p6.getEntry("string_2").valid_strings[0], "bla") TEST_EQUAL(p6.getEntry("string_2").valid_strings[1], "bluff") TEST_EQUAL(p6.getEntry("stringlist").valid_strings.size(), 0) TEST_EQUAL(p6.getEntry("stringlist2").valid_strings.size(), 2) TEST_EQUAL(p6.getEntry("stringlist2").valid_strings[0], "xml") TEST_EQUAL(p6.getEntry("stringlist2").valid_strings[1], "txt") TEST_EQUAL(p6.getEntry("intlist").min_int, -numeric_limits<Int>::max()) TEST_EQUAL(p6.getEntry("intlist").max_int, numeric_limits<Int>::max()) TEST_EQUAL(p6.getEntry("intlist2").min_int, 1) TEST_EQUAL(p6.getEntry("intlist2").max_int, numeric_limits<Int>::max()) TEST_EQUAL(p6.getEntry("intlist3").min_int, -numeric_limits<Int>::max()) TEST_EQUAL(p6.getEntry("intlist3").max_int, 11) TEST_EQUAL(p6.getEntry("intlist4").min_int, 0) TEST_EQUAL(p6.getEntry("intlist4").max_int, 15) TEST_REAL_SIMILAR(p6.getEntry("doublelist").min_float, -numeric_limits<double>::max()) TEST_REAL_SIMILAR(p6.getEntry("doublelist").max_float, numeric_limits<double>::max()) TEST_REAL_SIMILAR(p6.getEntry("doublelist2").min_float, 1.1) TEST_REAL_SIMILAR(p6.getEntry("doublelist2").max_float, numeric_limits<double>::max()) TEST_REAL_SIMILAR(p6.getEntry("doublelist3").min_float, -numeric_limits<double>::max()) TEST_REAL_SIMILAR(p6.getEntry("doublelist3").max_float, 4.45) TEST_REAL_SIMILAR(p6.getEntry("doublelist4").min_float, 0.1) TEST_REAL_SIMILAR(p6.getEntry("doublelist4").max_float, 5.8) // NaN for float/double Param p_nan; p_nan.setValue("float_nan", std::numeric_limits<float>::quiet_NaN()); p_nan.setValue("double_nan", std::numeric_limits<double>::quiet_NaN()); NEW_TMP_FILE(filename); paramFile.store(filename, p_nan); Param p_nan2; paramFile.load(filename, p_nan2); TEST_TRUE(std::isnan((double)p_nan2.getValue("float_nan"))) TEST_TRUE(std::isnan((double)p_nan2.getValue("double_nan"))) // ... test the actual values written to INI (should be 'NaN', not 'nan', for compatibility with downstream tools, like Java's double) TextFile tf; tf.load(filename); TEST_TRUE((tf.begin() + 2)->hasSubstring("value=\"NaN\"")) TEST_TRUE((tf.begin() + 3)->hasSubstring("value=\"NaN\"")) //Test if an empty Param written to a file validates against the schema NEW_TMP_FILE(filename); Param p4; paramFile.store(filename,p4); TEST_EQUAL(paramFile.isValid(filename, std::cerr),true) END_SECTION START_SECTION((void writeXMLToStream(std::ostream *os_ptr, const Param &param) const )) { Param p; p.setValue("stringlist", std::vector<std::string>{"a","bb","ccc"}, "StringList Description"); p.setValue("intlist", ListUtils::create<Int>("1,22,333")); p.setValue("item", String("bla")); p.setValue("stringlist2", std::vector<std::string>()); p.setValue("intlist2", ListUtils::create<Int>("")); p.setValue("item1", 7); p.setValue("intlist3", ListUtils::create<Int>("1")); p.setValue("stringlist3", std::vector<std::string>{"1"}); p.setValue("item3", 7.6); p.setValue("doublelist", ListUtils::create<double>("1.22,2.33,4.55")); p.setValue("doublelist3", ListUtils::create<double>("1.4")); p.setValue("file_parameter", "", "This is a file parameter."); p.addTag("file_parameter", "input file"); p.setValidStrings("file_parameter", std::vector<std::string>{"*.mzML","*.mzXML"}); p.setValue("advanced_parameter", "", "This is an advanced parameter.", {"advanced"}); p.setValue("flag", "false", "This is a flag i.e. in a command line input it does not need a value."); p.setValidStrings("flag",{"true","false"}); p.setValue("noflagJustTrueFalse", "true", "This is not a flag but has a boolean meaning."); p.setValidStrings("noflagJustTrueFalse", {"true","false"}); String filename; NEW_TMP_FILE(filename) std::ofstream s(filename.c_str(), std::ios::out); ParamXMLFile paramFile; paramFile.writeXMLToStream(&s,p); TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("ParamXMLFile_test_writeXMLToStream.xml")) } END_SECTION START_SECTION([EXTRA] loading and storing of lists) ParamXMLFile paramFile; Param p; p.setValue("stringlist", std::vector<std::string>{"a","bb","ccc"}); p.setValue("intlist", ListUtils::create<Int>("1,22,333")); p.setValue("item", String("bla")); p.setValue("stringlist2", std::vector<std::string>()); p.setValue("intlist2", ListUtils::create<Int>("")); p.setValue("item1", 7); p.setValue("intlist3", ListUtils::create<Int>("1")); p.setValue("stringlist3", std::vector<std::string>{"1"}); p.setValue("item3", 7.6); p.setValue("doublelist", ListUtils::create<double>("1.22,2.33,4.55")); p.setValue("doublelist2", ListUtils::create<double>("")); p.setValue("doublelist3", ListUtils::create<double>("1.4")); //store String filename; NEW_TMP_FILE(filename); paramFile.store(filename,p); //load Param p2; paramFile.load(filename,p2); TEST_EQUAL(p2.size(),12); TEST_EQUAL(p2.getValue("stringlist").valueType(), ParamValue::STRING_LIST) std::vector<std::string> list = p2.getValue("stringlist"); TEST_EQUAL(list.size(),3) TEST_EQUAL(list[0],"a") TEST_EQUAL(list[1],"bb") TEST_EQUAL(list[2],"ccc") TEST_EQUAL(p2.getValue("stringlist2").valueType(), ParamValue::STRING_LIST) list = p2.getValue("stringlist2"); TEST_EQUAL(list.size(),0) TEST_EQUAL(p2.getValue("stringlist").valueType(), ParamValue::STRING_LIST) list = p2.getValue("stringlist3"); TEST_EQUAL(list.size(),1) TEST_EQUAL(list[0],"1") TEST_EQUAL(p2.getValue("intlist").valueType(), ParamValue::INT_LIST) IntList intlist = p2.getValue("intlist"); TEST_EQUAL(intlist.size(),3); TEST_EQUAL(intlist[0], 1) TEST_EQUAL(intlist[1], 22) TEST_EQUAL(intlist[2], 333) TEST_EQUAL(p2.getValue("intlist2").valueType(),ParamValue::INT_LIST) intlist = p2.getValue("intlist2"); TEST_EQUAL(intlist.size(),0) TEST_EQUAL(p2.getValue("intlist3").valueType(),ParamValue::INT_LIST) intlist = p2.getValue("intlist3"); TEST_EQUAL(intlist.size(),1) TEST_EQUAL(intlist[0],1) TEST_EQUAL(p2.getValue("doublelist").valueType(), ParamValue::DOUBLE_LIST) DoubleList doublelist = p2.getValue("doublelist"); TEST_EQUAL(doublelist.size(),3); TEST_EQUAL(doublelist[0], 1.22) TEST_EQUAL(doublelist[1], 2.33) TEST_EQUAL(doublelist[2], 4.55) TEST_EQUAL(p2.getValue("doublelist2").valueType(),ParamValue::DOUBLE_LIST) doublelist = p2.getValue("doublelist2"); TEST_EQUAL(doublelist.size(),0) TEST_EQUAL(p2.getValue("doublelist3").valueType(),ParamValue::DOUBLE_LIST) doublelist = p2.getValue("doublelist3"); TEST_EQUAL(doublelist.size(),1) TEST_EQUAL(doublelist[0],1.4) END_SECTION START_SECTION(([EXTRA] Escaping of characters)) Param p; ParamXMLFile paramFile; p.setValue("string",String("bla"),"string"); p.setValue("string_with_ampersand", String("bla2&blubb"), "string with ampersand"); p.setValue("string_with_ampersand_in_descr", String("blaxx"), "String with & in description"); p.setValue("string_with_single_quote", String("bla'xxx"), "String with single quotes"); p.setValue("string_with_single_quote_in_descr", String("blaxxx"), "String with ' quote in description"); p.setValue("string_with_double_quote", String("bla\"xxx"), "String with double quote"); p.setValue("string_with_double_quote_in_descr", String("bla\"xxx"), "String with \" description"); p.setValue("string_with_greater_sign", String("bla>xxx"), "String with greater sign"); p.setValue("string_with_greater_sign_in_descr", String("bla greater xxx"), "String with >"); p.setValue("string_with_less_sign", String("bla<xxx"), "String with less sign"); p.setValue("string_with_less_sign_in_descr", String("bla less sign_xxx"), "String with less sign <"); String filename; NEW_TMP_FILE(filename) paramFile.store(filename,p); Param p2; paramFile.load(filename,p2); TEST_STRING_EQUAL(p2.getDescription("string"), "string") TEST_STRING_EQUAL(p.getValue("string_with_ampersand"), String("bla2&blubb")) TEST_STRING_EQUAL(p.getDescription("string_with_ampersand_in_descr"), "String with & in description") TEST_STRING_EQUAL(p.getValue("string_with_single_quote"), String("bla'xxx")) TEST_STRING_EQUAL(p.getDescription("string_with_single_quote_in_descr"), "String with ' quote in description") TEST_STRING_EQUAL(p.getValue("string_with_double_quote"), String("bla\"xxx")) TEST_STRING_EQUAL(p.getDescription("string_with_double_quote_in_descr"), "String with \" description") TEST_STRING_EQUAL(p.getValue("string_with_greater_sign"), String("bla>xxx")) TEST_STRING_EQUAL(p.getDescription("string_with_greater_sign_in_descr"), "String with >") TEST_STRING_EQUAL(p.getValue("string_with_less_sign"), String("bla<xxx")) TEST_STRING_EQUAL(p.getDescription("string_with_less_sign_in_descr"), "String with less sign <") END_SECTION START_SECTION([EXTRA] loading pre 1.6.2 files and storing them in 1.6.2 format) { Param p; ParamXMLFile paramFile; paramFile.load(OPENMS_GET_TEST_DATA_PATH("Param_pre16_update.ini"), p); // test some of the former tags if they were loaded correctly TEST_EQUAL(p.getValue("SpectraFilterMarkerMower:version"), "1.11.0") TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:in", "input file"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:in", "required"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:in", "advanced"), false) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:out", "output file"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:in", "required"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:in", "advanced"), false) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:log", "advanced"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:log", "required"), false) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:no_progress", "advanced"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:no_progress", "required"), false) // write as 1.6.2 ini and check if the output is as expected String filename; NEW_TMP_FILE(filename) paramFile.store(filename,p); TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("Param_post16_update.ini")) } END_SECTION START_SECTION([EXTRA] loading 1.6.2 files) { Param p; ParamXMLFile paramFile; paramFile.load(OPENMS_GET_TEST_DATA_PATH("Param_post16_update.ini"), p); // test some of the former tags if they were loaded correctly TEST_EQUAL(p.getValue("SpectraFilterMarkerMower:version"), "1.11.0") TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:in", "input file"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:in", "required"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:in", "advanced"), false) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:out", "output file"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:in", "required"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:in", "advanced"), false) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:log", "advanced"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:log", "required"), false) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:no_progress", "advanced"), true) TEST_EQUAL(p.hasTag("SpectraFilterMarkerMower:1:no_progress", "required"), false) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST #ifdef __clang__ #pragma clang diagnostic pop #endif
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GaussFilterAlgorithm_test.cpp
.cpp
5,351
143
// 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/PROCESSING/SMOOTHING/GaussFilterAlgorithm.h> /////////////////////////// START_TEST(GaussFilterAlgorithm<D>, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; GaussFilterAlgorithm* dgauss_ptr = nullptr; GaussFilterAlgorithm* dgauss_nullPointer = nullptr; START_SECTION((GaussFilterAlgorithm())) dgauss_ptr = new GaussFilterAlgorithm; TEST_NOT_EQUAL(dgauss_ptr, dgauss_nullPointer) END_SECTION START_SECTION((virtual ~GaussFilterAlgorithm())) delete dgauss_ptr; END_SECTION START_SECTION((void initialize(double gaussian_width, double spacing, double ppm_tolerance, bool use_ppm_tolerance))) // We cannot really test that the variables are correctly set since we dont // have access to them. dgauss_ptr = new GaussFilterAlgorithm; dgauss_ptr->initialize(0.5, 0.5, 10, false); dgauss_ptr->initialize(0.5, 0.5, 10, true); TEST_NOT_EQUAL(dgauss_ptr, dgauss_nullPointer) delete dgauss_ptr; END_SECTION START_SECTION((template <typename ConstIterT, typename IterT> bool filter(ConstIterT mz_in_start, ConstIterT mz_in_end, ConstIterT int_in_start, IterT mz_out, IterT int_out))) std::vector<double> mz; std::vector<double> intensities; std::vector<double> mz_out(5); std::vector<double> intensities_out(5); for (Size i=0; i<5; ++i) { intensities.push_back(1.0f); mz.push_back(500.0+0.2*i); } GaussFilterAlgorithm gauss; gauss.initialize(1.0 * 8 /* gaussian_width */, 0.01 /* spacing */, 10.0 /* ppm_tolerance */, false /* use_ppm_tolerance */); gauss.filter(mz.begin(), mz.end(), intensities.begin(), mz_out.begin(), intensities_out.begin()); for (double intensity : intensities_out) { TEST_REAL_SIMILAR(intensity, 1.0) } END_SECTION START_SECTION((bool filter(OpenMS::Interfaces::SpectrumPtr spectrum))) OpenMS::Interfaces::SpectrumPtr spectrum(new OpenMS::Interfaces::Spectrum); spectrum->getMZArray()->data.resize(9); spectrum->getIntensityArray()->data.resize(9); for (Size i=0; i<9; ++i) { spectrum->getIntensityArray()->data[i] = 0.0f; spectrum->getMZArray()->data[i] = 500.0+0.03*i; } spectrum->getIntensityArray()->data[3] = 1.0f; spectrum->getIntensityArray()->data[4] = 0.8f; spectrum->getIntensityArray()->data[5] = 1.2f; TOLERANCE_ABSOLUTE(0.01) GaussFilterAlgorithm gauss; TEST_EQUAL(spectrum->getIntensityArray()->data.size(), 9) gauss.initialize(0.2, 0.01, 1.0, false); gauss.filter(spectrum); TEST_EQUAL(spectrum->getIntensityArray()->data.size(), 9) TEST_REAL_SIMILAR(spectrum->getIntensityArray()->data[0],0.000734827) TEST_REAL_SIMILAR(spectrum->getIntensityArray()->data[1],0.0543746) TEST_REAL_SIMILAR(spectrum->getIntensityArray()->data[2],0.298025) TEST_REAL_SIMILAR(spectrum->getIntensityArray()->data[3],0.707691) TEST_REAL_SIMILAR(spectrum->getIntensityArray()->data[4],0.8963) TEST_REAL_SIMILAR(spectrum->getIntensityArray()->data[5],0.799397) TEST_REAL_SIMILAR(spectrum->getIntensityArray()->data[6],0.352416) TEST_REAL_SIMILAR(spectrum->getIntensityArray()->data[7],0.065132) TEST_REAL_SIMILAR(spectrum->getIntensityArray()->data[8],0.000881793) END_SECTION START_SECTION((bool filter(OpenMS::Interfaces::ChromatogramPtr chromatogram))) OpenMS::Interfaces::ChromatogramPtr chromatogram(new OpenMS::Interfaces::Chromatogram); chromatogram->getTimeArray()->data.resize(9); chromatogram->getIntensityArray()->data.resize(9); for (Size i=0; i<9; ++i) { chromatogram->getIntensityArray()->data[i] = 0.0f; chromatogram->getTimeArray()->data[i] = 500.0+0.03*i; } chromatogram->getIntensityArray()->data[3] = 1.0f; chromatogram->getIntensityArray()->data[4] = 0.8f; chromatogram->getIntensityArray()->data[5] = 1.2f; TOLERANCE_ABSOLUTE(0.01) GaussFilterAlgorithm gauss; TEST_EQUAL(chromatogram->getIntensityArray()->data.size(), 9) gauss.initialize(0.2, 0.01, 1.0, false); gauss.filter(chromatogram); TEST_EQUAL(chromatogram->getIntensityArray()->data.size(), 9) TEST_REAL_SIMILAR(chromatogram->getIntensityArray()->data[0],0.000734827) TEST_REAL_SIMILAR(chromatogram->getIntensityArray()->data[1],0.0543746) TEST_REAL_SIMILAR(chromatogram->getIntensityArray()->data[2],0.298025) TEST_REAL_SIMILAR(chromatogram->getIntensityArray()->data[3],0.707691) TEST_REAL_SIMILAR(chromatogram->getIntensityArray()->data[4],0.8963) TEST_REAL_SIMILAR(chromatogram->getIntensityArray()->data[5],0.799397) TEST_REAL_SIMILAR(chromatogram->getIntensityArray()->data[6],0.352416) TEST_REAL_SIMILAR(chromatogram->getIntensityArray()->data[7],0.065132) TEST_REAL_SIMILAR(chromatogram->getIntensityArray()->data[8],0.000881793) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ClusteringGrid_test.cpp
.cpp
3,123
101
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Lars Nilse $ // $Authors: Lars Nilse $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/ML/CLUSTERING/ClusteringGrid.h> #include <limits> #include <iostream> using namespace OpenMS; START_TEST(ClusteringGrid, "$Id$") std::vector<double> grid_spacing_x; std::vector<double> grid_spacing_y; for (double i = 0; i <=10; ++i) { grid_spacing_x.push_back(i); grid_spacing_y.push_back(i); } ClusteringGrid* nullPointer = nullptr; ClusteringGrid* ptr; START_SECTION(ClusteringGrid(const std::vector<double> &grid_spacing_x, const std::vector<double> &grid_spacing_y)) ClusteringGrid grid(grid_spacing_x, grid_spacing_y); TEST_EQUAL(grid.getGridSpacingX()[3], 3); ptr = new ClusteringGrid(grid_spacing_x, grid_spacing_y); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION ClusteringGrid grid(grid_spacing_x, grid_spacing_y); ClusteringGrid::CellIndex index1 = std::make_pair(2,3); ClusteringGrid::CellIndex index2 = std::make_pair(5,4); ClusteringGrid::CellIndex index3 = std::make_pair(7,7); ClusteringGrid::Point point(6.6,7.7); START_SECTION(std::vector<double> getGridSpacingX() const) TEST_EQUAL(grid.getGridSpacingX()[3], 3); TEST_EQUAL(grid.getGridSpacingX()[10], 10); END_SECTION START_SECTION(std::vector<double> getGridSpacingY() const) TEST_EQUAL(grid.getGridSpacingY()[3], 3); TEST_EQUAL(grid.getGridSpacingY()[10], 10); END_SECTION START_SECTION(void addCluster(const CellIndex &cell_index, const int &cluster_index)) grid.addCluster(index1,1); grid.addCluster(index2,2); TEST_EQUAL(grid.getCellCount(), 2); END_SECTION START_SECTION(void removeCluster(const CellIndex &cell_index, const int &cluster_index)) grid.addCluster(index1,1); grid.addCluster(index2,2); grid.removeCluster(index2,2); TEST_EQUAL(grid.getCellCount(), 1); END_SECTION START_SECTION(void removeAllClusters()) grid.addCluster(index1,1); grid.addCluster(index2,2); grid.removeAllClusters(); TEST_EQUAL(grid.getCellCount(), 0); END_SECTION START_SECTION(std::list<int> getClusters(const CellIndex &cell_index) const) grid.addCluster(index1,1); grid.addCluster(index2,2); TEST_EQUAL(grid.getClusters(index1).front(), 1); END_SECTION START_SECTION(CellIndex getIndex(const Point &position) const) TEST_EQUAL(grid.getIndex(point).first, 7); TEST_EQUAL(grid.getIndex(point).second, 8); END_SECTION START_SECTION(bool isNonEmptyCell(const CellIndex &cell_index) const) grid.addCluster(index1,1); TEST_EQUAL(grid.isNonEmptyCell(index1), true); TEST_EQUAL(grid.isNonEmptyCell(index3), false); END_SECTION START_SECTION(int getCellCount() const) grid.addCluster(index1,1); grid.addCluster(index2,2); TEST_EQUAL(grid.getCellCount(), 2); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ChromatogramExtractor_test.cpp
.cpp
6,140
151
// 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/ChromatogramExtractor.h> #include <OpenMS/test_config.h> #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/FORMAT/TraMLFile.h> #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h> using namespace OpenMS; using namespace std; START_TEST(ChromatogramExtractor, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ChromatogramExtractor* ptr = nullptr; ChromatogramExtractor* nullPointer = nullptr; START_SECTION(ChromatogramExtractor()) { ptr = new ChromatogramExtractor(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~ChromatogramExtractor()) { 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)) { NOT_TESTABLE // is tested in ChromatogramExtractorAlgorithm } END_SECTION START_SECTION(void prepare_coordinates(std::vector< OpenSwath::ChromatogramPtr > & output_chromatograms, std::vector< ExtractionCoordinates > & coordinates, OpenMS::TargetedExperiment & transition_exp, const double rt_extraction_window, const bool ms1) const) { TargetedExperiment transitions; TraMLFile().load(OPENMS_GET_TEST_DATA_PATH("ChromatogramExtractor_input.TraML"), transitions); TargetedExperiment transitions_; TraMLFile().load(OPENMS_GET_TEST_DATA_PATH("ChromatogramExtractor_input.TraML"), transitions_); double rt_extraction_window = 1.0; // Test transitions { std::vector< OpenSwath::ChromatogramPtr > output_chromatograms; std::vector< ChromatogramExtractor::ExtractionCoordinates > coordinates; ChromatogramExtractor extractor; extractor.prepare_coordinates(output_chromatograms, coordinates, transitions, rt_extraction_window, false); TEST_TRUE(transitions == transitions_) TEST_EQUAL(output_chromatograms.size(), coordinates.size()) TEST_EQUAL(coordinates.size(), 3) TEST_EQUAL(coordinates[0].mz, 618.31) TEST_EQUAL(coordinates[1].mz, 628.45) TEST_EQUAL(coordinates[2].mz, 654.38) TEST_REAL_SIMILAR(coordinates[0].rt_start, 1.5) TEST_REAL_SIMILAR(coordinates[1].rt_start, 43.5) TEST_REAL_SIMILAR(coordinates[2].rt_start, 43.5) TEST_REAL_SIMILAR(coordinates[0].rt_end, 2.5) TEST_REAL_SIMILAR(coordinates[1].rt_end, 44.5) TEST_REAL_SIMILAR(coordinates[2].rt_end, 44.5) // Note: they are ordered according to m/z TEST_EQUAL(coordinates[0].id, "tr3") TEST_EQUAL(coordinates[1].id, "tr1") TEST_EQUAL(coordinates[2].id, "tr2") } // Test peptides { std::vector< OpenSwath::ChromatogramPtr > output_chromatograms; std::vector< ChromatogramExtractor::ExtractionCoordinates > coordinates; ChromatogramExtractor extractor; extractor.prepare_coordinates(output_chromatograms, coordinates, transitions, rt_extraction_window, true); TEST_TRUE(transitions == transitions_) TEST_EQUAL(output_chromatograms.size(), coordinates.size()) TEST_EQUAL(coordinates.size(), 2) TEST_EQUAL(coordinates[0].mz, 500) TEST_EQUAL(coordinates[1].mz, 501) TEST_REAL_SIMILAR(coordinates[0].rt_start, 43.5) TEST_REAL_SIMILAR(coordinates[1].rt_start, 1.5) TEST_REAL_SIMILAR(coordinates[0].rt_end, 44.5) TEST_REAL_SIMILAR(coordinates[1].rt_end, 2.5) TEST_EQUAL(coordinates[0].id, "tr_gr1_Precursor_i0") TEST_EQUAL(coordinates[1].id, "tr_gr2_Precursor_i0") TEST_EQUAL(OpenSwathHelper::computeTransitionGroupId(coordinates[0].id), "tr_gr1") TEST_EQUAL(OpenSwathHelper::computeTransitionGroupId(coordinates[1].id), "tr_gr2") } } END_SECTION START_SECTION((template < typename TransitionExpT > static void return_chromatogram(std::vector< OpenSwath::ChromatogramPtr > &chromatograms, std::vector< ExtractionCoordinates > &coordinates, TransitionExpT &transition_exp_used, SpectrumSettings settings, std::vector< OpenMS::MSChromatogram > &output_chromatograms, bool ms1))) { double extract_window = 0.05; double ppm = false; double rt_extraction_window = -1; String extraction_function = "tophat"; TargetedExperiment transitions; TraMLFile().load(OPENMS_GET_TEST_DATA_PATH("ChromatogramExtractor_input.TraML"), transitions); std::shared_ptr<PeakMap > exp(new PeakMap); MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("ChromatogramExtractor_input.mzML"), *exp); OpenSwath::SpectrumAccessPtr expptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp); std::vector< OpenMS::MSChromatogram > chromatograms; { std::vector< OpenSwath::ChromatogramPtr > output_chromatograms; std::vector< ChromatogramExtractor::ExtractionCoordinates > coordinates; ChromatogramExtractor extractor; extractor.prepare_coordinates(output_chromatograms, coordinates, transitions, rt_extraction_window, false); extractor.extractChromatograms(expptr, output_chromatograms, coordinates, extract_window, ppm, extraction_function); extractor.return_chromatogram(output_chromatograms, coordinates, transitions, (*exp)[0], chromatograms, false); } TEST_EQUAL(chromatograms.size(), 3) TEST_EQUAL(chromatograms[0].getChromatogramType(), ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM) TEST_REAL_SIMILAR(chromatograms[0].getProduct().getMZ(), 618.31) TEST_EQUAL(chromatograms[0].getPrecursor().metaValueExists("peptide_sequence"), true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FLASHHelperClasses_test.cpp
.cpp
23,586
814
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeong, Jihyung Kim $ // $Authors: Kyowon Jeong, Jihyung Kim $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h> #include <OpenMS/CONCEPT/Constants.h> #include <cmath> #include <unordered_set> /////////////////////////// START_TEST(FLASHHelperClasses, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; typedef FLASHHelperClasses::LogMzPeak LogMzPeak; typedef FLASHHelperClasses::MassFeature MassFeature; typedef FLASHHelperClasses::IsobaricQuantities IsobaricQuantities; typedef FLASHHelperClasses::PrecalculatedAveragine PrecalculatedAveragine; ///////////////////////////////////////////////////////////// // Static utility function tests ///////////////////////////////////////////////////////////// START_SECTION(static float getChargeMass(bool positive_ioniziation_mode)) { // Positive mode should return proton mass float pos_mass = FLASHHelperClasses::getChargeMass(true); TEST_REAL_SIMILAR(pos_mass, Constants::PROTON_MASS_U) // Negative mode should return negative proton mass float neg_mass = FLASHHelperClasses::getChargeMass(false); TEST_REAL_SIMILAR(neg_mass, -Constants::PROTON_MASS_U) } END_SECTION START_SECTION(static double getLogMz(double mz, bool positive)) { // Test positive mode double mz = 500.0; double log_mz_pos = FLASHHelperClasses::getLogMz(mz, true); double expected_pos = std::log(mz - Constants::PROTON_MASS_U); TEST_REAL_SIMILAR(log_mz_pos, expected_pos) // Test negative mode double log_mz_neg = FLASHHelperClasses::getLogMz(mz, false); double expected_neg = std::log(mz + Constants::PROTON_MASS_U); TEST_REAL_SIMILAR(log_mz_neg, expected_neg) // Test with different m/z values double mz2 = 1000.0; double log_mz2 = FLASHHelperClasses::getLogMz(mz2, true); TEST_REAL_SIMILAR(log_mz2, std::log(mz2 - Constants::PROTON_MASS_U)) } END_SECTION ///////////////////////////////////////////////////////////// // LogMzPeak tests ///////////////////////////////////////////////////////////// LogMzPeak* lmp_ptr = nullptr; LogMzPeak* lmp_null_ptr = nullptr; START_SECTION(LogMzPeak()) { lmp_ptr = new LogMzPeak(); TEST_NOT_EQUAL(lmp_ptr, lmp_null_ptr) // Check default values TEST_REAL_SIMILAR(lmp_ptr->mz, 0.0) TEST_REAL_SIMILAR(lmp_ptr->intensity, 0.0f) TEST_REAL_SIMILAR(lmp_ptr->logMz, -1000.0) TEST_REAL_SIMILAR(lmp_ptr->mass, 0.0) TEST_EQUAL(lmp_ptr->abs_charge, 0) TEST_EQUAL(lmp_ptr->is_positive, true) TEST_EQUAL(lmp_ptr->isotopeIndex, -1) } END_SECTION START_SECTION(~LogMzPeak()) { delete lmp_ptr; } END_SECTION START_SECTION(explicit LogMzPeak(const Peak1D& peak, bool positive)) { // Test with positive mode Peak1D peak; peak.setMZ(500.5); peak.setIntensity(10000.0f); LogMzPeak lmp_pos(peak, true); TEST_REAL_SIMILAR(lmp_pos.mz, 500.5) TEST_REAL_SIMILAR(lmp_pos.intensity, 10000.0f) TEST_EQUAL(lmp_pos.is_positive, true) TEST_EQUAL(lmp_pos.abs_charge, 0) TEST_EQUAL(lmp_pos.isotopeIndex, 0) double expected_logMz = std::log(500.5 - Constants::PROTON_MASS_U); TEST_REAL_SIMILAR(lmp_pos.logMz, expected_logMz) // Test with negative mode LogMzPeak lmp_neg(peak, false); TEST_REAL_SIMILAR(lmp_neg.mz, 500.5) TEST_EQUAL(lmp_neg.is_positive, false) double expected_logMz_neg = std::log(500.5 + Constants::PROTON_MASS_U); TEST_REAL_SIMILAR(lmp_neg.logMz, expected_logMz_neg) } END_SECTION START_SECTION(LogMzPeak(const LogMzPeak&)) { Peak1D peak; peak.setMZ(750.25); peak.setIntensity(5000.0f); LogMzPeak original(peak, true); original.abs_charge = 3; original.isotopeIndex = 2; original.mass = 2248.0; LogMzPeak copy(original); TEST_REAL_SIMILAR(copy.mz, 750.25) TEST_REAL_SIMILAR(copy.intensity, 5000.0f) TEST_EQUAL(copy.abs_charge, 3) TEST_EQUAL(copy.isotopeIndex, 2) TEST_REAL_SIMILAR(copy.mass, 2248.0) TEST_EQUAL(copy.is_positive, true) TEST_REAL_SIMILAR(copy.logMz, original.logMz) } END_SECTION START_SECTION(double getUnchargedMass() const) { Peak1D peak; peak.setMZ(500.5); peak.setIntensity(1000.0f); LogMzPeak lmp(peak, true); // With no charge set, should return 0 TEST_REAL_SIMILAR(lmp.getUnchargedMass(), 0.0) // Set charge and mass = 0 (will calculate from mz) lmp.abs_charge = 2; lmp.mass = 0; double expected_mass = (500.5 - Constants::PROTON_MASS_U) * 2; TEST_REAL_SIMILAR(lmp.getUnchargedMass(), expected_mass) // With mass already set > 0, should return that mass lmp.mass = 999.5; TEST_REAL_SIMILAR(lmp.getUnchargedMass(), 999.5) // Test negative mode Peak1D peak2; peak2.setMZ(500.5); peak2.setIntensity(1000.0f); LogMzPeak lmp_neg(peak2, false); lmp_neg.abs_charge = 2; lmp_neg.mass = 0; double expected_neg = (500.5 + Constants::PROTON_MASS_U) * 2; TEST_REAL_SIMILAR(lmp_neg.getUnchargedMass(), expected_neg) } END_SECTION START_SECTION(bool operator<(const LogMzPeak& a) const) { LogMzPeak lmp1, lmp2, lmp3; // Different logMz values lmp1.logMz = 5.0; lmp1.intensity = 100.0f; lmp2.logMz = 6.0; lmp2.intensity = 100.0f; TEST_EQUAL(lmp1 < lmp2, true) TEST_EQUAL(lmp2 < lmp1, false) // Same logMz, different intensity lmp3.logMz = 5.0; lmp3.intensity = 200.0f; TEST_EQUAL(lmp1 < lmp3, true) // same logMz, but lmp1 has lower intensity TEST_EQUAL(lmp3 < lmp1, false) } END_SECTION START_SECTION(bool operator>(const LogMzPeak& a) const) { LogMzPeak lmp1, lmp2, lmp3; // Different logMz values lmp1.logMz = 6.0; lmp1.intensity = 100.0f; lmp2.logMz = 5.0; lmp2.intensity = 100.0f; TEST_EQUAL(lmp1 > lmp2, true) TEST_EQUAL(lmp2 > lmp1, false) // Same logMz, different intensity lmp3.logMz = 6.0; lmp3.intensity = 50.0f; TEST_EQUAL(lmp1 > lmp3, true) // same logMz, but lmp1 has higher intensity TEST_EQUAL(lmp3 > lmp1, false) } END_SECTION START_SECTION(bool operator==(const LogMzPeak& other) const) { LogMzPeak lmp1, lmp2, lmp3; lmp1.logMz = 5.5; lmp1.intensity = 100.0f; lmp2.logMz = 5.5; lmp2.intensity = 100.0f; lmp3.logMz = 5.5; lmp3.intensity = 200.0f; TEST_EQUAL(lmp1 == lmp2, true) TEST_EQUAL(lmp1 == lmp3, false) // same logMz but different intensity } END_SECTION ///////////////////////////////////////////////////////////// // MassFeature tests ///////////////////////////////////////////////////////////// START_SECTION([MassFeature] bool operator<(const MassFeature& a) const) { MassFeature mf1, mf2; mf1.avg_mass = 10000.0; mf2.avg_mass = 15000.0; TEST_EQUAL(mf1 < mf2, true) TEST_EQUAL(mf2 < mf1, false) } END_SECTION START_SECTION([MassFeature] bool operator>(const MassFeature& a) const) { MassFeature mf1, mf2; mf1.avg_mass = 15000.0; mf2.avg_mass = 10000.0; TEST_EQUAL(mf1 > mf2, true) TEST_EQUAL(mf2 > mf1, false) } END_SECTION START_SECTION([MassFeature] bool operator==(const MassFeature& other) const) { MassFeature mf1, mf2, mf3; mf1.avg_mass = 10000.0; mf2.avg_mass = 10000.0; mf3.avg_mass = 10001.0; TEST_EQUAL(mf1 == mf2, true) TEST_EQUAL(mf1 == mf3, false) } END_SECTION START_SECTION([MassFeature] member variables) { MassFeature mf; // Test setting and accessing all member variables mf.index = 42; mf.iso_offset = 1; mf.scan_number = 100; mf.min_scan_number = 95; mf.max_scan_number = 105; mf.rep_charge = 10; mf.avg_mass = 15000.5; mf.min_charge = 5; mf.max_charge = 15; mf.charge_count = 11; mf.isotope_score = 0.95; mf.qscore = 0.85; mf.rep_mz = 1500.05; mf.is_decoy = false; mf.ms_level = 1; TEST_EQUAL(mf.index, 42) TEST_EQUAL(mf.iso_offset, 1) TEST_EQUAL(mf.scan_number, 100) TEST_EQUAL(mf.min_scan_number, 95) TEST_EQUAL(mf.max_scan_number, 105) TEST_EQUAL(mf.rep_charge, 10) TEST_REAL_SIMILAR(mf.avg_mass, 15000.5) TEST_EQUAL(mf.min_charge, 5) TEST_EQUAL(mf.max_charge, 15) TEST_EQUAL(mf.charge_count, 11) TEST_REAL_SIMILAR(mf.isotope_score, 0.95) TEST_REAL_SIMILAR(mf.qscore, 0.85) TEST_REAL_SIMILAR(mf.rep_mz, 1500.05) TEST_EQUAL(mf.is_decoy, false) TEST_EQUAL(mf.ms_level, 1) // Test per_charge_intensity and per_isotope_intensity vectors mf.per_charge_intensity.resize(20, 0.0f); mf.per_isotope_intensity.resize(10, 0.0f); mf.per_charge_intensity[10] = 5000.0f; mf.per_isotope_intensity[0] = 10000.0f; TEST_REAL_SIMILAR(mf.per_charge_intensity[10], 5000.0f) TEST_REAL_SIMILAR(mf.per_isotope_intensity[0], 10000.0f) } END_SECTION ///////////////////////////////////////////////////////////// // IsobaricQuantities tests ///////////////////////////////////////////////////////////// START_SECTION([IsobaricQuantities] bool empty() const) { IsobaricQuantities iq; // Initially empty (no quantities) TEST_EQUAL(iq.empty(), true) // Add a quantity iq.quantities.push_back(100.0); TEST_EQUAL(iq.empty(), false) // Clear and verify empty again iq.quantities.clear(); TEST_EQUAL(iq.empty(), true) } END_SECTION START_SECTION([IsobaricQuantities] member variables) { IsobaricQuantities iq; // Test setting and accessing all member variables iq.scan = 150; iq.rt = 600.5; iq.precursor_mz = 800.4; iq.precursor_mass = 7996.0; TEST_EQUAL(iq.scan, 150) TEST_REAL_SIMILAR(iq.rt, 600.5) TEST_REAL_SIMILAR(iq.precursor_mz, 800.4) TEST_REAL_SIMILAR(iq.precursor_mass, 7996.0) // Test quantities vectors iq.quantities = {100.0, 200.0, 300.0, 400.0}; iq.merged_quantities = {150.0, 350.0}; TEST_EQUAL(iq.quantities.size(), 4) TEST_REAL_SIMILAR(iq.quantities[0], 100.0) TEST_REAL_SIMILAR(iq.quantities[3], 400.0) TEST_EQUAL(iq.merged_quantities.size(), 2) TEST_REAL_SIMILAR(iq.merged_quantities[0], 150.0) } END_SECTION ///////////////////////////////////////////////////////////// // PrecalculatedAveragine tests ///////////////////////////////////////////////////////////// START_SECTION(PrecalculatedAveragine()) { PrecalculatedAveragine* pa_ptr = new PrecalculatedAveragine(); TEST_NOT_EQUAL(pa_ptr, nullptr) delete pa_ptr; } END_SECTION START_SECTION(PrecalculatedAveragine(double min_mass, double max_mass, double delta, CoarseIsotopePatternGenerator& generator, bool use_RNA_averagine, double decoy_iso_distance = -1)) { CoarseIsotopePatternGenerator generator(100); // Create PrecalculatedAveragine for peptide PrecalculatedAveragine pa(500.0, 5000.0, 100.0, generator, false); // Test that it was created and can return isotope distributions IsotopeDistribution iso = pa.get(1000.0); TEST_EQUAL(iso.size() > 0, true) // Test RNA averagine PrecalculatedAveragine pa_rna(500.0, 5000.0, 100.0, generator, true); IsotopeDistribution iso_rna = pa_rna.get(1000.0); TEST_EQUAL(iso_rna.size() > 0, true) } END_SECTION START_SECTION(PrecalculatedAveragine(const PrecalculatedAveragine&)) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine original(500.0, 5000.0, 100.0, generator, false); PrecalculatedAveragine copy(original); IsotopeDistribution iso_orig = original.get(2000.0); IsotopeDistribution iso_copy = copy.get(2000.0); TEST_EQUAL(iso_orig.size(), iso_copy.size()) if (iso_orig.size() > 0 && iso_copy.size() > 0) { TEST_REAL_SIMILAR(iso_orig[0].getIntensity(), iso_copy[0].getIntensity()) } } END_SECTION START_SECTION(PrecalculatedAveragine(PrecalculatedAveragine&& other) noexcept) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine original(500.0, 5000.0, 100.0, generator, false); Size orig_apex = original.getApexIndex(2000.0); PrecalculatedAveragine moved(std::move(original)); TEST_EQUAL(moved.getApexIndex(2000.0), orig_apex) } END_SECTION START_SECTION(PrecalculatedAveragine& operator=(const PrecalculatedAveragine& pc)) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine original(500.0, 5000.0, 100.0, generator, false); PrecalculatedAveragine assigned; assigned = original; IsotopeDistribution iso_orig = original.get(2000.0); IsotopeDistribution iso_assigned = assigned.get(2000.0); TEST_EQUAL(iso_orig.size(), iso_assigned.size()) } END_SECTION START_SECTION(PrecalculatedAveragine& operator=(PrecalculatedAveragine&& pc) noexcept) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine original(500.0, 5000.0, 100.0, generator, false); Size orig_apex = original.getApexIndex(2000.0); PrecalculatedAveragine moved_assigned; moved_assigned = std::move(original); TEST_EQUAL(moved_assigned.getApexIndex(2000.0), orig_apex) } END_SECTION START_SECTION(IsotopeDistribution get(double mass) const) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine pa(500.0, 10000.0, 100.0, generator, false); // Test various masses IsotopeDistribution iso1 = pa.get(1000.0); IsotopeDistribution iso2 = pa.get(5000.0); IsotopeDistribution iso3 = pa.get(9000.0); TEST_EQUAL(iso1.size() > 0, true) TEST_EQUAL(iso2.size() > 0, true) TEST_EQUAL(iso3.size() > 0, true) // Higher mass should have more isotopes with significant intensity // (apex moves to higher index) Size apex1 = pa.getApexIndex(1000.0); Size apex2 = pa.getApexIndex(5000.0); Size apex3 = pa.getApexIndex(9000.0); TEST_EQUAL(apex1 <= apex2, true) TEST_EQUAL(apex2 <= apex3, true) // Test mass exceeding max - should return distribution for max mass IsotopeDistribution iso_exceed = pa.get(20000.0); TEST_EQUAL(iso_exceed.size() > 0, true) } END_SECTION START_SECTION(size_t getMaxIsotopeIndex() const) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine pa(500.0, 5000.0, 100.0, generator, false); pa.setMaxIsotopeIndex(50); TEST_EQUAL(pa.getMaxIsotopeIndex(), 50) } END_SECTION START_SECTION(void setMaxIsotopeIndex(int index)) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine pa(500.0, 5000.0, 100.0, generator, false); pa.setMaxIsotopeIndex(30); TEST_EQUAL(pa.getMaxIsotopeIndex(), 30) pa.setMaxIsotopeIndex(100); TEST_EQUAL(pa.getMaxIsotopeIndex(), 100) } END_SECTION START_SECTION(Size getLeftCountFromApex(double mass) const) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine pa(500.0, 10000.0, 100.0, generator, false); Size left1 = pa.getLeftCountFromApex(1000.0); Size left2 = pa.getLeftCountFromApex(5000.0); // Should return reasonable values (at least minimum of 2) TEST_EQUAL(left1 >= 2, true) TEST_EQUAL(left2 >= 2, true) } END_SECTION START_SECTION(Size getRightCountFromApex(double mass) const) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine pa(500.0, 10000.0, 100.0, generator, false); Size right1 = pa.getRightCountFromApex(1000.0); Size right2 = pa.getRightCountFromApex(5000.0); // Should return reasonable values (at least minimum of 2) TEST_EQUAL(right1 >= 2, true) TEST_EQUAL(right2 >= 2, true) } END_SECTION START_SECTION(Size getApexIndex(double mass) const) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine pa(500.0, 10000.0, 100.0, generator, false); Size apex1 = pa.getApexIndex(1000.0); Size apex5 = pa.getApexIndex(5000.0); Size apex9 = pa.getApexIndex(9000.0); // Apex should shift to higher indices for higher masses TEST_EQUAL(apex1 <= apex5, true) TEST_EQUAL(apex5 <= apex9, true) // For small mass, apex should be at or near 0 Size apex_small = pa.getApexIndex(600.0); TEST_EQUAL(apex_small <= 2, true) } END_SECTION START_SECTION(Size getLastIndex(double mass) const) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine pa(500.0, 10000.0, 100.0, generator, false); Size last1 = pa.getLastIndex(1000.0); Size last5 = pa.getLastIndex(5000.0); // Last index should be apex + right count Size apex1 = pa.getApexIndex(1000.0); Size right1 = pa.getRightCountFromApex(1000.0); TEST_EQUAL(last1, apex1 + right1) Size apex5 = pa.getApexIndex(5000.0); Size right5 = pa.getRightCountFromApex(5000.0); TEST_EQUAL(last5, apex5 + right5) } END_SECTION START_SECTION(double getAverageMassDelta(double mass) const) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine pa(500.0, 10000.0, 100.0, generator, false); double delta1 = pa.getAverageMassDelta(1000.0); double delta5 = pa.getAverageMassDelta(5000.0); double delta9 = pa.getAverageMassDelta(9000.0); // Average mass should be greater than monoisotopic mass (delta > 0) TEST_EQUAL(delta1 > 0, true) TEST_EQUAL(delta5 > 0, true) TEST_EQUAL(delta9 > 0, true) // Delta should increase with mass TEST_EQUAL(delta1 < delta5, true) TEST_EQUAL(delta5 < delta9, true) } END_SECTION START_SECTION(double getMostAbundantMassDelta(double mass) const) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine pa(500.0, 10000.0, 100.0, generator, false); double delta1 = pa.getMostAbundantMassDelta(1000.0); double delta5 = pa.getMostAbundantMassDelta(5000.0); double delta9 = pa.getMostAbundantMassDelta(9000.0); // Most abundant mass delta should be non-negative TEST_EQUAL(delta1 >= 0, true) TEST_EQUAL(delta5 >= 0, true) TEST_EQUAL(delta9 >= 0, true) // For small masses, monoisotopic is often most abundant (delta ~ 0) // For larger masses, delta should increase TEST_EQUAL(delta1 <= delta5, true) } END_SECTION START_SECTION(double getSNRMultiplicationFactor(double mass) const) { CoarseIsotopePatternGenerator generator(100); PrecalculatedAveragine pa(500.0, 10000.0, 100.0, generator, false); double snr1 = pa.getSNRMultiplicationFactor(1000.0); double snr5 = pa.getSNRMultiplicationFactor(5000.0); // SNR factor should be positive TEST_EQUAL(snr1 > 0, true) TEST_EQUAL(snr5 > 0, true) } END_SECTION ///////////////////////////////////////////////////////////// // Test decoy isotope pattern generation ///////////////////////////////////////////////////////////// START_SECTION([PrecalculatedAveragine] decoy isotope patterns) { CoarseIsotopePatternGenerator generator(100); // Create normal and decoy averagine patterns PrecalculatedAveragine pa_normal(500.0, 5000.0, 100.0, generator, false, -1); PrecalculatedAveragine pa_decoy(500.0, 5000.0, 100.0, generator, false, 1.5); IsotopeDistribution iso_normal = pa_normal.get(2000.0); IsotopeDistribution iso_decoy = pa_decoy.get(2000.0); // Both should have distributions TEST_EQUAL(iso_normal.size() > 0, true) TEST_EQUAL(iso_decoy.size() > 0, true) // Decoy pattern should be different (scaled isotope distances) // The m/z values will be different if (iso_normal.size() > 1 && iso_decoy.size() > 1) { double normal_spacing = iso_normal[1].getMZ() - iso_normal[0].getMZ(); double decoy_spacing = iso_decoy[1].getMZ() - iso_decoy[0].getMZ(); // Decoy spacing should be approximately 1.5x normal spacing TEST_REAL_SIMILAR(decoy_spacing / normal_spacing, 1.5) } } END_SECTION ///////////////////////////////////////////////////////////// // Integration tests: combining multiple classes ///////////////////////////////////////////////////////////// START_SECTION([Integration] LogMzPeak with charge and mass calculations) { // Create a peak and test full workflow Peak1D peak; peak.setMZ(857.0789); // m/z for a +3 charged peptide peak.setIntensity(50000.0f); LogMzPeak lmp(peak, true); lmp.abs_charge = 3; lmp.isotopeIndex = 0; // Calculate uncharged mass double mass = lmp.getUnchargedMass(); // Expected: (857.0789 - 1.007276) * 3 = 2568.2148 double expected_mass = (857.0789 - Constants::PROTON_MASS_U) * 3; TEST_REAL_SIMILAR(mass, expected_mass) // Set mass directly and verify lmp.mass = 2568.0; TEST_REAL_SIMILAR(lmp.getUnchargedMass(), 2568.0) } END_SECTION START_SECTION([Integration] MassFeature sorting) { // Create multiple MassFeatures and test sorting std::vector<MassFeature> features; MassFeature mf1, mf2, mf3; mf1.avg_mass = 15000.0; mf1.index = 1; mf2.avg_mass = 10000.0; mf2.index = 2; mf3.avg_mass = 20000.0; mf3.index = 3; features.push_back(mf1); features.push_back(mf2); features.push_back(mf3); // Sort by mass using operator< std::sort(features.begin(), features.end()); TEST_REAL_SIMILAR(features[0].avg_mass, 10000.0) TEST_REAL_SIMILAR(features[1].avg_mass, 15000.0) TEST_REAL_SIMILAR(features[2].avg_mass, 20000.0) } END_SECTION START_SECTION([Integration] LogMzPeak sorting) { // Create multiple LogMzPeaks and test sorting std::vector<LogMzPeak> peaks; LogMzPeak lmp1, lmp2, lmp3; lmp1.logMz = 6.5; lmp1.intensity = 1000.0f; lmp2.logMz = 6.2; lmp2.intensity = 2000.0f; lmp3.logMz = 6.8; lmp3.intensity = 1500.0f; peaks.push_back(lmp1); peaks.push_back(lmp2); peaks.push_back(lmp3); // Sort by logMz using operator< std::sort(peaks.begin(), peaks.end()); TEST_REAL_SIMILAR(peaks[0].logMz, 6.2) TEST_REAL_SIMILAR(peaks[1].logMz, 6.5) TEST_REAL_SIMILAR(peaks[2].logMz, 6.8) } END_SECTION ///////////////////////////////////////////////////////////// // Hash tests ///////////////////////////////////////////////////////////// START_SECTION([MassFeature] std::hash) { std::hash<MassFeature> hasher; // Test that equal objects have equal hashes MassFeature mf1, mf2; mf1.avg_mass = 10000.0; mf2.avg_mass = 10000.0; TEST_EQUAL(mf1 == mf2, true) TEST_EQUAL(hasher(mf1), hasher(mf2)) // Test that different objects have different hashes (not guaranteed, but likely) MassFeature mf3; mf3.avg_mass = 15000.0; TEST_EQUAL(mf1 == mf3, false) TEST_NOT_EQUAL(hasher(mf1), hasher(mf3)) // Test usability in unordered_set std::unordered_set<MassFeature> feature_set; feature_set.insert(mf1); feature_set.insert(mf2); // Should not be added (equal to mf1) feature_set.insert(mf3); TEST_EQUAL(feature_set.size(), 2) TEST_EQUAL(feature_set.count(mf1), 1) TEST_EQUAL(feature_set.count(mf3), 1) } END_SECTION START_SECTION([LogMzPeak] std::hash) { std::hash<LogMzPeak> hasher; // Test that equal objects have equal hashes LogMzPeak lmp1, lmp2; lmp1.logMz = 5.5; lmp1.intensity = 100.0f; lmp2.logMz = 5.5; lmp2.intensity = 100.0f; TEST_EQUAL(lmp1 == lmp2, true) TEST_EQUAL(hasher(lmp1), hasher(lmp2)) // Test that different objects have different hashes LogMzPeak lmp3; lmp3.logMz = 5.5; lmp3.intensity = 200.0f; // Different intensity TEST_EQUAL(lmp1 == lmp3, false) TEST_NOT_EQUAL(hasher(lmp1), hasher(lmp3)) LogMzPeak lmp4; lmp4.logMz = 6.0; // Different logMz lmp4.intensity = 100.0f; TEST_EQUAL(lmp1 == lmp4, false) TEST_NOT_EQUAL(hasher(lmp1), hasher(lmp4)) // Test usability in unordered_set std::unordered_set<LogMzPeak> peak_set; peak_set.insert(lmp1); peak_set.insert(lmp2); // Should not be added (equal to lmp1) peak_set.insert(lmp3); peak_set.insert(lmp4); TEST_EQUAL(peak_set.size(), 3) TEST_EQUAL(peak_set.count(lmp1), 1) TEST_EQUAL(peak_set.count(lmp3), 1) TEST_EQUAL(peak_set.count(lmp4), 1) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AbsoluteQuantitation_test.cpp
.cpp
46,123
1,031
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Douglas McCloskey $ // $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/METADATA/AbsoluteQuantitationStandards.h> /////////////////////////// #include <OpenMS/ANALYSIS/QUANTITATION/AbsoluteQuantitation.h> using namespace OpenMS; using namespace std; /////////////////////////// std::vector<AbsoluteQuantitationStandards::featureConcentration> make_serL_standards() { // TEST 1: ser-L static const double arrx1[] = {2.32e4,2.45e4,1.78e4,2.11e4,1.91e4, 2.06e4,1.85e4,1.53e4,1.40e4,1.03e4,1.07e4,6.68e3,5.27e3,2.83e3}; std::vector<double> x1 (arrx1, arrx1 + sizeof(arrx1) / sizeof(arrx1[0]) ); static const double arry1[] = {4.94e3,6.55e3,7.37e3,1.54e4,2.87e4, 5.41e4,1.16e5,1.85e5,3.41e5,7.54e5,9.76e5,1.42e6,1.93e6,2.23e6}; std::vector<double> y1 (arry1, arry1 + sizeof(arry1) / sizeof(arry1[0]) ); static const double arrz1[] = {1.00e-2,2.00e-2,4.00e-2,1.00e-1,2.00e-1, 4.00e-1,1.00e0,2.00e0,4.00e0,1.00e1,2.00e1,4.00e1,1.00e2,2.00e2}; std::vector<double> z1 (arrz1, arrz1 + sizeof(arrz1) / sizeof(arrz1[0]) ); // set-up the features std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations; AbsoluteQuantitationStandards::featureConcentration component_concentration; Feature component, IS_component; for (size_t i = 0; i < x1.size(); ++i) { component.setMetaValue("native_id","ser-L.ser-L_1.Light"); component.setMetaValue("peak_apex_int",y1[i]); IS_component.setMetaValue("native_id","ser-L.ser-L_1.Heavy"); IS_component.setMetaValue("peak_apex_int",x1[i]); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = z1[i]; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 1.0; component_concentrations.push_back(component_concentration); } return component_concentrations; } std::vector<AbsoluteQuantitationStandards::featureConcentration> make_amp_standards() { // TEST 2: amp static const double arrx2[] = {2.15e5,2.32e5,2.69e5,2.53e5,2.50e5, 2.75e5,2.67e5,3.31e5,3.15e5,3.04e5,3.45e5,3.91e5,4.62e5,3.18e5}; std::vector<double> x2 (arrx2, arrx2 + sizeof(arrx2) / sizeof(arrx2[0]) ); static const double arry2[] = {4.40e2,1.15e3,1.53e3,2.01e3,4.47e3, 7.36e3,2.18e4,4.46e4,8.50e4,2.33e5,5.04e5,1.09e6,2.54e6,3.64e6}; std::vector<double> y2 (arry2, arry2 + sizeof(arry2) / sizeof(arry2[0]) ); static const double arrz2[] = {2.00e-3,4.00e-3,8.00e-3,2.00e-2,4.00e-2, 8.00e-2,2.00e-1,4.00e-1,8.00e-1,2.00e0,4.00e0,8.00e0,2.00e1,4.00e1}; std::vector<double> z2 (arrz2, arrz2 + sizeof(arrz2) / sizeof(arrz2[0]) ); // set-up the features std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations; AbsoluteQuantitationStandards::featureConcentration component_concentration; Feature component, IS_component; for (size_t i = 0; i < x2.size(); ++i) { component.setMetaValue("native_id","amp.amp_1.Light"); component.setMetaValue("peak_apex_int",y2[i]); IS_component.setMetaValue("native_id","amp.amp_1.Heavy"); IS_component.setMetaValue("peak_apex_int",x2[i]); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = z2[i]; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 1.0; component_concentrations.push_back(component_concentration); } return component_concentrations; } std::vector<AbsoluteQuantitationStandards::featureConcentration> make_atp_standards() { // TEST 3: atp static const double arrx3[] = {8.28e2,1.32e3,1.57e3,1.63e3,1.48e3, 2.43e3,4.44e3,1.03e4,1.75e4,6.92e4,1.97e5,2.69e5,3.20e5,3.22e5}; std::vector<double> x3 (arrx3, arrx3 + sizeof(arrx3) / sizeof(arrx3[0]) ); static const double arry3[] = {2.21e2,4.41e2,3.31e2,2.21e2,3.09e2, 5.96e2,1.26e3,2.49e3,1.12e4,8.79e4,4.68e5,1.38e6,3.46e6,4.19e6}; std::vector<double> y3 (arry3, arry3 + sizeof(arry3) / sizeof(arry3[0]) ); static const double arrz3[] = {2.00e-3,4.00e-3,8.00e-3,2.00e-2,4.00e-2, 8.00e-2,2.00e-1,4.00e-1,8.00e-1,2.00e0,4.00e0,8.00e0,2.00e1,4.00e1}; std::vector<double> z3 (arrz3, arrz3 + sizeof(arrz3) / sizeof(arrz3[0]) ); // set-up the features std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations; AbsoluteQuantitationStandards::featureConcentration component_concentration; Feature component, IS_component; for (size_t i = 0; i < x3.size(); ++i) { component.setMetaValue("native_id","atp.atp_1.Light"); component.setMetaValue("peak_apex_int",y3[i]); IS_component.setMetaValue("native_id","atp.atp_1.Heavy"); IS_component.setMetaValue("peak_apex_int",x3[i]); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = z3[i]; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 1.0; component_concentrations.push_back(component_concentration); } return component_concentrations; } ///////////////////////////////////////////////////////////// START_TEST(AbsoluteQuantitation, "$Id$") ///////////////////////////////////////////////////////////// class AbsoluteQuantitation_test : public AbsoluteQuantitation { public : int jackknifeOutlierCandidate_(const std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params) { return AbsoluteQuantitation::jackknifeOutlierCandidate_(component_concentrations, feature_name, transformation_model, transformation_model_params); } int residualOutlierCandidate_(const std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params) { return AbsoluteQuantitation::residualOutlierCandidate_(component_concentrations, feature_name, transformation_model, transformation_model_params); } std::vector<AbsoluteQuantitationStandards::featureConcentration> extractComponents_( const std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations, std::vector<size_t> component_concentrations_indices) { return AbsoluteQuantitation::extractComponents_( component_concentrations, component_concentrations_indices); } }; ///////////////////////////////////////////////////////////// AbsoluteQuantitation* ptr = nullptr; AbsoluteQuantitation* nullPointer = nullptr; START_SECTION((AbsoluteQuantitation())) ptr = new AbsoluteQuantitation(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~AbsoluteQuantitation())) delete ptr; END_SECTION START_SECTION((double calculateRatio(const Feature & component_1, const Feature & component_2, const String feature_name))) AbsoluteQuantitation absquant; String feature_name = "peak_apex_int"; double inf = std::numeric_limits<double>::infinity(); // dummy features OpenMS::Feature component_1, component_2; component_1.setMetaValue(feature_name, 5.0); component_1.setMetaValue("native_id","component1"); component_2.setMetaValue(feature_name, 5.0); component_2.setMetaValue("native_id","component2"); // tests TEST_REAL_SIMILAR(absquant.calculateRatio(component_1,component_2,feature_name),1.0); component_2.setMetaValue(feature_name, 0.0); TEST_REAL_SIMILAR(absquant.calculateRatio(component_1,component_2,feature_name),inf); // dummy features OpenMS::Feature component_3, component_4; component_3.setMetaValue("peak_area", 5.0); component_3.setMetaValue("native_id","component3"); component_4.setMetaValue("peak_area", 5.0); component_4.setMetaValue("native_id","component4"); TEST_REAL_SIMILAR(absquant.calculateRatio(component_1,component_4,feature_name),5.0); TEST_REAL_SIMILAR(absquant.calculateRatio(component_3,component_4,feature_name),0.0); // feature_name == "intensity" Feature component_5, component_6, component_7, component_8; feature_name = "intensity"; component_5.setMetaValue("native_id", "component5"); component_6.setMetaValue("native_id", "component6"); component_5.setIntensity(3.0); component_6.setIntensity(4.0); TEST_REAL_SIMILAR(absquant.calculateRatio(component_5, component_6, feature_name), 0.75); TEST_REAL_SIMILAR(absquant.calculateRatio(component_6, component_5, feature_name), 1.33333333333333); component_7.setMetaValue("native_id", "component7"); TEST_REAL_SIMILAR(absquant.calculateRatio(component_5, component_7, feature_name), inf); TEST_REAL_SIMILAR(absquant.calculateRatio(component_5, component_8, feature_name), 3.0); END_SECTION START_SECTION((double calculateBias(const double & actual_concentration, const double & calculated_concentration))) AbsoluteQuantitation absquant; double actual_concentration = 5.0; double calculated_concentration = 5.0; TEST_REAL_SIMILAR(absquant.calculateBias(actual_concentration,calculated_concentration),0.0); calculated_concentration = 4.0; TEST_REAL_SIMILAR(absquant.calculateBias(actual_concentration,calculated_concentration),20.0); END_SECTION START_SECTION((double applyCalibration(const Feature & component, const Feature & IS_component, const String & feature_name, const String & transformation_model, const Param & transformation_model_params))) AbsoluteQuantitation absquant; // set-up the features Feature component, IS_component; component.setMetaValue("native_id","component"); component.setMetaValue("peak_apex_int",2.0); IS_component.setMetaValue("native_id","IS"); IS_component.setMetaValue("peak_apex_int",1.0); String feature_name = "peak_apex_int"; // set-up the model and params // y = m*x + b // x = (y - b)/m String transformation_model; Param param; // transformation_model = "TransformationModelLinear"; transformation_model = "linear"; param.setValue("slope",2.0); param.setValue("intercept",1.0); TEST_REAL_SIMILAR(absquant.applyCalibration(component, IS_component, feature_name, transformation_model, param),0.5); END_SECTION START_SECTION((void quantifyComponents(std::vector<FeatureMap>& unknowns))) AbsoluteQuantitation absquant; // set-up the unknown FeatureMap FeatureMap unknown_feature_map; // set-up the features and sub-features std::vector<Feature> unknown_feature_subordinates; Feature unknown_feature, component, IS_component; String feature_name = "peak_apex_int"; // component 1 unknown_feature.setMetaValue("PeptideRef","component_group1"); component.setMetaValue("native_id","component1"); component.setMetaValue(feature_name,2.0); IS_component.setMetaValue("native_id","IS1"); IS_component.setMetaValue(feature_name,2.0); unknown_feature_subordinates.push_back(IS_component); unknown_feature_subordinates.push_back(component); unknown_feature.setSubordinates(unknown_feature_subordinates); unknown_feature_map.push_back(unknown_feature); unknown_feature_subordinates.clear(); // component 2 unknown_feature.setMetaValue("PeptideRef","component_group2"); component.setMetaValue("native_id","component2"); component.setMetaValue(feature_name,4.0); IS_component.setMetaValue("native_id","IS2"); IS_component.setMetaValue(feature_name,4.0); unknown_feature_subordinates.push_back(IS_component); unknown_feature_subordinates.push_back(component); unknown_feature.setSubordinates(unknown_feature_subordinates); unknown_feature_map.push_back(unknown_feature); unknown_feature_subordinates.clear(); // component 3 unknown_feature.setMetaValue("PeptideRef","component_group3"); component.setMetaValue("native_id","component3"); component.setMetaValue(feature_name,6.0); IS_component.setMetaValue("native_id","IS3"); IS_component.setMetaValue(feature_name,6.0); unknown_feature_subordinates.push_back(component); // test order change unknown_feature_subordinates.push_back(IS_component); unknown_feature.setSubordinates(unknown_feature_subordinates); unknown_feature_map.push_back(unknown_feature); unknown_feature_subordinates.clear(); // // set-up the unknowns // std::vector<FeatureMap> unknowns; // unknowns.push_back(unknown_feature_map); // set-up the model and params AbsoluteQuantitationMethod aqm; String transformation_model; Param param; // transformation_model = "TransformationModelLinear"; transformation_model = "linear"; param.setValue("slope",1.0); param.setValue("intercept",0.0); aqm.setTransformationModel(transformation_model); aqm.setTransformationModelParams(param); // set-up the quant_method map std::vector<AbsoluteQuantitationMethod> quant_methods; // component_1 aqm.setComponentName("component1"); aqm.setISName("IS1"); aqm.setFeatureName(feature_name); aqm.setConcentrationUnits("uM"); quant_methods.push_back(aqm); // component_2 aqm.setComponentName("component2"); aqm.setISName("IS1"); aqm.setFeatureName(feature_name); // test IS outside component_group aqm.setConcentrationUnits("uM"); quant_methods.push_back(aqm); // component_3 aqm.setComponentName("component3"); aqm.setISName("IS3"); aqm.setFeatureName(feature_name); aqm.setConcentrationUnits("uM"); quant_methods.push_back(aqm); absquant.setQuantMethods(quant_methods); absquant.quantifyComponents(unknown_feature_map); // DEBUGGING: // for (size_t i = 0; i < unknowns.size(); ++i) // { // for (size_t j = 0; j < unknowns[i].size(); ++j) // { // for (size_t k = 0; k < unknowns[i][j].getSubordinates().size(); ++k) // { // std::cout << "component = " << unknowns[i][j].getSubordinates()[k].getMetaValue("native_id") << std::endl; // std::cout << "calculated_concentration = " << unknowns[i][j].getSubordinates()[k].getMetaValue("calculated_concentration") << std::endl; // } // } // } TEST_EQUAL(unknown_feature_map[0].getSubordinates()[0].getMetaValue("calculated_concentration"),""); TEST_STRING_EQUAL(unknown_feature_map[0].getSubordinates()[0].getMetaValue("concentration_units"),""); TEST_REAL_SIMILAR(unknown_feature_map[0].getSubordinates()[1].getMetaValue("calculated_concentration"),1.0); TEST_STRING_EQUAL(unknown_feature_map[0].getSubordinates()[1].getMetaValue("concentration_units"),"uM"); TEST_REAL_SIMILAR(unknown_feature_map[1].getSubordinates()[1].getMetaValue("calculated_concentration"),2.0); TEST_STRING_EQUAL(unknown_feature_map[1].getSubordinates()[1].getMetaValue("concentration_units"),"uM"); TEST_REAL_SIMILAR(unknown_feature_map[2].getSubordinates()[0].getMetaValue("calculated_concentration"),1.0); TEST_STRING_EQUAL(unknown_feature_map[2].getSubordinates()[0].getMetaValue("concentration_units"),"uM"); END_SECTION START_SECTION((void ( const std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params, std::vector<double> & biases, double & correlation_coefficient))) AbsoluteQuantitation absquant; // set-up the features std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations; AbsoluteQuantitationStandards::featureConcentration component_concentration; Feature component, IS_component; // point #1 component.setMetaValue("native_id","component"); component.setMetaValue("peak_apex_int",1.0); IS_component.setMetaValue("native_id","IS"); IS_component.setMetaValue("peak_apex_int",1.0); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = 2.0; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 2.0; component_concentrations.push_back(component_concentration); // point #2 component.setMetaValue("native_id","component"); component.setMetaValue("peak_apex_int",2.0); IS_component.setMetaValue("native_id","IS"); IS_component.setMetaValue("peak_apex_int",1.0); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = 4.0; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 2.0; component_concentrations.push_back(component_concentration); // point #3 component.setMetaValue("native_id","component"); component.setMetaValue("peak_apex_int",3.0); IS_component.setMetaValue("native_id","IS"); IS_component.setMetaValue("peak_apex_int",1.0); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = 6.0; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 2.0; component_concentrations.push_back(component_concentration); String feature_name = "peak_apex_int"; // set-up the model and params // y = m*x + b // x = (y - b)/m String transformation_model; Param param; // transformation_model = "TransformationModelLinear"; transformation_model = "linear"; param.setValue("slope",1.0); param.setValue("intercept",0.0); std::vector<double> biases; double correlation_coefficient; absquant.calculateBiasAndR( component_concentrations, feature_name, transformation_model, param, biases, correlation_coefficient); TEST_REAL_SIMILAR(biases[0],0.0); TEST_REAL_SIMILAR(correlation_coefficient,1.0); END_SECTION START_SECTION((Param AbsoluteQuantitation::fitCalibration( const std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params))) AbsoluteQuantitation absquant; // TEST 1: static const double arrx1[] = {-1, -2, -3, 1, 2, 3}; std::vector<double> x1 (arrx1, arrx1 + sizeof(arrx1) / sizeof(arrx1[0]) ); static const double arry1[] = {1, 1, 1, 1, 1, 1}; std::vector<double> y1 (arry1, arry1 + sizeof(arry1) / sizeof(arry1[0]) ); static const double arrz1[] = {-4, -8, -12, 4, 8, 12}; std::vector<double> z1 (arrz1, arrz1 + sizeof(arrz1) / sizeof(arrz1[0]) ); // set-up the features std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations; AbsoluteQuantitationStandards::featureConcentration component_concentration; Feature component, IS_component; for (size_t i = 0; i < x1.size(); ++i) { component.setMetaValue("native_id","ser-L.ser-L_1.Light"); component.setMetaValue("peak_apex_int",x1[i]); IS_component.setMetaValue("native_id","IS"); IS_component.setMetaValue("peak_apex_int",y1[i]); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = z1[i]; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 2.0; component_concentrations.push_back(component_concentration); } String feature_name = "peak_apex_int"; Param transformation_model_params; transformation_model_params.setValue("x_datum_min", -1e12); transformation_model_params.setValue("x_datum_max", 1e12); transformation_model_params.setValue("y_datum_min", -1e12); transformation_model_params.setValue("y_datum_max", 1e12); // String transformation_model = "TransformationModelLinear"; String transformation_model = "linear"; Param param = absquant.fitCalibration(component_concentrations, feature_name, transformation_model, transformation_model_params); TEST_REAL_SIMILAR(param.getValue("slope"),0.5); TEST_REAL_SIMILAR(param.getValue("intercept"),0.0); // TEST 2: static const double arrx2[] = {0.25,0.5,1,2,3,4,5,6}; std::vector<double> x2 (arrx2, arrx2 + sizeof(arrx2) / sizeof(arrx2[0]) ); static const double arry2[] = {1,1,1,1,1,1,1,1}; std::vector<double> y2 (arry2, arry2 + sizeof(arry2) / sizeof(arry2[0]) ); static const double arrz2[] = {0.5,1,2,4,6,8,10,12}; std::vector<double> z2 (arrz2, arrz2 + sizeof(arrz2) / sizeof(arrz2[0]) ); // set-up the features component_concentrations.clear(); for (size_t i = 0; i < x2.size(); ++i) { component.setMetaValue("native_id","ser-L.ser-L_1.Light"); component.setMetaValue("peak_apex_int",x2[i]); IS_component.setMetaValue("native_id","IS"); IS_component.setMetaValue("peak_apex_int",y2[i]); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = z2[i]; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 1.0; component_concentrations.push_back(component_concentration); } transformation_model_params.setValue("x_weight", "ln(x)"); transformation_model_params.setValue("y_weight", "ln(y)"); param = absquant.fitCalibration(component_concentrations, feature_name, transformation_model, transformation_model_params); TEST_REAL_SIMILAR(param.getValue("slope"), 1.0); TEST_REAL_SIMILAR(param.getValue("intercept"), -0.69314718); END_SECTION START_SECTION((bool optimizeCalibrationCurveIterative( std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params, Param & optimized_params))) AbsoluteQuantitation absquant; // TEST 1: ser-L std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations = make_serL_standards(); // set-up the class parameters Param absquant_params; absquant_params.setValue("min_points", 4); absquant_params.setValue("max_bias", 30.0); absquant_params.setValue("min_correlation_coefficient", 0.9); absquant_params.setValue("max_iters", 100); absquant_params.setValue("outlier_detection_method", "iter_jackknife"); absquant_params.setValue("use_chauvenet", "false"); absquant.setParameters(absquant_params); // set-up the function parameters const String feature_name = "peak_apex_int"; const String transformation_model = "linear"; Param transformation_model_params; transformation_model_params.setValue("x_weight", "ln(x)"); transformation_model_params.setValue("y_weight", "ln(y)"); transformation_model_params.setValue("slope", "1.0"); transformation_model_params.setValue("intercept", "0.0"); transformation_model_params.setValue("x_datum_min", -1e12); transformation_model_params.setValue("x_datum_max", 1e12); transformation_model_params.setValue("y_datum_min", -1e12); transformation_model_params.setValue("y_datum_max", 1e12); Param optimized_params; bool optimal_fit_found = absquant.optimizeCalibrationCurveIterative( component_concentrations, feature_name, transformation_model, transformation_model_params, optimized_params); TEST_REAL_SIMILAR(component_concentrations[0].actual_concentration, 0.04); TEST_REAL_SIMILAR(component_concentrations[8].actual_concentration, 40.0); TEST_REAL_SIMILAR(optimized_params.getValue("slope"), 0.9011392589); TEST_REAL_SIMILAR(optimized_params.getValue("intercept"), 1.870185076); TEST_EQUAL(optimal_fit_found, true); // TEST 2: amp component_concentrations = make_amp_standards(); optimal_fit_found = absquant.optimizeCalibrationCurveIterative( component_concentrations, feature_name, transformation_model, transformation_model_params, optimized_params); TEST_REAL_SIMILAR(component_concentrations[0].actual_concentration, 0.02); TEST_REAL_SIMILAR(component_concentrations[8].actual_concentration, 8.0); TEST_REAL_SIMILAR(optimized_params.getValue("slope"), 0.95799683); TEST_REAL_SIMILAR(optimized_params.getValue("intercept"), -1.047543387); TEST_EQUAL(optimal_fit_found, true); // TEST 3: atp component_concentrations = make_atp_standards(); optimal_fit_found = absquant.optimizeCalibrationCurveIterative( component_concentrations, feature_name, transformation_model, transformation_model_params, optimized_params); TEST_REAL_SIMILAR(component_concentrations[0].actual_concentration, 0.02); TEST_REAL_SIMILAR(component_concentrations[3].actual_concentration, 8.0); TEST_REAL_SIMILAR(optimized_params.getValue("slope"), 0.623040824); TEST_REAL_SIMILAR(optimized_params.getValue("intercept"), 0.36130172586); TEST_EQUAL(optimal_fit_found, true); // TEST 4: atp with too stringent of a criteria (should fail) component_concentrations = make_atp_standards(); absquant_params.setValue("min_points", 12); absquant_params.setValue("max_bias", 5.0); absquant_params.setValue("min_correlation_coefficient", 0.99); absquant_params.setValue("max_iters", 100); absquant_params.setValue("outlier_detection_method", "iter_jackknife"); absquant_params.setValue("use_chauvenet", "false"); absquant.setParameters(absquant_params); optimal_fit_found = absquant.optimizeCalibrationCurveIterative( component_concentrations, feature_name, transformation_model, transformation_model_params, optimized_params); TEST_REAL_SIMILAR(optimized_params.getValue("slope"), 0.482400123016735); TEST_REAL_SIMILAR(optimized_params.getValue("intercept"), 0.305125368008987); TEST_EQUAL(optimal_fit_found, false); END_SECTION START_SECTION((void optimizeCalibrationCurves(AbsoluteQuantitationStandards::components_to_concentrations & components_concentrations))) AbsoluteQuantitation absquant; // set-up the class parameters Param absquant_params; absquant_params.setValue("min_points", 4); absquant_params.setValue("max_bias", 30.0); absquant_params.setValue("min_correlation_coefficient", 0.9); absquant_params.setValue("max_iters", 100); absquant_params.setValue("outlier_detection_method", "iter_jackknife"); absquant_params.setValue("use_chauvenet", "false"); absquant.setParameters(absquant_params); // set up the quantitation method AbsoluteQuantitationMethod aqm; String feature_name = "peak_apex_int"; String transformation_model; Param param; transformation_model = "linear"; param.setValue("slope",1.0); param.setValue("intercept",0.0); param.setValue("x_weight", "ln(x)"); param.setValue("y_weight", "ln(y)"); param.setValue("x_datum_min", -1e12); param.setValue("x_datum_max", 1e12); param.setValue("y_datum_min", -1e12); param.setValue("y_datum_max", 1e12); aqm.setTransformationModel(transformation_model); aqm.setTransformationModelParams(param); // set-up the quant_method map std::vector<AbsoluteQuantitationMethod> quant_methods; // component_1 aqm.setComponentName("ser-L.ser-L_1.Light"); aqm.setISName("ser-L.ser-L_1.Heavy"); aqm.setFeatureName(feature_name); aqm.setConcentrationUnits("uM"); quant_methods.push_back(aqm); // component_2 aqm.setComponentName("amp.amp_1.Light"); aqm.setISName("amp.amp_1.Heavy"); aqm.setFeatureName(feature_name); // test IS outside component_group aqm.setConcentrationUnits("uM"); quant_methods.push_back(aqm); // component_3 aqm.setComponentName("atp.atp_1.Light"); aqm.setISName("atp.atp_1.Heavy"); aqm.setFeatureName(feature_name); aqm.setConcentrationUnits("uM"); quant_methods.push_back(aqm); absquant.setQuantMethods(quant_methods); // set up the standards std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>> components_concentrations; components_concentrations["ser-L.ser-L_1.Light"] = make_serL_standards(); components_concentrations["amp.amp_1.Light"] = make_amp_standards(); components_concentrations["atp.atp_1.Light"] = make_atp_standards(); absquant.optimizeCalibrationCurves(components_concentrations); std::map<String, AbsoluteQuantitationMethod> quant_methods_map = absquant.getQuantMethodsAsMap(); TEST_REAL_SIMILAR(components_concentrations["ser-L.ser-L_1.Light"][0].actual_concentration, 0.04); TEST_REAL_SIMILAR(components_concentrations["ser-L.ser-L_1.Light"][8].actual_concentration, 40.0); TEST_REAL_SIMILAR(quant_methods_map["ser-L.ser-L_1.Light"].getTransformationModelParams().getValue("slope"), 0.9011392589); TEST_REAL_SIMILAR(quant_methods_map["ser-L.ser-L_1.Light"].getTransformationModelParams().getValue("intercept"), 1.87018507); TEST_REAL_SIMILAR(quant_methods_map["ser-L.ser-L_1.Light"].getCorrelationCoefficient(), 0.999320072); TEST_EQUAL(quant_methods_map["ser-L.ser-L_1.Light"].getLLOQ(), 0.04); TEST_EQUAL(quant_methods_map["ser-L.ser-L_1.Light"].getULOQ(), 200); TEST_EQUAL(quant_methods_map["ser-L.ser-L_1.Light"].getNPoints(), 11); TEST_REAL_SIMILAR(components_concentrations["amp.amp_1.Light"][0].actual_concentration, 0.02); TEST_REAL_SIMILAR(components_concentrations["amp.amp_1.Light"][8].actual_concentration, 8.0); TEST_REAL_SIMILAR(quant_methods_map["amp.amp_1.Light"].getTransformationModelParams().getValue("slope"), 0.95799683); TEST_REAL_SIMILAR(quant_methods_map["amp.amp_1.Light"].getTransformationModelParams().getValue("intercept"), -1.047543387); TEST_REAL_SIMILAR(quant_methods_map["amp.amp_1.Light"].getCorrelationCoefficient(), 0.99916926); TEST_EQUAL(quant_methods_map["amp.amp_1.Light"].getLLOQ(), 0.02); TEST_EQUAL(quant_methods_map["amp.amp_1.Light"].getULOQ(), 40.0); TEST_EQUAL(quant_methods_map["amp.amp_1.Light"].getNPoints(), 11); TEST_REAL_SIMILAR(components_concentrations["atp.atp_1.Light"][0].actual_concentration, 0.02); TEST_REAL_SIMILAR(components_concentrations["atp.atp_1.Light"][3].actual_concentration, 8.0); TEST_REAL_SIMILAR(quant_methods_map["atp.atp_1.Light"].getTransformationModelParams().getValue("slope"), 0.623040824); TEST_REAL_SIMILAR(quant_methods_map["atp.atp_1.Light"].getTransformationModelParams().getValue("intercept"), 0.36130172586); TEST_REAL_SIMILAR(quant_methods_map["atp.atp_1.Light"].getCorrelationCoefficient(), 0.998208402); TEST_EQUAL(quant_methods_map["atp.atp_1.Light"].getLLOQ(), 0.02); TEST_EQUAL(quant_methods_map["atp.atp_1.Light"].getULOQ(), 40.0); TEST_EQUAL(quant_methods_map["atp.atp_1.Light"].getNPoints(), 6); components_concentrations.clear(); components_concentrations["ser-L.ser-L_1.Light"] = make_serL_standards(); absquant_params.setValue("min_points", 20); // so that an optimal calibration curve is not found, and the sorting is not saved absquant.setParameters(absquant_params); absquant.optimizeCalibrationCurves(components_concentrations); quant_methods_map = absquant.getQuantMethodsAsMap(); TEST_REAL_SIMILAR(components_concentrations["ser-L.ser-L_1.Light"][0].actual_concentration, 0.01); TEST_REAL_SIMILAR(components_concentrations["ser-L.ser-L_1.Light"][8].actual_concentration, 4.0); TEST_REAL_SIMILAR(quant_methods_map["ser-L.ser-L_1.Light"].getTransformationModelParams().getValue("slope"), 0.9011392589); // previous supplied TEST_REAL_SIMILAR(quant_methods_map["ser-L.ser-L_1.Light"].getTransformationModelParams().getValue("intercept"), 1.87018507); // previous supplied TEST_REAL_SIMILAR(quant_methods_map["ser-L.ser-L_1.Light"].getCorrelationCoefficient(), 0.0); TEST_EQUAL(quant_methods_map["ser-L.ser-L_1.Light"].getLLOQ(), 0.0); TEST_EQUAL(quant_methods_map["ser-L.ser-L_1.Light"].getULOQ(), 0.0); TEST_EQUAL(quant_methods_map["ser-L.ser-L_1.Light"].getNPoints(), 0.0); END_SECTION START_SECTION(void optimizeSingleCalibrationCurve( const String& component_name, std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations )) // set up the quantitation method Param param; param.setValue("slope",1.0); param.setValue("intercept",0.0); param.setValue("x_weight", "ln(x)"); param.setValue("y_weight", "ln(y)"); param.setValue("x_datum_min", -1e12); param.setValue("x_datum_max", 1e12); param.setValue("y_datum_min", -1e12); param.setValue("y_datum_max", 1e12); AbsoluteQuantitationMethod aqm; aqm.setTransformationModel("linear"); aqm.setTransformationModelParams(param); // set-up the quant_method map std::vector<AbsoluteQuantitationMethod> quant_methods; const String feature_name = "peak_apex_int"; // component_1 aqm.setComponentName("ser-L.ser-L_1.Light"); aqm.setISName("ser-L.ser-L_1.Heavy"); aqm.setFeatureName(feature_name); aqm.setConcentrationUnits("uM"); quant_methods.push_back(aqm); // component_2 aqm.setComponentName("amp.amp_1.Light"); aqm.setISName("amp.amp_1.Heavy"); aqm.setFeatureName(feature_name); // test IS outside component_group aqm.setConcentrationUnits("uM"); quant_methods.push_back(aqm); // component_3 aqm.setComponentName("atp.atp_1.Light"); aqm.setISName("atp.atp_1.Heavy"); aqm.setFeatureName(feature_name); aqm.setConcentrationUnits("uM"); quant_methods.push_back(aqm); AbsoluteQuantitation absquant; // set-up the class parameters Param absquant_params; absquant_params.setValue("min_points", 4); absquant_params.setValue("max_bias", 30.0); absquant_params.setValue("min_correlation_coefficient", 0.9); absquant_params.setValue("max_iters", 100); absquant_params.setValue("outlier_detection_method", "iter_jackknife"); absquant_params.setValue("use_chauvenet", "false"); absquant.setParameters(absquant_params); absquant.setQuantMethods(quant_methods); // set up the standards std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>> components_concentrations; components_concentrations["ser-L.ser-L_1.Light"] = make_serL_standards(); components_concentrations["amp.amp_1.Light"] = make_amp_standards(); components_concentrations["atp.atp_1.Light"] = make_atp_standards(); absquant.optimizeSingleCalibrationCurve("ser-L.ser-L_1.Light", components_concentrations.at("ser-L.ser-L_1.Light")); absquant.optimizeSingleCalibrationCurve("amp.amp_1.Light", components_concentrations.at("amp.amp_1.Light")); absquant.optimizeSingleCalibrationCurve("atp.atp_1.Light", components_concentrations.at("atp.atp_1.Light")); std::map<String, AbsoluteQuantitationMethod> quant_methods_map = absquant.getQuantMethodsAsMap(); TEST_REAL_SIMILAR(components_concentrations["ser-L.ser-L_1.Light"][0].actual_concentration, 0.04); TEST_REAL_SIMILAR(components_concentrations["ser-L.ser-L_1.Light"][8].actual_concentration, 40.0); TEST_REAL_SIMILAR(quant_methods_map["ser-L.ser-L_1.Light"].getTransformationModelParams().getValue("slope"), 0.9011392589); TEST_REAL_SIMILAR(quant_methods_map["ser-L.ser-L_1.Light"].getTransformationModelParams().getValue("intercept"), 1.87018507); TEST_REAL_SIMILAR(quant_methods_map["ser-L.ser-L_1.Light"].getCorrelationCoefficient(), 0.999320072); TEST_EQUAL(quant_methods_map["ser-L.ser-L_1.Light"].getLLOQ(), 0.04); TEST_EQUAL(quant_methods_map["ser-L.ser-L_1.Light"].getULOQ(), 200); TEST_EQUAL(quant_methods_map["ser-L.ser-L_1.Light"].getNPoints(), 11); TEST_REAL_SIMILAR(components_concentrations["amp.amp_1.Light"][0].actual_concentration, 0.02); TEST_REAL_SIMILAR(components_concentrations["amp.amp_1.Light"][8].actual_concentration, 8.0); TEST_REAL_SIMILAR(components_concentrations["amp.amp_1.Light"][0].actual_concentration, 0.02); TEST_REAL_SIMILAR(components_concentrations["amp.amp_1.Light"][8].actual_concentration, 8.0); TEST_REAL_SIMILAR(quant_methods_map["amp.amp_1.Light"].getTransformationModelParams().getValue("slope"), 0.95799683); TEST_REAL_SIMILAR(quant_methods_map["amp.amp_1.Light"].getTransformationModelParams().getValue("intercept"), -1.047543387); TEST_REAL_SIMILAR(quant_methods_map["amp.amp_1.Light"].getCorrelationCoefficient(), 0.99916926); TEST_EQUAL(quant_methods_map["amp.amp_1.Light"].getLLOQ(), 0.02); TEST_EQUAL(quant_methods_map["amp.amp_1.Light"].getULOQ(), 40.0); TEST_EQUAL(quant_methods_map["amp.amp_1.Light"].getNPoints(), 11); TEST_REAL_SIMILAR(components_concentrations["atp.atp_1.Light"][0].actual_concentration, 0.02); TEST_REAL_SIMILAR(components_concentrations["atp.atp_1.Light"][3].actual_concentration, 8.0); TEST_REAL_SIMILAR(components_concentrations["atp.atp_1.Light"][0].actual_concentration, 0.02); TEST_REAL_SIMILAR(components_concentrations["atp.atp_1.Light"][3].actual_concentration, 8.0); TEST_REAL_SIMILAR(quant_methods_map["atp.atp_1.Light"].getTransformationModelParams().getValue("slope"), 0.623040824); TEST_REAL_SIMILAR(quant_methods_map["atp.atp_1.Light"].getTransformationModelParams().getValue("intercept"), 0.36130172586); TEST_REAL_SIMILAR(quant_methods_map["atp.atp_1.Light"].getCorrelationCoefficient(), 0.998208402); TEST_EQUAL(quant_methods_map["atp.atp_1.Light"].getLLOQ(), 0.02); TEST_EQUAL(quant_methods_map["atp.atp_1.Light"].getULOQ(), 40.0); TEST_EQUAL(quant_methods_map["atp.atp_1.Light"].getNPoints(), 6); END_SECTION ///////////////////////////// /* Protected Members **/ ///////////////////////////// START_SECTION((std::vector<AbsoluteQuantitationStandards::featureConcentration> extractComponents_( const std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations, const std::vector<size_t>& component_concentrations_indices))) AbsoluteQuantitation_test absquant; // make the components_concentrations static const double arrx1[] = { 1.1, 2.0, 3.3, 3.9, 4.9, 6.2 }; std::vector<double> x1 (arrx1, arrx1 + sizeof(arrx1) / sizeof(arrx1[0]) ); static const double arry1[] = { 0.9, 1.9, 3.0, 3.7, 5.2, 6.1 }; std::vector<double> y1 (arry1, arry1 + sizeof(arry1) / sizeof(arry1[0]) ); // set-up the features std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations; AbsoluteQuantitationStandards::featureConcentration component_concentration; Feature component, IS_component; for (size_t i = 0; i < x1.size(); ++i) { component.setMetaValue("native_id","component" + std::to_string(i)); component.setMetaValue("peak_apex_int",y1[i]); IS_component.setMetaValue("native_id","IS" + std::to_string(i)); IS_component.setMetaValue("peak_apex_int",1.0); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = x1[i]; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 1.0; component_concentrations.push_back(component_concentration); } // make the indices to extract static const size_t arrx2[] = { 0, 1, 3 }; std::vector<size_t> component_concentrations_indices(arrx2, arrx2 + sizeof(arrx2) / sizeof(arrx2[0]) ); std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations_sub = absquant.extractComponents_( component_concentrations, component_concentrations_indices); TEST_EQUAL(component_concentrations_sub[0].feature.getMetaValue("native_id"), "component0"); TEST_REAL_SIMILAR(component_concentrations_sub[0].actual_concentration, 1.1); TEST_EQUAL(component_concentrations_sub[1].feature.getMetaValue("native_id"), "component1"); TEST_REAL_SIMILAR(component_concentrations_sub[1].actual_concentration, 2.0); TEST_EQUAL(component_concentrations_sub[2].feature.getMetaValue("native_id"), "component3"); TEST_REAL_SIMILAR(component_concentrations_sub[2].actual_concentration, 3.9); END_SECTION START_SECTION((int jackknifeOutlierCandidate_( const std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params))) AbsoluteQuantitation_test absquant; static const double arrx1[] = { 1.1, 2.0,3.3,3.9,4.9,6.2 }; std::vector<double> x1 (arrx1, arrx1 + sizeof(arrx1) / sizeof(arrx1[0]) ); static const double arry1[] = { 0.9, 1.9,3.0,3.7,5.2,6.1 }; std::vector<double> y1 (arry1, arry1 + sizeof(arry1) / sizeof(arry1[0]) ); // set-up the features std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations; AbsoluteQuantitationStandards::featureConcentration component_concentration; Feature component, IS_component; for (size_t i = 0; i < x1.size(); ++i) { component.setMetaValue("native_id","component"); component.setMetaValue("peak_apex_int",y1[i]); IS_component.setMetaValue("native_id","IS"); IS_component.setMetaValue("peak_apex_int",1.0); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = x1[i]; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 1.0; component_concentrations.push_back(component_concentration); } String feature_name = "peak_apex_int"; // set-up the model and params // y = m*x + b // x = (y - b)/m Param transformation_model_params; // String transformation_model = "TransformationModelLinear"; String transformation_model = "linear"; int c1 = absquant.jackknifeOutlierCandidate_( component_concentrations, feature_name, transformation_model, transformation_model_params); TEST_EQUAL(c1,4); static const double arrx2[] = { 1,2,3,4,5,6 }; std::vector<double> x2 (arrx2, arrx2 + sizeof(arrx2) / sizeof(arrx2[0]) ); static const double arry2[] = { 1,2,3,4,5,6}; std::vector<double> y2 (arry2, arry2 + sizeof(arry2) / sizeof(arry2[0]) ); component_concentrations.clear(); for (size_t i = 0; i < x2.size(); ++i) { component.setMetaValue("native_id","component"); component.setMetaValue("peak_apex_int",y2[i]); IS_component.setMetaValue("native_id","IS"); IS_component.setMetaValue("peak_apex_int",1.0); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = x2[i]; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 1.0; component_concentrations.push_back(component_concentration); } int c2 = absquant.jackknifeOutlierCandidate_( component_concentrations, feature_name, transformation_model, transformation_model_params); TEST_EQUAL(c2,0); END_SECTION START_SECTION((int residualOutlierCandidate_( const std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params))) AbsoluteQuantitation_test absquant; static const double arrx1[] = { 1.1, 2.0,3.3,3.9,4.9,6.2 }; std::vector<double> x1 (arrx1, arrx1 + sizeof(arrx1) / sizeof(arrx1[0]) ); static const double arry1[] = { 0.9, 1.9,3.0,3.7,5.2,6.1 }; std::vector<double> y1 (arry1, arry1 + sizeof(arry1) / sizeof(arry1[0]) ); // set-up the features std::vector<AbsoluteQuantitationStandards::featureConcentration> component_concentrations; AbsoluteQuantitationStandards::featureConcentration component_concentration; Feature component, IS_component; for (size_t i = 0; i < x1.size(); ++i) { component.setMetaValue("native_id","component"); component.setMetaValue("peak_apex_int",y1[i]); IS_component.setMetaValue("native_id","IS"); IS_component.setMetaValue("peak_apex_int",1.0); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = x1[i]; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 1.0; component_concentrations.push_back(component_concentration); } String feature_name = "peak_apex_int"; // set-up the model and params // y = m*x + b // x = (y - b)/m Param transformation_model_params; // String transformation_model = "TransformationModelLinear"; String transformation_model = "linear"; int c1 = absquant.residualOutlierCandidate_( component_concentrations, feature_name, transformation_model, transformation_model_params); TEST_EQUAL(c1,4); static const double arrx2[] = { 1,2,3,4,5,6 }; std::vector<double> x2 (arrx2, arrx2 + sizeof(arrx2) / sizeof(arrx2[0]) ); static const double arry2[] = { 1,2,3,4,5,6}; std::vector<double> y2 (arry2, arry2 + sizeof(arry2) / sizeof(arry2[0]) ); component_concentrations.clear(); for (size_t i = 0; i < x2.size(); ++i) { component.setMetaValue("native_id","component"); component.setMetaValue("peak_apex_int",y2[i]); IS_component.setMetaValue("native_id","IS"); IS_component.setMetaValue("peak_apex_int",1.0); component_concentration.feature = component; component_concentration.IS_feature = IS_component; component_concentration.actual_concentration = x2[i]; component_concentration.IS_actual_concentration = 1.0; component_concentration.dilution_factor = 1.0; component_concentrations.push_back(component_concentration); } int c2 = absquant.residualOutlierCandidate_( component_concentrations, feature_name, transformation_model, transformation_model_params); TEST_EQUAL(c2,0); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SqrtScaler_test.cpp
.cpp
2,579
94
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Authors: Volker Mosthaf $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/PROCESSING/SCALING/SqrtScaler.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/DTAFile.h> #include <cmath> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(SqrtScaler, "$Id$") ///////////////////////////////////////////////////////////// SqrtScaler* e_ptr = nullptr; SqrtScaler* e_nullPointer = nullptr; START_SECTION((SqrtScaler())) e_ptr = new SqrtScaler; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION((~SqrtScaler())) delete e_ptr; END_SECTION e_ptr = new SqrtScaler(); START_SECTION((SqrtScaler(const SqrtScaler& source))) SqrtScaler copy(*e_ptr); TEST_EQUAL(*e_ptr == copy, true) END_SECTION START_SECTION((SqrtScaler& operator=(const SqrtScaler& source))) SqrtScaler copy; copy = *e_ptr; TEST_EQUAL(*e_ptr == copy, true) 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_REAL_SIMILAR((spec.begin() + 40)->getIntensity(), 37.5) e_ptr->filterSpectrum(spec); TEST_REAL_SIMILAR((spec.begin() + 40)->getIntensity(), sqrt(37.5)) END_SECTION START_SECTION((void filterPeakMap(PeakMap& exp))) DTAFile dta_file; PeakSpectrum spec; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec); PeakMap pm; pm.addSpectrum(spec); TEST_REAL_SIMILAR((pm.begin()->begin() + 40)->getIntensity(), 37.5) e_ptr->filterPeakMap(pm); TEST_REAL_SIMILAR((pm.begin()->begin() + 40)->getIntensity(), sqrt(37.5)) END_SECTION START_SECTION((void filterPeakSpectrum(PeakSpectrum& spectrum))) DTAFile dta_file; PeakSpectrum spec; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec); TEST_REAL_SIMILAR((spec.begin() + 40)->getIntensity(), 37.5) e_ptr->filterPeakSpectrum(spec); TEST_REAL_SIMILAR((spec.begin() + 40)->getIntensity(), sqrt(37.5)) END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MassAnalyzer_test.cpp
.cpp
18,087
547
// 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/MassAnalyzer.h> /////////////////////////// #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; START_TEST(MassAnalyzer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MassAnalyzer* ptr = nullptr; MassAnalyzer* nullPointer = nullptr; START_SECTION((MassAnalyzer())) ptr = new MassAnalyzer(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~MassAnalyzer())) delete ptr; END_SECTION START_SECTION((Int getOrder() const)) MassAnalyzer tmp; TEST_EQUAL(tmp.getOrder(),0) END_SECTION START_SECTION((void setOrder(Int order))) MassAnalyzer tmp; tmp.setOrder(4711); TEST_EQUAL(tmp.getOrder(),4711) END_SECTION START_SECTION((AnalyzerType getType() const)) MassAnalyzer tmp; TEST_EQUAL(tmp.getType(),MassAnalyzer::AnalyzerType::ANALYZERNULL); END_SECTION START_SECTION((ReflectronState getReflectronState() const)) MassAnalyzer tmp; TEST_EQUAL(tmp.getReflectronState(),MassAnalyzer::ReflectronState::REFLSTATENULL); END_SECTION START_SECTION((ResolutionMethod getResolutionMethod() const)) MassAnalyzer tmp; TEST_EQUAL(tmp.getResolutionMethod(),MassAnalyzer::ResolutionMethod::RESMETHNULL); END_SECTION START_SECTION((ResolutionType getResolutionType() const)) MassAnalyzer tmp; TEST_EQUAL(tmp.getResolutionType(),MassAnalyzer::ResolutionType::RESTYPENULL); END_SECTION START_SECTION((ScanDirection getScanDirection() const)) MassAnalyzer tmp; TEST_EQUAL(tmp.getScanDirection(),MassAnalyzer::ScanDirection::SCANDIRNULL); END_SECTION START_SECTION((ScanLaw getScanLaw() const)) MassAnalyzer tmp; TEST_EQUAL(tmp.getScanLaw(),MassAnalyzer::ScanLaw::SCANLAWNULL); END_SECTION START_SECTION((Int getFinalMSExponent() const)) MassAnalyzer tmp; TEST_EQUAL(tmp.getFinalMSExponent(),0); END_SECTION START_SECTION((double getAccuracy() const )) MassAnalyzer tmp; TEST_REAL_SIMILAR(tmp.getAccuracy(),0.0); END_SECTION START_SECTION((double getIsolationWidth() const )) MassAnalyzer tmp; TEST_REAL_SIMILAR(tmp.getIsolationWidth(),0.0); END_SECTION START_SECTION((double getMagneticFieldStrength() const )) MassAnalyzer tmp; TEST_REAL_SIMILAR(tmp.getMagneticFieldStrength(),0.0); END_SECTION START_SECTION((double getResolution() const )) MassAnalyzer tmp; TEST_REAL_SIMILAR(tmp.getResolution(),0.0); END_SECTION START_SECTION((double getScanRate() const )) MassAnalyzer tmp; TEST_REAL_SIMILAR(tmp.getScanRate(),0.0); END_SECTION START_SECTION((double getScanTime() const )) MassAnalyzer tmp; TEST_REAL_SIMILAR(tmp.getScanTime(),0.0); END_SECTION START_SECTION((double getTOFTotalPathLength() const )) MassAnalyzer tmp; TEST_REAL_SIMILAR(tmp.getTOFTotalPathLength(),0.0); END_SECTION START_SECTION((void setType(AnalyzerType type))) MassAnalyzer tmp; tmp.setType(MassAnalyzer::AnalyzerType::QUADRUPOLE); TEST_EQUAL(tmp.getType(),MassAnalyzer::AnalyzerType::QUADRUPOLE); END_SECTION START_SECTION((void setAccuracy(double accuracy))) MassAnalyzer tmp; tmp.setAccuracy(47.11); TEST_REAL_SIMILAR(tmp.getAccuracy(),47.11); END_SECTION START_SECTION((void setFinalMSExponent(Int final_MS_exponent))) MassAnalyzer tmp; tmp.setFinalMSExponent(47); TEST_EQUAL(tmp.getFinalMSExponent(),47); END_SECTION START_SECTION((void setIsolationWidth(double isolation_width))) MassAnalyzer tmp; tmp.setIsolationWidth(47.11); TEST_REAL_SIMILAR(tmp.getIsolationWidth(),47.11); END_SECTION START_SECTION((void setMagneticFieldStrength(double magnetic_field_strength))) MassAnalyzer tmp; tmp.setMagneticFieldStrength(47.11); TEST_REAL_SIMILAR(tmp.getMagneticFieldStrength(),47.11); END_SECTION START_SECTION((void setReflectronState(ReflectronState reflecton_state))) MassAnalyzer tmp; tmp.setReflectronState(MassAnalyzer::ReflectronState::ON); TEST_EQUAL(tmp.getReflectronState(),MassAnalyzer::ReflectronState::ON); END_SECTION START_SECTION((void setResolution(double resolution))) MassAnalyzer tmp; tmp.setResolution(47.11); TEST_REAL_SIMILAR(tmp.getResolution(),47.11); END_SECTION START_SECTION((void setResolutionMethod(ResolutionMethod resolution_method))) MassAnalyzer tmp; tmp.setResolutionMethod(MassAnalyzer::ResolutionMethod::FWHM); TEST_EQUAL(tmp.getResolutionMethod(),MassAnalyzer::ResolutionMethod::FWHM); END_SECTION START_SECTION((void setResolutionType(ResolutionType resolution_type))) MassAnalyzer tmp; tmp.setResolutionType(MassAnalyzer::ResolutionType::CONSTANT); TEST_EQUAL(tmp.getResolutionType(),MassAnalyzer::ResolutionType::CONSTANT); END_SECTION START_SECTION((void setScanDirection(ScanDirection scan_direction))) MassAnalyzer tmp; tmp.setScanDirection(MassAnalyzer::ScanDirection::UP); TEST_EQUAL(tmp.getScanDirection(),MassAnalyzer::ScanDirection::UP); END_SECTION START_SECTION((void setScanLaw(ScanLaw scan_law))) MassAnalyzer tmp; tmp.setScanLaw(MassAnalyzer::ScanLaw::LINEAR); TEST_EQUAL(tmp.getScanLaw(),MassAnalyzer::ScanLaw::LINEAR); END_SECTION START_SECTION((void setScanRate(double scan_rate))) MassAnalyzer tmp; tmp.setScanRate(47.11); TEST_REAL_SIMILAR(tmp.getScanRate(),47.11); END_SECTION START_SECTION((void setScanTime(double scan_time))) MassAnalyzer tmp; tmp.setScanTime(47.11); TEST_REAL_SIMILAR(tmp.getScanTime(),47.11); END_SECTION START_SECTION((void setTOFTotalPathLength(double TOF_total_path_length))) MassAnalyzer tmp; tmp.setTOFTotalPathLength(47.11); TEST_REAL_SIMILAR(tmp.getTOFTotalPathLength(),47.11); END_SECTION START_SECTION((MassAnalyzer(const MassAnalyzer& source))) MassAnalyzer tmp; tmp.setType(MassAnalyzer::AnalyzerType::QUADRUPOLE); tmp.setAccuracy(47.11); tmp.setFinalMSExponent(47); tmp.setIsolationWidth(47.12); tmp.setMagneticFieldStrength(47.13); tmp.setReflectronState(MassAnalyzer::ReflectronState::ON); tmp.setResolution(47.14); tmp.setResolutionMethod(MassAnalyzer::ResolutionMethod::FWHM); tmp.setResolutionType(MassAnalyzer::ResolutionType::CONSTANT); tmp.setScanDirection(MassAnalyzer::ScanDirection::UP); tmp.setScanLaw(MassAnalyzer::ScanLaw::LINEAR); tmp.setScanRate(47.15); tmp.setScanTime(47.16); tmp.setTOFTotalPathLength(47.17); tmp.setMetaValue("label",String("label")); tmp.setOrder(45); MassAnalyzer tmp2(tmp); TEST_EQUAL(tmp.getType(),MassAnalyzer::AnalyzerType::QUADRUPOLE); TEST_REAL_SIMILAR(tmp.getAccuracy(),47.11); TEST_EQUAL(tmp.getFinalMSExponent(),47); TEST_REAL_SIMILAR(tmp.getIsolationWidth(),47.12); TEST_REAL_SIMILAR(tmp.getMagneticFieldStrength(),47.13); TEST_EQUAL(tmp.getReflectronState(),MassAnalyzer::ReflectronState::ON); TEST_REAL_SIMILAR(tmp.getResolution(),47.14); TEST_EQUAL(tmp.getResolutionMethod(),MassAnalyzer::ResolutionMethod::FWHM); TEST_EQUAL(tmp.getResolutionType(),MassAnalyzer::ResolutionType::CONSTANT); TEST_EQUAL(tmp.getScanDirection(),MassAnalyzer::ScanDirection::UP); TEST_EQUAL(tmp.getScanLaw(),MassAnalyzer::ScanLaw::LINEAR); TEST_REAL_SIMILAR(tmp.getScanRate(),47.15); TEST_REAL_SIMILAR(tmp.getScanTime(),47.16); TEST_REAL_SIMILAR(tmp.getTOFTotalPathLength(),47.17); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_EQUAL(tmp2.getOrder(),45) END_SECTION START_SECTION((MassAnalyzer& operator= (const MassAnalyzer& source))) MassAnalyzer tmp; tmp.setType(MassAnalyzer::AnalyzerType::QUADRUPOLE); tmp.setAccuracy(47.11); tmp.setFinalMSExponent(47); tmp.setIsolationWidth(47.12); tmp.setMagneticFieldStrength(47.13); tmp.setReflectronState(MassAnalyzer::ReflectronState::ON); tmp.setResolution(47.14); tmp.setResolutionMethod(MassAnalyzer::ResolutionMethod::FWHM); tmp.setResolutionType(MassAnalyzer::ResolutionType::CONSTANT); tmp.setScanDirection(MassAnalyzer::ScanDirection::UP); tmp.setScanLaw(MassAnalyzer::ScanLaw::LINEAR); tmp.setScanRate(47.15); tmp.setScanTime(47.16); tmp.setTOFTotalPathLength(47.17); tmp.setMetaValue("label",String("label")); tmp.setOrder(45); MassAnalyzer tmp2; tmp2 = tmp; TEST_EQUAL(tmp2.getType(),MassAnalyzer::AnalyzerType::QUADRUPOLE); TEST_REAL_SIMILAR(tmp2.getAccuracy(),47.11); TEST_EQUAL(tmp2.getFinalMSExponent(),47); TEST_REAL_SIMILAR(tmp2.getIsolationWidth(),47.12); TEST_REAL_SIMILAR(tmp2.getMagneticFieldStrength(),47.13); TEST_EQUAL(tmp2.getReflectronState(),MassAnalyzer::ReflectronState::ON); TEST_REAL_SIMILAR(tmp2.getResolution(),47.14); TEST_EQUAL(tmp2.getResolutionMethod(),MassAnalyzer::ResolutionMethod::FWHM); TEST_EQUAL(tmp2.getResolutionType(),MassAnalyzer::ResolutionType::CONSTANT); TEST_EQUAL(tmp2.getScanDirection(),MassAnalyzer::ScanDirection::UP); TEST_EQUAL(tmp2.getScanLaw(),MassAnalyzer::ScanLaw::LINEAR); TEST_REAL_SIMILAR(tmp2.getScanRate(),47.15); TEST_REAL_SIMILAR(tmp2.getScanTime(),47.16); TEST_REAL_SIMILAR(tmp2.getTOFTotalPathLength(),47.17); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_EQUAL(tmp2.getOrder(),45) tmp2 = MassAnalyzer(); TEST_EQUAL(tmp2.getType(),MassAnalyzer::AnalyzerType::ANALYZERNULL); TEST_REAL_SIMILAR(tmp2.getAccuracy(),0.0); TEST_EQUAL(tmp2.getFinalMSExponent(),0); TEST_REAL_SIMILAR(tmp2.getIsolationWidth(),0.0); TEST_REAL_SIMILAR(tmp2.getMagneticFieldStrength(),0.0); TEST_EQUAL(tmp2.getReflectronState(),MassAnalyzer::ReflectronState::REFLSTATENULL); TEST_REAL_SIMILAR(tmp2.getResolution(),0.0); TEST_EQUAL(tmp2.getResolutionMethod(),MassAnalyzer::ResolutionMethod::RESMETHNULL); TEST_EQUAL(tmp2.getResolutionType(),MassAnalyzer::ResolutionType::RESTYPENULL); TEST_EQUAL(tmp2.getScanDirection(),MassAnalyzer::ScanDirection::SCANDIRNULL); TEST_EQUAL(tmp2.getScanLaw(),MassAnalyzer::ScanLaw::SCANLAWNULL); TEST_REAL_SIMILAR(tmp2.getScanRate(),0.0); TEST_REAL_SIMILAR(tmp2.getScanTime(),0.0); TEST_REAL_SIMILAR(tmp2.getTOFTotalPathLength(),0.0); TEST_EQUAL(tmp2.getMetaValue("label").isEmpty(), true); TEST_EQUAL(tmp2.getOrder(),0) END_SECTION START_SECTION((bool operator== (const MassAnalyzer& rhs) const)) MassAnalyzer edit, empty; TEST_EQUAL(edit==empty,true); edit=empty; edit.setType(MassAnalyzer::AnalyzerType::QUADRUPOLE); TEST_EQUAL(edit==empty,false); edit=empty; edit.setAccuracy(47.11); TEST_EQUAL(edit==empty,false); edit=empty; edit.setFinalMSExponent(47); TEST_EQUAL(edit==empty,false); edit=empty; edit.setIsolationWidth(47.12); TEST_EQUAL(edit==empty,false); edit=empty; edit.setMagneticFieldStrength(47.13); TEST_EQUAL(edit==empty,false); edit=empty; edit.setReflectronState(MassAnalyzer::ReflectronState::ON); TEST_EQUAL(edit==empty,false); edit=empty; edit.setResolution(47.14); TEST_EQUAL(edit==empty,false); edit=empty; edit.setResolutionMethod(MassAnalyzer::ResolutionMethod::FWHM); TEST_EQUAL(edit==empty,false); edit=empty; edit.setResolutionType(MassAnalyzer::ResolutionType::CONSTANT); TEST_EQUAL(edit==empty,false); edit=empty; edit.setScanDirection(MassAnalyzer::ScanDirection::UP); TEST_EQUAL(edit==empty,false); edit=empty; edit.setScanLaw(MassAnalyzer::ScanLaw::LINEAR); TEST_EQUAL(edit==empty,false); edit=empty; edit.setScanRate(47.15); TEST_EQUAL(edit==empty,false); edit=empty; edit.setScanTime(47.16); TEST_EQUAL(edit==empty,false); edit=empty; edit.setTOFTotalPathLength(47.17); TEST_EQUAL(edit==empty,false); edit = empty; edit.setOrder(45); TEST_EQUAL(edit==empty,false); END_SECTION START_SECTION((bool operator!= (const MassAnalyzer& rhs) const)) MassAnalyzer edit, empty; TEST_EQUAL(edit!=empty,false); edit=empty; edit.setType(MassAnalyzer::AnalyzerType::QUADRUPOLE); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setAccuracy(47.11); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setFinalMSExponent(47); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setIsolationWidth(47.12); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setMagneticFieldStrength(47.13); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setReflectronState(MassAnalyzer::ReflectronState::ON); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setResolution(47.14); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setResolutionMethod(MassAnalyzer::ResolutionMethod::FWHM); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setResolutionType(MassAnalyzer::ResolutionType::CONSTANT); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setScanDirection(MassAnalyzer::ScanDirection::UP); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setScanLaw(MassAnalyzer::ScanLaw::LINEAR); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setScanRate(47.15); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setScanTime(47.16); TEST_EQUAL(edit!=empty,true); edit=empty; edit.setTOFTotalPathLength(47.17); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setOrder(45); TEST_EQUAL(edit!=empty,true); END_SECTION START_SECTION((static StringList getAllNamesOfAnalyzerType())) StringList names = MassAnalyzer::getAllNamesOfAnalyzerType(); TEST_EQUAL(names.size(), static_cast<size_t>(MassAnalyzer::AnalyzerType::SIZE_OF_ANALYZERTYPE)); TEST_EQUAL(names[static_cast<size_t>(MassAnalyzer::AnalyzerType::QUADRUPOLE)], "Quadrupole"); TEST_EQUAL(names[static_cast<size_t>(MassAnalyzer::AnalyzerType::ORBITRAP)], "Orbitrap"); END_SECTION START_SECTION((static StringList getAllNamesOfResolutionMethod())) StringList names = MassAnalyzer::getAllNamesOfResolutionMethod(); TEST_EQUAL(names.size(), static_cast<size_t>(MassAnalyzer::ResolutionMethod::SIZE_OF_RESOLUTIONMETHOD)); TEST_EQUAL(names[static_cast<size_t>(MassAnalyzer::ResolutionMethod::FWHM)], "Full width at half max"); END_SECTION START_SECTION((static StringList getAllNamesOfResolutionType())) StringList names = MassAnalyzer::getAllNamesOfResolutionType(); TEST_EQUAL(names.size(), static_cast<size_t>(MassAnalyzer::ResolutionType::SIZE_OF_RESOLUTIONTYPE)); TEST_EQUAL(names[static_cast<size_t>(MassAnalyzer::ResolutionType::CONSTANT)], "Constant"); END_SECTION START_SECTION((static StringList getAllNamesOfScanDirection())) StringList names = MassAnalyzer::getAllNamesOfScanDirection(); TEST_EQUAL(names.size(), static_cast<size_t>(MassAnalyzer::ScanDirection::SIZE_OF_SCANDIRECTION)); TEST_EQUAL(names[static_cast<size_t>(MassAnalyzer::ScanDirection::UP)], "Up"); END_SECTION START_SECTION((static StringList getAllNamesOfScanLaw())) StringList names = MassAnalyzer::getAllNamesOfScanLaw(); TEST_EQUAL(names.size(), static_cast<size_t>(MassAnalyzer::ScanLaw::SIZE_OF_SCANLAW)); TEST_EQUAL(names[static_cast<size_t>(MassAnalyzer::ScanLaw::LINEAR)], "Linar"); END_SECTION START_SECTION((static StringList getAllNamesOfReflectronState())) StringList names = MassAnalyzer::getAllNamesOfReflectronState(); TEST_EQUAL(names.size(), static_cast<size_t>(MassAnalyzer::ReflectronState::SIZE_OF_REFLECTRONSTATE)); TEST_EQUAL(names[static_cast<size_t>(MassAnalyzer::ReflectronState::ON)], "On"); END_SECTION START_SECTION(([EXTRA] std::hash<MassAnalyzer>)) { // Test that equal objects have equal hashes MassAnalyzer ma1, ma2; std::hash<MassAnalyzer> hasher; // Default constructed objects should have equal hashes TEST_EQUAL(hasher(ma1), hasher(ma2)) // Set all fields to the same values ma1.setType(MassAnalyzer::AnalyzerType::QUADRUPOLE); ma1.setResolutionMethod(MassAnalyzer::ResolutionMethod::FWHM); ma1.setResolutionType(MassAnalyzer::ResolutionType::CONSTANT); ma1.setScanDirection(MassAnalyzer::ScanDirection::UP); ma1.setScanLaw(MassAnalyzer::ScanLaw::LINEAR); ma1.setReflectronState(MassAnalyzer::ReflectronState::ON); ma1.setResolution(47.14); ma1.setAccuracy(47.11); ma1.setScanRate(47.15); ma1.setScanTime(47.16); ma1.setTOFTotalPathLength(47.17); ma1.setIsolationWidth(47.12); ma1.setMagneticFieldStrength(47.13); ma1.setFinalMSExponent(47); ma1.setOrder(45); ma2.setType(MassAnalyzer::AnalyzerType::QUADRUPOLE); ma2.setResolutionMethod(MassAnalyzer::ResolutionMethod::FWHM); ma2.setResolutionType(MassAnalyzer::ResolutionType::CONSTANT); ma2.setScanDirection(MassAnalyzer::ScanDirection::UP); ma2.setScanLaw(MassAnalyzer::ScanLaw::LINEAR); ma2.setReflectronState(MassAnalyzer::ReflectronState::ON); ma2.setResolution(47.14); ma2.setAccuracy(47.11); ma2.setScanRate(47.15); ma2.setScanTime(47.16); ma2.setTOFTotalPathLength(47.17); ma2.setIsolationWidth(47.12); ma2.setMagneticFieldStrength(47.13); ma2.setFinalMSExponent(47); ma2.setOrder(45); // Equal objects should have equal hashes TEST_EQUAL(ma1 == ma2, true) TEST_EQUAL(hasher(ma1), hasher(ma2)) // Test that different objects have different hashes (not guaranteed but highly likely) MassAnalyzer ma3; ma3.setType(MassAnalyzer::AnalyzerType::TOF); TEST_NOT_EQUAL(hasher(ma1), hasher(ma3)) // Test use in unordered_set std::unordered_set<MassAnalyzer> ma_set; ma_set.insert(ma1); ma_set.insert(ma2); // Should not add a duplicate ma_set.insert(ma3); TEST_EQUAL(ma_set.size(), 2) // ma1 and ma2 are equal, so only 2 elements // Test use in unordered_map std::unordered_map<MassAnalyzer, int> ma_map; ma_map[ma1] = 1; ma_map[ma2] = 2; // Should overwrite ma1's value since they're equal ma_map[ma3] = 3; TEST_EQUAL(ma_map.size(), 2) TEST_EQUAL(ma_map[ma1], 2) // Value should be 2 since ma2 overwrote ma1 // Test hash consistency (same object should produce same hash) std::size_t hash1 = hasher(ma1); std::size_t hash2 = hasher(ma1); TEST_EQUAL(hash1, hash2) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BinnedSumAgreeingIntensities_test.cpp
.cpp
2,744
95
// 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/COMPARISON/BinnedSumAgreeingIntensities.h> #include <OpenMS/KERNEL/BinnedSpectrum.h> #include <OpenMS/FORMAT/DTAFile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(BinnedSumAgreeingIntensities, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// BinnedSumAgreeingIntensities* ptr = nullptr; BinnedSumAgreeingIntensities* nullPointer = nullptr; START_SECTION(BinnedSumAgreeingIntensities()) { ptr = new BinnedSumAgreeingIntensities(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~BinnedSumAgreeingIntensities()) { delete ptr; } END_SECTION ptr = new BinnedSumAgreeingIntensities(); START_SECTION((BinnedSumAgreeingIntensities(const BinnedSumAgreeingIntensities &source))) { BinnedSumAgreeingIntensities copy(*ptr); TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); } END_SECTION START_SECTION((BinnedSumAgreeingIntensities& operator=(const BinnedSumAgreeingIntensities &source))) { BinnedSumAgreeingIntensities copy; copy = *ptr; TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); } END_SECTION START_SECTION((double operator()(const BinnedSpectrum &spec1, const BinnedSpectrum &spec2) const)) { PeakSpectrum s1, s2; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s2); s2.pop_back(); BinnedSpectrum bs1(s1, 1.5, false, 2, 0.0 ); BinnedSpectrum bs2(s2, 1.5, false, 2, 0.0); double score = (*ptr)(bs1, bs2); TEST_REAL_SIMILAR(score, 0.99707) score = (*ptr)(bs1, bs1); TEST_REAL_SIMILAR(score, 1.0) } END_SECTION START_SECTION((double operator()(const BinnedSpectrum &spec) const )) { PeakSpectrum s1; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); BinnedSpectrum bs1(s1, 1.5, false, 2, BinnedSpectrum::DEFAULT_BIN_OFFSET_LOWRES); double score = (*ptr)(bs1); TEST_REAL_SIMILAR(score, 1); } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AbsoluteQuantitationStandardsFile_test.cpp
.cpp
3,261
88
// 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/FORMAT/AbsoluteQuantitationStandardsFile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(AbsoluteQuantitationStandardsFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// AbsoluteQuantitationStandardsFile* ptr = 0; AbsoluteQuantitationStandardsFile* null_ptr = 0; const String csv_path = OPENMS_GET_TEST_DATA_PATH("AbsoluteQuantitationStandardsFile.csv"); START_SECTION(AbsoluteQuantitationStandardsFile()) { ptr = new AbsoluteQuantitationStandardsFile(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~AbsoluteQuantitationStandardsFile()) { delete ptr; } END_SECTION ptr = new AbsoluteQuantitationStandardsFile(); START_SECTION(void load( const String& filename, std::vector<AbsoluteQuantitationStandards::runConcentration>& run_concentrations ) const) { std::vector<AbsoluteQuantitationStandards::runConcentration> runs; ptr->load(csv_path, runs); TEST_EQUAL(runs.size(), 10) TEST_EQUAL(runs[0].sample_name, "150516_CM1_Level1") TEST_EQUAL(runs[0].component_name, "23dpg.23dpg_1.Light") TEST_EQUAL(runs[0].IS_component_name, "23dpg.23dpg_1.Heavy") TEST_REAL_SIMILAR(runs[0].actual_concentration, 0) TEST_REAL_SIMILAR(runs[0].IS_actual_concentration, 1) TEST_EQUAL(runs[0].concentration_units, "uM") TEST_REAL_SIMILAR(runs[0].dilution_factor, 1) TEST_EQUAL(runs[3].sample_name, "150516_CM1_Level1") TEST_EQUAL(runs[3].component_name, "35cgmp.35cgmp_1.Light") TEST_EQUAL(runs[3].IS_component_name, "35cgmp.35cgmp_1.Heavy") TEST_REAL_SIMILAR(runs[3].actual_concentration, 0) TEST_REAL_SIMILAR(runs[3].IS_actual_concentration, 1) TEST_EQUAL(runs[3].concentration_units, "uM") TEST_REAL_SIMILAR(runs[3].dilution_factor, 1) TEST_EQUAL(runs[6].sample_name, "150516_CM1_Level1") TEST_EQUAL(runs[6].component_name, "accoa.accoa_1.Light") TEST_EQUAL(runs[6].IS_component_name, "accoa.accoa_1.Heavy") TEST_REAL_SIMILAR(runs[6].actual_concentration, 0) TEST_REAL_SIMILAR(runs[6].IS_actual_concentration, 1) TEST_EQUAL(runs[6].concentration_units, "uM") TEST_REAL_SIMILAR(runs[6].dilution_factor, 1) TEST_EQUAL(runs[9].sample_name, "150516_CM1_Level1") TEST_EQUAL(runs[9].component_name, "ade.ade_1.Light") TEST_EQUAL(runs[9].IS_component_name, "ade.ade_1.Heavy") TEST_REAL_SIMILAR(runs[9].actual_concentration, 40) TEST_REAL_SIMILAR(runs[9].IS_actual_concentration, 1) TEST_EQUAL(runs[9].concentration_units, "uM") TEST_REAL_SIMILAR(runs[9].dilution_factor, 1) } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AreaIterator_test.cpp
.cpp
10,991
362
// 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/AreaIterator.h> #include <OpenMS/KERNEL/MSExperiment.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(AreaIterator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// typedef PeakMap Map; using AI = Internal::AreaIterator<Map::PeakType, Map::PeakType&, Map::PeakType*, Map::Iterator, Map::SpectrumType::Iterator>; using AIP = AI::Param; //typedef Internal::AreaIterator<Map::PeakType, const Map::PeakType&, const Map::PeakType*, Map::ConstIterator, Map::SpectrumType::ConstIterator> CAI; AI* ptr1 = nullptr, *ptr2 = nullptr; AI* nullPointer = nullptr; Map exp; exp.resize(5); exp[0].resize(2); exp[0].setRT(2.0); exp[0].setDriftTime(1); exp[0].setMSLevel(1); exp[0][0].setMZ(502); exp[0][1].setMZ(510); exp[1].resize(2); exp[1].setRT(4.0); exp[1].setDriftTime(1.4); exp[1].setMSLevel(1); exp[1][0].setMZ(504); exp[1][1].setMZ(506); exp[2].setRT(6.0); exp[2].setDriftTime(1.6); exp[2].setMSLevel(1); exp[3].resize(2); exp[3].setRT(8.0); exp[3].setDriftTime(1.8); exp[3].setMSLevel(1); exp[3][0].setMZ(504.1); exp[3][1].setMZ(506.1); exp[4].resize(2); exp[4].setRT(10.0); exp[4].setDriftTime(1.99); exp[4].setMSLevel(1); exp[4][0].setMZ(502.1); exp[4][1].setMZ(510.1); START_SECTION((AreaIterator())) ptr1 = new AI(); TEST_NOT_EQUAL(ptr1,nullPointer) END_SECTION START_SECTION((AreaIterator(SpectrumIteratorType first, SpectrumIteratorType begin, SpectrumIteratorType end, CoordinateType low_mz, CoordinateType high_mz))) ptr2 = new AI(AIP(exp.begin(),exp.RTBegin(0), exp.RTEnd(0), 1).lowMZ(0).highMZ(0)); TEST_NOT_EQUAL(ptr2,nullPointer) END_SECTION START_SECTION((~AreaIterator())) delete ptr1; delete ptr2; END_SECTION START_SECTION((bool operator==(const AreaIterator &rhs) const)) AI a1, a2; TEST_TRUE(a1 == a1) TEST_TRUE(a2 == a2) TEST_TRUE(a1 == a2) AI a3(AIP(exp.begin(),exp.RTBegin(0), exp.RTEnd(10), 1).lowMZ(500).highMZ(600)); TEST_TRUE(a3 == a3) TEST_EQUAL(a1==a3, false) TEST_EQUAL(a2==a3, false) END_SECTION START_SECTION((bool operator!=(const AreaIterator &rhs) const)) AI a1, a2; TEST_EQUAL(a1!=a1, false) TEST_EQUAL(a2!=a2, false) TEST_EQUAL(a1!=a2, false) AI a3(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(10), 1).lowMZ(500).highMZ(600)); TEST_EQUAL(a3!=a3, false) TEST_FALSE(a1 == a3) TEST_FALSE(a2 == a3) END_SECTION START_SECTION((AreaIterator(const AreaIterator &rhs))) AI a1; AI a2(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(10), 1).lowMZ(500).highMZ(600)); AI a3(a2); TEST_EQUAL(a3==a1, false) TEST_TRUE(a3 == a2) // copy-constructor on end-Iterator is undefined, so the following // operation is invalid // AI a4(a1); // TEST_TRUE(a4 == a1) // TEST_EQUAL(a4==a2, false) END_SECTION START_SECTION((AreaIterator& operator=(const AreaIterator &rhs))) AI a1, a2; AI a3(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(10), 1).lowMZ(500).highMZ(600)); a2 = a3; TEST_TRUE(a2 == a3) TEST_EQUAL(a2==a1, false) a2 = a1; TEST_TRUE(a2 == a1) TEST_EQUAL(a2==a3, false) END_SECTION START_SECTION((reference operator *() const)) AI it = AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(7), 1).lowMZ(505).highMZ(520)); TEST_REAL_SIMILAR((*it).getMZ(),510.0); END_SECTION START_SECTION((pointer operator->() const)) AI it = AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(7), 1).lowMZ(505).highMZ(520)); TEST_REAL_SIMILAR(it->getMZ(),510.0); END_SECTION START_SECTION((AreaIterator& operator++())) AI it = AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(7), 1).lowMZ(505).highMZ(520)); Map::PeakType* peak = &(*(it++)); TEST_REAL_SIMILAR(peak->getMZ(),510.0); peak = &(*(it++)); TEST_REAL_SIMILAR(peak->getMZ(),506.0); TEST_EQUAL(it==exp.areaEnd(),true); END_SECTION START_SECTION((AreaIterator operator++(int))) AI it = AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(7), 1).lowMZ(505).highMZ(520)); TEST_REAL_SIMILAR(it->getMZ(),510.0); ++it; TEST_REAL_SIMILAR(it->getMZ(),506.0); ++it; TEST_EQUAL(it==exp.areaEnd(),true); END_SECTION START_SECTION((CoordinateType getRT() const)) AI it = AI(AIP(exp.begin(), exp.RTBegin(3), exp.RTEnd(9), 1).lowMZ(503).highMZ(509)); TEST_REAL_SIMILAR(it->getMZ(),504.0); TEST_REAL_SIMILAR(it.getRT(),4.0); ++it; TEST_REAL_SIMILAR(it->getMZ(),506.0); TEST_REAL_SIMILAR(it.getRT(),4.0); ++it; TEST_REAL_SIMILAR(it->getMZ(),504.1); TEST_REAL_SIMILAR(it.getRT(),8.0); ++it; TEST_REAL_SIMILAR(it->getMZ(),506.1); TEST_REAL_SIMILAR(it.getRT(),8.0); ++it; TEST_EQUAL(it==exp.areaEnd(),true); END_SECTION START_SECTION((CoordinateType getDriftTime() const)) AI it = AI(AIP(exp.begin(), exp.RTBegin(3), exp.RTEnd(9), 1).lowMZ(503).highMZ(509).lowIM(1).highIM(1.5)); TEST_REAL_SIMILAR(it->getMZ(), 504.0); TEST_REAL_SIMILAR(it.getRT(), 4.0); TEST_REAL_SIMILAR(it.getDriftTime(), 1.4); ++it; TEST_REAL_SIMILAR(it->getMZ(), 506.0); TEST_REAL_SIMILAR(it.getRT(), 4.0); TEST_REAL_SIMILAR(it.getDriftTime(), 1.4); ++it; ++it; TEST_EQUAL(it == exp.areaEnd(), true); END_SECTION START_SECTION([EXTRA] Overall test) // whole area auto test_all = [&](auto it) { TEST_REAL_SIMILAR(it->getMZ(), 502.0) TEST_REAL_SIMILAR(it.getRT(), 2.0) ++it; TEST_REAL_SIMILAR(it->getMZ(), 510.0) TEST_REAL_SIMILAR(it.getRT(), 2.0) ++it; TEST_REAL_SIMILAR(it->getMZ(), 504.0) TEST_REAL_SIMILAR(it.getRT(), 4.0) ++it; TEST_REAL_SIMILAR(it->getMZ(), 506.0) TEST_REAL_SIMILAR(it.getRT(), 4.0) ++it; TEST_REAL_SIMILAR(it->getMZ(), 504.1) TEST_REAL_SIMILAR(it.getRT(), 8.0) ++it; TEST_REAL_SIMILAR(it->getMZ(), 506.1) TEST_REAL_SIMILAR(it.getRT(), 8.0) ++it; TEST_REAL_SIMILAR(it->getMZ(), 502.1) TEST_REAL_SIMILAR(it.getRT(), 10.0) ++it; TEST_REAL_SIMILAR(it->getMZ(), 510.1) TEST_REAL_SIMILAR(it.getRT(), 10.0) ++it; TEST_EQUAL(it == exp.areaEnd(), true); }; // restrict dimensions (from -inf,+inf), but include the whole range test_all(AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(15), 1).lowMZ(500).highMZ(520))); test_all(AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(15), 1))); test_all(AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(15), 1).lowIM(0).highIM(2))); test_all(AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(15), 1).lowIM(0).highIM(2).lowMZ(500).highMZ(520))); test_all(AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(15), 1).lowIM(0).highIM(2).lowMZ(500).highMZ(520).msLevel(1))); AI it = AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(15), 1).lowMZ(500).highMZ(520)); // center peaks it = AI(AIP(exp.begin(), exp.RTBegin(3), exp.RTEnd(9), 1).lowMZ(503).highMZ(509)); TEST_REAL_SIMILAR(it->getMZ(),504.0); TEST_REAL_SIMILAR(it.getRT(),4.0); ++it; TEST_REAL_SIMILAR(it->getMZ(),506.0); TEST_REAL_SIMILAR(it.getRT(),4.0); ++it; TEST_REAL_SIMILAR(it->getMZ(),504.1); TEST_REAL_SIMILAR(it.getRT(),8.0); ++it; TEST_REAL_SIMILAR(it->getMZ(),506.1); TEST_REAL_SIMILAR(it.getRT(),8.0); ++it; TEST_EQUAL(it==exp.areaEnd(),true); //upper left area it = AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(7), 1).lowMZ(505).highMZ(520)); TEST_REAL_SIMILAR(it->getMZ(),510.0); TEST_REAL_SIMILAR(it.getRT(),2.0); ++it; TEST_REAL_SIMILAR(it->getMZ(),506.0); TEST_REAL_SIMILAR(it.getRT(),4.0); ++it; TEST_EQUAL(it==exp.areaEnd(),true); //upper right area it = AI(AIP(exp.begin(), exp.RTBegin(5), exp.RTEnd(11), 1).lowMZ(505).highMZ(520)); TEST_REAL_SIMILAR(it->getMZ(),506.1); TEST_REAL_SIMILAR(it.getRT(),8.0); ++it; TEST_REAL_SIMILAR(it->getMZ(),510.1); TEST_REAL_SIMILAR(it.getRT(),10.0); ++it; TEST_EQUAL(it==exp.areaEnd(),true); //lower right it = AI(AIP(exp.begin(), exp.RTBegin(5), exp.RTEnd(11), 1).lowMZ(500).highMZ(505)); TEST_REAL_SIMILAR(it->getMZ(),504.1); TEST_REAL_SIMILAR(it.getRT(),8.0); ++it; TEST_REAL_SIMILAR(it->getMZ(),502.1); TEST_REAL_SIMILAR(it.getRT(),10.0); ++it; TEST_EQUAL(it==exp.areaEnd(),true); // lower left it = AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(7), 1).lowMZ(500).highMZ(505)); TEST_REAL_SIMILAR(it->getMZ(),502.0) TEST_REAL_SIMILAR(it.getRT(),2.0) ++it; TEST_REAL_SIMILAR(it->getMZ(),504.0) TEST_REAL_SIMILAR(it.getRT(),4.0) ++it; TEST_EQUAL(it==exp.areaEnd(),true) // Test with empty RT range it = AI(AIP(exp.begin(), exp.RTBegin(5), exp.RTEnd(5.5), 1).lowMZ(500).highMZ(520)); TEST_EQUAL(it==exp.areaEnd(),true) // Test with empty MZ range it = AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(15), 1).lowMZ(505).highMZ(505.5)); TEST_EQUAL(it==exp.areaEnd(),true) // Test with empty RT + MZ range it = AI(AIP(exp.begin(), exp.RTBegin(5), exp.RTEnd(5.5), 1).lowMZ(505).highMZ(505.5)); TEST_EQUAL(it==exp.areaEnd(),true) // Test with empty IM range it = AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(15), 1).lowIM(0).highIM(0.9)); TEST_EQUAL(it == exp.areaEnd(), true) // Test with empty MS level it = AI(AIP(exp.begin(), exp.RTBegin(0), exp.RTEnd(15), 3)); TEST_EQUAL(it == exp.areaEnd(), true) // Test with empty (no MS level 1) experiment PeakMap exp2(exp); exp2[0].setMSLevel(2); exp2[1].setMSLevel(2); exp2[2].setMSLevel(2); exp2[3].setMSLevel(2); exp2[4].setMSLevel(2); it = AI(AIP(exp2.begin(), exp2.RTBegin(0), exp2.RTEnd(15), 1).lowMZ(500).highMZ(520)); TEST_TRUE(it==exp2.areaEnd()) // however: MS level 2 should work it = AI(AIP(exp2.begin(), exp2.RTBegin(0), exp2.RTEnd(15), 2).lowMZ(500).highMZ(520)); TEST_FALSE(it == exp2.areaEnd()) END_SECTION START_SECTION((PeakIndex getPeakIndex() const)) PeakIndex i; AI it = AI(AIP(exp.begin(), exp.begin(), exp.end(), 1).lowMZ(0).highMZ(1000)); i = it.getPeakIndex(); TEST_EQUAL(i.peak,0) TEST_EQUAL(i.spectrum,0) ++it; i = it.getPeakIndex(); TEST_EQUAL(i.peak,1) TEST_EQUAL(i.spectrum,0) ++it; i = it.getPeakIndex(); TEST_EQUAL(i.peak,0) TEST_EQUAL(i.spectrum,1) ++it; i = it.getPeakIndex(); TEST_EQUAL(i.peak,1) TEST_EQUAL(i.spectrum,1) ++it; i = it.getPeakIndex(); TEST_EQUAL(i.peak,0) TEST_EQUAL(i.spectrum,3) ++it; i = it.getPeakIndex(); TEST_EQUAL(i.peak,1) TEST_EQUAL(i.spectrum,3) ++it; i = it.getPeakIndex(); TEST_EQUAL(i.peak,0) TEST_EQUAL(i.spectrum,4) ++it; i = it.getPeakIndex(); TEST_EQUAL(i.peak,1) TEST_EQUAL(i.spectrum,4) ++it; i = it.getPeakIndex(); TEST_EQUAL(i.isValid(),false) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FuzzyStringComparator_test.cpp
.cpp
13,660
451
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Clemens Groepl $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// using namespace std; using namespace OpenMS; /////////////////////////// #include <OpenMS/CONCEPT/FuzzyStringComparator.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <fstream> ///////////////////////////////////////////////////////////// START_TEST(FuzzyStringComparator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FuzzyStringComparator* inst_ptr = nullptr; FuzzyStringComparator* nullPointer = nullptr; START_SECTION((FuzzyStringComparator())) { inst_ptr = new FuzzyStringComparator; TEST_NOT_EQUAL(inst_ptr, nullPointer); } END_SECTION START_SECTION((virtual ~FuzzyStringComparator())) { delete inst_ptr; } END_SECTION START_SECTION((FuzzyStringComparator& operator=(const FuzzyStringComparator& rhs))) { // Not implemented NOT_TESTABLE; } END_SECTION START_SECTION((FuzzyStringComparator(const FuzzyStringComparator& rhs))) { // Not implemented NOT_TESTABLE; } END_SECTION //------------------------------------------------------------ START_SECTION((const double& getAcceptableAbsolute() const)) { // tested along with set-method NOT_TESTABLE; } END_SECTION START_SECTION((const double& getAcceptableRelative() const)) { // tested along with set-method NOT_TESTABLE; } END_SECTION START_SECTION((const int& getVerboseLevel() const)) { // tested along with set-method NOT_TESTABLE; } END_SECTION START_SECTION((const int& getTabWidth() const)) { // tested along with set-method NOT_TESTABLE; } END_SECTION START_SECTION((const int& getFirstColumn() const)) { // tested along with set-method NOT_TESTABLE; } END_SECTION START_SECTION((std::ostream& getLogDestination() const)) { // tested along with set-method NOT_TESTABLE; } END_SECTION START_SECTION((void setAcceptableAbsolute(const double rhs))) { FuzzyStringComparator fsc; fsc.setAcceptableAbsolute(2345.6789); TEST_REAL_SIMILAR(fsc.getAcceptableAbsolute(),2345.6789); } END_SECTION START_SECTION((void setAcceptableRelative(const double rhs))) { FuzzyStringComparator fsc; fsc.setAcceptableRelative(6789.2345); TEST_REAL_SIMILAR(fsc.getAcceptableRelative(),6789.2345); } END_SECTION START_SECTION((void setTabWidth(const int rhs))) { FuzzyStringComparator fsc; fsc.setTabWidth(1452); TEST_EQUAL(fsc.getTabWidth(),1452); } END_SECTION START_SECTION((void setFirstColumn(const int rhs))) { FuzzyStringComparator fsc; fsc.setFirstColumn(4321235); TEST_EQUAL(fsc.getFirstColumn(),4321235); } END_SECTION START_SECTION((void setLogDestination(std::ostream & rhs))) { FuzzyStringComparator fsc; TEST_EQUAL(&fsc.getLogDestination(),&std::cout); fsc.setLogDestination(std::cerr); TEST_EQUAL(&fsc.getLogDestination(),&std::cerr); TEST_NOT_EQUAL(&fsc.getLogDestination(),&std::cout); fsc.setLogDestination(std::cout); TEST_NOT_EQUAL(&fsc.getLogDestination(),&std::cerr); TEST_EQUAL(&fsc.getLogDestination(),&std::cout); } END_SECTION START_SECTION((void setVerboseLevel(const int rhs))) { FuzzyStringComparator fsc; // default should be 2 TEST_EQUAL(fsc.getVerboseLevel(),2); fsc.setVerboseLevel(88); TEST_EQUAL(fsc.getVerboseLevel(),88); fsc.setVerboseLevel(-21); TEST_EQUAL(fsc.getVerboseLevel(),-21); } END_SECTION { FuzzyStringComparator fsc; FuzzyStringComparator const & fsc_cref = fsc; START_SECTION((const StringList& getWhitelist() const )) { TEST_EQUAL(fsc_cref.getWhitelist().empty(),true); // continued below } END_SECTION START_SECTION((StringList& getWhitelist())) { TEST_EQUAL(fsc_cref.getWhitelist().empty(),true); // continued below } END_SECTION START_SECTION((void setWhitelist(const StringList &rhs))) { fsc.setWhitelist(ListUtils::create<String>("null,eins,zwei,drei")); TEST_STRING_EQUAL(fsc.getWhitelist()[0],"null"); TEST_STRING_EQUAL(fsc_cref.getWhitelist()[1],"eins"); TEST_EQUAL(fsc_cref.getWhitelist().size(),4); fsc.setWhitelist(ListUtils::create<String>("zero,one,two,three,four")); TEST_STRING_EQUAL(fsc.getWhitelist()[0],"zero"); TEST_STRING_EQUAL(fsc_cref.getWhitelist()[1],"one"); TEST_EQUAL(fsc_cref.getWhitelist().size(),5); } END_SECTION } //------------------------------------------------------------ START_SECTION((bool compareStrings(std::string const &lhs, std::string const &rhs))) { std::ostringstream log; //------------------------------ // A few test to show what regular expressions could not do but our class can do. { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(2); fsc.setAcceptableRelative(1.00021); fsc.setAcceptableAbsolute(0.0); bool result = (fsc.compareStrings("0.9999E4","1.0001E4")!=0); TEST_EQUAL(result,true); // STATUS(log.str()); } { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(2); fsc.setAcceptableRelative(1.0); fsc.setAcceptableAbsolute(2.0); bool result = (fsc.compareStrings("0.9999E4","1.0001E4")!=0); TEST_EQUAL(result,true); // STATUS(log.str()); } //------------------------------ // Various issues, mixing letters, whitespace, and numbers. { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(1); fsc.setAcceptableRelative(1.01); fsc.setAcceptableAbsolute(0.001); bool result = (fsc.compareStrings("bl a b 00.0022 asdfdf","bl a b 0.00225 asdfdf")!=0); TEST_EQUAL(result,true); // STATUS(log.str()); } { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(1); fsc.setAcceptableRelative(1.01); fsc.setAcceptableAbsolute(0.01); bool result = (fsc.compareStrings("bl a 1.2 b","bl a 1.25 b")!=0); TEST_EQUAL(result,false); // STATUS(log.str()); } { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(1); fsc.setAcceptableRelative(2.); fsc.setAcceptableAbsolute(0.01); bool result = (fsc.compareStrings("bl a 1.2 b","bl a 1.25 b")!=0); TEST_EQUAL(result,true); // STATUS(log.str()); } { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(1); fsc.setAcceptableRelative(1.01); fsc.setAcceptableAbsolute(0.0); bool result = (fsc.compareStrings("bl a 1.002 b","bl a 1.0025 b")!=0); TEST_EQUAL(result,true); // STATUS(log.str()); } //------------------------------ // Test the impact of verbosity_level. { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(1); fsc.setAcceptableRelative(1.03); fsc.setAcceptableAbsolute(0.01); bool result = (fsc.compareStrings("1 \n 2 \n 3","1.01 \n \n \n\n 0002.01000 \n 3")!=0); TEST_EQUAL(result,true); std::vector<OpenMS::String> substrings; result = OpenMS::String(log.str()).split('\n',substrings); // STATUS(log.str()); TEST_EQUAL(result, false); TEST_EQUAL(substrings.size(), 0); STATUS(substrings.size()); } { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(2); fsc.setAcceptableRelative(1.03); fsc.setAcceptableAbsolute(0.01); bool result = (fsc.compareStrings("1 \n 2 \n 3","1.01 \n \n \n\n 0002.01000 \n 3")!=0); TEST_EQUAL(result,true); std::vector<OpenMS::String> substrings; OpenMS::String(log.str()).split('\n',substrings); // STATUS(log.str()); // Magic alert! - You might need to edit these numbers if reportSuccess_() or reportFailure_() changes. TEST_EQUAL(substrings.size(),17); ABORT_IF(substrings.size()!=17); TEST_STRING_EQUAL(substrings[0],"PASSED."); } { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(1); fsc.setAcceptableRelative(1.01); fsc.setAcceptableAbsolute(0.01); fsc.compareStrings("1 \n 2 \n 3","1.11 \n \n \n\n 0004.01000 \n 3"); std::vector<OpenMS::String> substrings; OpenMS::String(log.str()).split('\n',substrings); // STATUS(log.str()); // Magic alert! - You might need to edit these numbers if reportSuccess_() or reportFailure_() changes. TEST_EQUAL(substrings.size(),36); ABORT_IF(substrings.size()!=36); TEST_STRING_EQUAL(substrings[0],"FAILED: 'ratio of numbers is too large'"); } { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); // fsc.setLogDestination(std::cout); fsc.setVerboseLevel(3); fsc.setAcceptableRelative(1.01); fsc.setAcceptableAbsolute(0.01); fsc.compareStrings ( "1 \n xx\n 2.008 \n 3", "1.11 \nU\n \n\n q 0002.04000 \n 3" ); std::vector<OpenMS::String> substrings; OpenMS::String(log.str()).split('\n',substrings); // STATUS(log.str()); // Magic alert! - You might need to edit these numbers if reportSuccess_() or reportFailure_() changes. TEST_EQUAL(substrings.size(),246); ABORT_IF(substrings.size()!=246); TEST_STRING_EQUAL(substrings[0],"FAILED: 'ratio of numbers is too large'"); TEST_STRING_EQUAL(substrings[35],"FAILED: 'input_1 is whitespace, but input_2 is not'"); TEST_STRING_EQUAL(substrings[70],"FAILED: 'different letters'"); TEST_STRING_EQUAL(substrings[105],"FAILED: 'line from input_2 is shorter than line from input_1'"); TEST_STRING_EQUAL(substrings[140],"FAILED: 'input_1 is a number, but input_2 is not'"); TEST_STRING_EQUAL(substrings[175],"FAILED: 'input_1 is not a number, but input_2 is'"); TEST_STRING_EQUAL(substrings[210],"FAILED: 'line from input_1 is shorter than line from input_2'"); } { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(2); fsc.setAcceptableRelative(1.0); fsc.setAcceptableAbsolute(2.0); bool result = fsc.compareStrings("0.9999X","1.0001X"); TEST_EQUAL(result,true); // STATUS(log.str()); } } END_SECTION START_SECTION((bool compareStreams(std::istream &input_1, std::istream &input_2))) { std::ostringstream log; { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(3); fsc.setAcceptableRelative(1.01); fsc.setAcceptableAbsolute(0.01); std::istringstream lhs("1 \n xx\n 2.008 \n 3"); std::istringstream rhs("1.11 \nU\n \n\n q 0002.04000 \n 3"); fsc.compareStreams(lhs,rhs); std::vector<OpenMS::String> substrings; OpenMS::String(log.str()).split('\n',substrings); // STATUS(log.str()); // Magic alert! - You might need to edit these numbers if reportSuccess_() or reportFailure_() changes. TEST_EQUAL(substrings.size(),246); ABORT_IF(substrings.size()!=246); TEST_STRING_EQUAL(substrings[0],"FAILED: 'ratio of numbers is too large'"); TEST_STRING_EQUAL(substrings[35],"FAILED: 'input_1 is whitespace, but input_2 is not'"); TEST_STRING_EQUAL(substrings[70],"FAILED: 'different letters'"); TEST_STRING_EQUAL(substrings[105],"FAILED: 'line from input_2 is shorter than line from input_1'"); TEST_STRING_EQUAL(substrings[140],"FAILED: 'input_1 is a number, but input_2 is not'"); TEST_STRING_EQUAL(substrings[175],"FAILED: 'input_1 is not a number, but input_2 is'"); TEST_STRING_EQUAL(substrings[210],"FAILED: 'line from input_1 is shorter than line from input_2'"); } } END_SECTION START_SECTION((bool compareFiles(const std::string &filename_1, const std::string &filename_2))) { std::ostringstream log; { FuzzyStringComparator fsc; log.str(""); fsc.setLogDestination(log); fsc.setVerboseLevel(3); fsc.setAcceptableRelative(1.01); fsc.setAcceptableAbsolute(0.01); std::string filename1, filename2; NEW_TMP_FILE(filename1); NEW_TMP_FILE(filename2); { std::ofstream file1(filename1.c_str()); std::ofstream file2(filename2.c_str()); file1 << "1 \n xx\n 2.008 \n 3" << std::flush; file2 << "1.11 \nU\n \n\n q 0002.04000 \n 3" << std::flush; file1.close(); file2.close(); } fsc.compareFiles(filename1,filename2); std::vector<OpenMS::String> substrings; OpenMS::String(log.str()).split('\n',substrings); // STATUS(log.str()); // Magic alert! - You might need to edit these numbers if reportSuccess_() or reportFailure_() changes. TEST_EQUAL(substrings.size(),246); ABORT_IF(substrings.size()!=246); TEST_STRING_EQUAL(substrings[0],"FAILED: 'ratio of numbers is too large'"); TEST_STRING_EQUAL(substrings[35],"FAILED: 'input_1 is whitespace, but input_2 is not'"); TEST_STRING_EQUAL(substrings[70],"FAILED: 'different letters'"); TEST_STRING_EQUAL(substrings[105],"FAILED: 'line from input_2 is shorter than line from input_1'"); TEST_STRING_EQUAL(substrings[140],"FAILED: 'input_1 is a number, but input_2 is not'"); TEST_STRING_EQUAL(substrings[175],"FAILED: 'input_1 is not a number, but input_2 is'"); TEST_STRING_EQUAL(substrings[210],"FAILED: 'line from input_1 is shorter than line from input_2'"); } } END_SECTION //------------------------------------------------------------ // START_SECTION(void reportFailure_( char const * const message ) const throw(Failure)) // { // // Tested in compare...() methods // NOT_TESTABLE; // } // END_SECTION // START_SECTION(void reportSuccess_() const) // { // // Tested in compare...() methods // NOT_TESTABLE; // } // END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeakSpectrumCompareFunctor_test.cpp
.cpp
1,482
55
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Volker Mosthaf, Andreas Bertsch $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/COMPARISON/PeakSpectrumCompareFunctor.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(PeakSpectrumCompareFunctor, "$Id$") ///////////////////////////////////////////////////////////// // pure interface class cannot test this START_SECTION(PeakSpectrumCompareFunctor()) NOT_TESTABLE END_SECTION START_SECTION(PeakSpectrumCompareFunctor(const PeakSpectrumCompareFunctor& source)) NOT_TESTABLE END_SECTION START_SECTION(~PeakSpectrumCompareFunctor()) NOT_TESTABLE END_SECTION START_SECTION(PeakSpectrumCompareFunctor& operator = (const PeakSpectrumCompareFunctor& source)) NOT_TESTABLE END_SECTION START_SECTION(double operator () (const PeakSpectrum& a, const PeakSpectrum& b) const) NOT_TESTABLE END_SECTION START_SECTION(double operator () (const PeakSpectrum& a) const) NOT_TESTABLE END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GaussFilter_test.cpp
.cpp
5,138
179
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Eva Lange $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/PROCESSING/SMOOTHING/GaussFilter.h> /////////////////////////// #include <OpenMS/KERNEL/Peak2D.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSChromatogram.h> START_TEST(GaussFilter<D>, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; GaussFilter* dgauss_ptr = nullptr; GaussFilter* dgauss_nullPointer = nullptr; START_SECTION((GaussFilter())) dgauss_ptr = new GaussFilter; TEST_NOT_EQUAL(dgauss_ptr, dgauss_nullPointer) END_SECTION START_SECTION((virtual ~GaussFilter())) delete dgauss_ptr; END_SECTION START_SECTION((template <typename PeakType> void filter(MSSpectrum& spectrum))) MSSpectrum spectrum; spectrum.resize(5); MSSpectrum::Iterator it = spectrum.begin(); for (Size i=0; i<5; ++i, ++it) { it->setIntensity(1.0f); it->setMZ(500.0+0.2*i); } GaussFilter gauss; Param param; param.setValue( "gaussian_width", 1.0); gauss.setParameters(param); gauss.filter(spectrum); it=spectrum.begin(); TEST_REAL_SIMILAR(it->getIntensity(),1.0) ++it; TEST_REAL_SIMILAR(it->getIntensity(),1.0) ++it; TEST_REAL_SIMILAR(it->getIntensity(),1.0) ++it; TEST_REAL_SIMILAR(it->getIntensity(),1.0) ++it; TEST_REAL_SIMILAR(it->getIntensity(),1.0) // We don't throw exceptions anymore... just issue warnings //test exception when the width is too small //param.setValue( "gaussian_width", 0.1); //gauss.setParameters(param); //TEST_EXCEPTION(Exception::IllegalArgument,gauss.filter(spectrum)) END_SECTION START_SECTION((template <typename PeakType> void filter(MSChromatogram<PeakType>& chromatogram))) MSChromatogram chromatogram; chromatogram.resize(5); MSChromatogram::Iterator it = chromatogram.begin(); for (Size i = 0; i < 5; ++i, ++it) { it->setIntensity(1.0f); it->setRT(500.0 + 0.2*i); } GaussFilter gauss; Param param; param.setValue( "gaussian_width", 1.0); gauss.setParameters(param); gauss.filter(chromatogram); it=chromatogram.begin(); TEST_REAL_SIMILAR(it->getIntensity(),1.0) ++it; TEST_REAL_SIMILAR(it->getIntensity(),1.0) ++it; TEST_REAL_SIMILAR(it->getIntensity(),1.0) ++it; TEST_REAL_SIMILAR(it->getIntensity(),1.0) ++it; TEST_REAL_SIMILAR(it->getIntensity(),1.0) END_SECTION START_SECTION((template <typename PeakType> void filterExperiment(MSExperiment<PeakType>& map))) PeakMap exp; exp.resize(4); Peak1D p; for (Size i=0; i<9; ++i) { p.setIntensity(0.0f); p.setMZ(500.0+0.03*i); if (i==3) { p.setIntensity(1.0f); } if (i==4) { p.setIntensity(0.8f); } if (i==5) { p.setIntensity(1.2f); } exp[0].push_back(p); exp[1].push_back(p); } exp[2].push_back(p); //test exception GaussFilter gauss; Param param; //real test TOLERANCE_ABSOLUTE(0.01) param.setValue("gaussian_width", 0.2); gauss.setParameters(param); gauss.filterExperiment(exp); TEST_EQUAL(exp.size(),4) TEST_EQUAL(exp[0].size(),9) TEST_EQUAL(exp[1].size(),9) TEST_EQUAL(exp[2].size(),1) TEST_EQUAL(exp[3].size(),0) TEST_REAL_SIMILAR(exp[0][0].getIntensity(),0.000734827) TEST_REAL_SIMILAR(exp[0][1].getIntensity(),0.0543746) TEST_REAL_SIMILAR(exp[0][2].getIntensity(),0.298025) TEST_REAL_SIMILAR(exp[0][3].getIntensity(),0.707691) TEST_REAL_SIMILAR(exp[0][4].getIntensity(),0.8963) TEST_REAL_SIMILAR(exp[0][5].getIntensity(),0.799397) TEST_REAL_SIMILAR(exp[0][6].getIntensity(),0.352416) TEST_REAL_SIMILAR(exp[0][7].getIntensity(),0.065132) TEST_REAL_SIMILAR(exp[0][8].getIntensity(),0.000881793) TEST_REAL_SIMILAR(exp[1][0].getIntensity(),0.000734827) TEST_REAL_SIMILAR(exp[1][1].getIntensity(),0.0543746) TEST_REAL_SIMILAR(exp[1][2].getIntensity(),0.298025) TEST_REAL_SIMILAR(exp[1][3].getIntensity(),0.707691) TEST_REAL_SIMILAR(exp[1][4].getIntensity(),0.8963) TEST_REAL_SIMILAR(exp[1][5].getIntensity(),0.799397) TEST_REAL_SIMILAR(exp[1][6].getIntensity(),0.352416) TEST_REAL_SIMILAR(exp[1][7].getIntensity(),0.065132) TEST_REAL_SIMILAR(exp[1][8].getIntensity(),0.000881793) TEST_REAL_SIMILAR(exp[2][0].getIntensity(),0.0) // We don't throw exceptions anymore... just issue warnings //test exception for too low gaussian width //param.setValue("gaussian_width", 0.01); //gauss.setParameters(param); //TEST_EXCEPTION(Exception::IllegalArgument,gauss.filterExperiment(exp)) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MassFeatureTrace_test.cpp
.cpp
5,176
173
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Jihyung Kim$ // $Authors: Jihyung Kim$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h> #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> #include <OpenMS/ANALYSIS/TOPDOWN/MassFeatureTrace.h> #include <OpenMS/ANALYSIS/TOPDOWN/PeakGroup.h> #include <OpenMS/ANALYSIS/TOPDOWN/SpectralDeconvolution.h> #include <OpenMS/FORMAT/FLASHDeconvFeatureFile.h> #include <OpenMS/KERNEL/MSSpectrum.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MassFeatureTrace, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MassFeatureTrace* ptr = 0; MassFeatureTrace* null_ptr = 0; START_SECTION(MassFeatureTrace()) { ptr = new MassFeatureTrace(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~MassFeatureTrace()) { delete ptr; } END_SECTION /// sample input for testing /// MassFeatureTrace mass_tracer; MSSpectrum sample_spec; sample_spec.setRT(50.0); sample_spec.setMSLevel(1); DeconvolvedSpectrum deconv_spec1(1); deconv_spec1.setOriginalSpectrum(sample_spec); PeakGroup tmp_pg = PeakGroup(15, 18, true); Peak1D p1(1000.8455675085044, 8347717.5); FLASHHelperClasses::LogMzPeak tmp_p1(p1, true); tmp_p1.abs_charge = 18; tmp_p1.isotopeIndex = 8; p1 = Peak1D(1000.9013094439375, 10087364); FLASHHelperClasses::LogMzPeak tmp_p2(p1, true); tmp_p2.abs_charge = 18; tmp_p2.isotopeIndex = 9; p1 = Peak1D(1000.9570513793709, 11094268); FLASHHelperClasses::LogMzPeak tmp_p3(p1, true); tmp_p3.abs_charge = 18; tmp_p3.isotopeIndex = 10; p1 = Peak1D(1001.0127933148044, 11212854); FLASHHelperClasses::LogMzPeak tmp_p4(p1, true); tmp_p4.abs_charge = 18; tmp_p4.isotopeIndex = 11; p1 = Peak1D(1001.0685352502376, 10497022); FLASHHelperClasses::LogMzPeak tmp_p5(p1, true); tmp_p5.abs_charge = 18; tmp_p5.isotopeIndex = 12; p1 = Peak1D(1001.124277185671, 9162559); FLASHHelperClasses::LogMzPeak tmp_p6(p1, true); tmp_p6.abs_charge = 18; tmp_p6.isotopeIndex = 13; p1 = Peak1D(1059.6595846286061, 8347717.5); FLASHHelperClasses::LogMzPeak tmp_p7(p1, true); tmp_p7.abs_charge = 17; tmp_p7.isotopeIndex = 8; p1 = Peak1D(1059.7186055014179, 10087364); FLASHHelperClasses::LogMzPeak tmp_p8(p1, true); tmp_p8.abs_charge = 17; tmp_p8.isotopeIndex = 9; p1 = Peak1D(1059.7776263742296, 11094268); FLASHHelperClasses::LogMzPeak tmp_p9(p1, true); tmp_p9.abs_charge = 17; tmp_p9.isotopeIndex = 10; p1 = Peak1D(1059.8366472470416, 11212854); FLASHHelperClasses::LogMzPeak tmp_p10(p1, true); tmp_p10.abs_charge = 17; tmp_p10.isotopeIndex = 11; p1 = Peak1D(1059.8956681198531, 10497022); FLASHHelperClasses::LogMzPeak tmp_p11(p1, true); tmp_p11.abs_charge = 17; tmp_p11.isotopeIndex = 12; p1 = Peak1D(1059.9546889926651, 9162559); FLASHHelperClasses::LogMzPeak tmp_p12(p1, true); tmp_p12.abs_charge = 17; tmp_p12.isotopeIndex = 13; tmp_pg.push_back(tmp_p1); tmp_pg.push_back(tmp_p2); tmp_pg.push_back(tmp_p3); tmp_pg.push_back(tmp_p4); tmp_pg.push_back(tmp_p5); tmp_pg.push_back(tmp_p6); tmp_pg.push_back(tmp_p7); tmp_pg.push_back(tmp_p8); tmp_pg.push_back(tmp_p9); tmp_pg.push_back(tmp_p10); tmp_pg.push_back(tmp_p11); tmp_pg.push_back(tmp_p12); deconv_spec1.push_back(tmp_pg); sample_spec.setRT(55.0); DeconvolvedSpectrum deconv_spec2(2); deconv_spec2.setOriginalSpectrum(sample_spec); deconv_spec2.push_back(tmp_pg); sample_spec.setRT(61.0); DeconvolvedSpectrum deconv_spec3(3); deconv_spec3.setOriginalSpectrum(sample_spec); deconv_spec3.push_back(tmp_pg); ////////////////////////////// std::vector<DeconvolvedSpectrum> deconvolved_specs; deconvolved_specs.push_back(deconv_spec1); deconvolved_specs.push_back(deconv_spec2); deconvolved_specs.push_back(deconv_spec3); /// < public methods without tests > /// - storeInformationFromDeconvolvedSpectrum : only private variables are affected (cannot test) /// - copy, assignment, move constructor -> not used. /// - size START_SECTION((std::vector<FLASHHelperClasses::MassFeature> findFeatures(const PrecalculatedAveragine &averagine))) { // prepare findFeature arguments std::unordered_map<int, PeakGroup> null_map; SpectralDeconvolution fd = SpectralDeconvolution(); Param fd_param; fd_param.setValue("min_charge", 5); fd_param.setValue("max_charge", 20); fd_param.setValue("max_mass", 50000.); fd.setParameters(fd_param); fd.calculateAveragine(false); FLASHHelperClasses::PrecalculatedAveragine averagine = fd.getAveragine(); std::vector<FLASHHelperClasses::MassFeature> found_feature = mass_tracer.findFeaturesAndUpdateQscore2D(averagine, deconvolved_specs, 1); OPENMS_LOG_INFO << found_feature.size() << std::endl; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeakAlignment_test.cpp
.cpp
3,210
118
// 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/COMPARISON/PeakAlignment.h> #include <OpenMS/FORMAT/DTAFile.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <vector> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(PeakAlignment, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeakAlignment* ptr = nullptr; PeakAlignment* nullPointer = nullptr; START_SECTION(PeakAlignment()) { ptr = new PeakAlignment(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~PeakAlignment()) { delete ptr; } END_SECTION START_SECTION((PeakAlignment(const PeakAlignment &source))) { ptr = new PeakAlignment(); PeakAlignment copy(*ptr); TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); } END_SECTION START_SECTION((PeakAlignment& operator=(const PeakAlignment &source))) { PeakAlignment copy; copy = *ptr; TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); } END_SECTION START_SECTION((double operator()(const PeakSpectrum &spec1, const PeakSpectrum &spec2) const )) { PeakAlignment pa; PeakSpectrum s1, s2; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s2); s2.pop_back(); double score = pa(s1, s2); TEST_REAL_SIMILAR(score, 0.997477) // Test empty spectra - they should return zero PeakSpectrum empty_spectrum; score = pa(empty_spectrum, s2); TEST_REAL_SIMILAR(score, 0.0) score = pa(s1, empty_spectrum); TEST_REAL_SIMILAR(score, 0.0) } END_SECTION START_SECTION((double operator()(const PeakSpectrum &spec) const )) { PeakSpectrum s1; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); double score = (*ptr)(s1); TEST_REAL_SIMILAR(score, 1); } END_SECTION START_SECTION((vector< pair<Size,Size> > getAlignmentTraceback(const PeakSpectrum &spec1, const PeakSpectrum &spec2) const )) { PeakAlignment pa; PeakSpectrum s1, s2; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s2); vector< pair<Size,Size> > result, tester; result = pa.getAlignmentTraceback(s1,s2); for (Size i = 0; i < 127; ++i) { tester.push_back(pair<Size,Size>(i,i)); } TEST_EQUAL(tester.size(),result.size()) for (Size i = 0; i < tester.size(); ++i) { TEST_EQUAL(tester.at(i).first,result.at(i).first) } } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BilinearInterpolation_test.cpp
.cpp
13,883
576
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- /////////////////////////// // This one is going to be tested. #include <OpenMS/ML/INTERPOLATION/BilinearInterpolation.h> #include <OpenMS/DATASTRUCTURES/MatrixEigen.h> /////////////////////////// // More headers #include <cstdlib> #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/MATH/MathFunctions.h> /////////////////////////// namespace OpenMS { double rand01 () { return double(rand()) / RAND_MAX; } } using namespace OpenMS; using namespace OpenMS::Math; ///////////////////////////////////////////////////////////// START_TEST( BilinearInterpolation, "$Id$" ) ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// typedef BilinearInterpolation < float, double > BIFD; BIFD * bifd_ptr = nullptr; BIFD * bifd_nullPointer = nullptr; START_SECTION(BilinearInterpolation()) { BIFD bifd; bifd_ptr = new BIFD; TEST_NOT_EQUAL(bifd_ptr,bifd_nullPointer); } END_SECTION START_SECTION(~BilinearInterpolation()) { delete bifd_ptr; } END_SECTION START_SECTION(BilinearInterpolation& operator= ( BilinearInterpolation const & arg )) { BIFD::ContainerType v; v.resize(2,3); v(0,0) = 17; v(0,1) = 18.9; v(0,2) = 20.333; v(1,0) = -.1; v(1,1) = -.13; v(1,2) = -.001; BIFD bifd; bifd.setData(v); bifd.setMapping_0( 13, 230, 14, 250 ); bifd.setMapping_1( 15, 2100, 17, 2900 ); BIFD bifd2; // do it bifd2 = bifd; TEST_REAL_SIMILAR(bifd2.getScale_0(), 20); TEST_REAL_SIMILAR(bifd2.getScale_1(), 400); TEST_REAL_SIMILAR(bifd2.getOffset_0(), -30); TEST_REAL_SIMILAR(bifd2.getOffset_1(), -3900); TEST_REAL_SIMILAR(bifd2.getInsideReferencePoint_0(), 13); TEST_REAL_SIMILAR(bifd2.getOutsideReferencePoint_0(), 230); TEST_REAL_SIMILAR(bifd2.getInsideReferencePoint_1(), 15); TEST_REAL_SIMILAR(bifd2.getOutsideReferencePoint_1(), 2100); for ( UInt i = 0; i < v.rows(); ++i ) for ( UInt j = 0; j < v.cols(); ++j ) TEST_EQUAL(bifd2.getData()(i,j),v(i,j)); } END_SECTION START_SECTION(BilinearInterpolation( BilinearInterpolation const & arg )) { BIFD::ContainerType v; v.resize(2,3); v(0,0) = 17; v(0,1) = 18.9; v(0,2) = 20.333; v(1,0) = -.1; v(1,1) = -.13; v(1,2) = -.001; BIFD bifd; bifd.setData(v); bifd.setMapping_0( 13, 230, 14, 250 ); bifd.setMapping_1( 15, 2100, 17, 2900 ); // do it BIFD bifd2 = bifd; TEST_REAL_SIMILAR(bifd2.getScale_0(), 20); TEST_REAL_SIMILAR(bifd2.getScale_1(), 400); TEST_REAL_SIMILAR(bifd2.getOffset_0(), -30); TEST_REAL_SIMILAR(bifd2.getOffset_1(), -3900); TEST_REAL_SIMILAR(bifd2.getInsideReferencePoint_0(), 13); TEST_REAL_SIMILAR(bifd2.getOutsideReferencePoint_0(), 230); TEST_REAL_SIMILAR(bifd2.getInsideReferencePoint_1(), 15); TEST_REAL_SIMILAR(bifd2.getOutsideReferencePoint_1(), 2100); for ( UInt i = 0; i < v.rows(); ++i ) for ( UInt j = 0; j < v.cols(); ++j ) TEST_EQUAL(bifd2.getData()(i,j),v(i,j)); } END_SECTION START_SECTION(ContainerType& getData()) { BIFD bifd; bifd.getData().resize(2,3); bifd.getData()(1,2) = 10012; bifd.getData()(0,0) = 10000; bifd.getData()(1,0) = 10010; BIFD const & bifd_cr(bifd); TEST_REAL_SIMILAR(bifd_cr.getData()(1,2),10012); TEST_REAL_SIMILAR(bifd_cr.getData()(0,0),10000); TEST_REAL_SIMILAR(bifd_cr.getData()(1,0),10010); } END_SECTION START_SECTION(ContainerType const& getData() const) { // see above, ContainerType& getData() NOT_TESTABLE; } END_SECTION START_SECTION(template< typename SourceContainer > void setData( SourceContainer const & data )) { BIFD bifd; bifd.getData().resize(2,3); bifd.getData().fill(0.0); bifd.getData()(1,2) = 10012; bifd.getData()(0,0) = 10000; bifd.getData()(1,0) = 10010; BIFD const & bifd_cr(bifd); BIFD bifd2; bifd2.setData(bifd_cr.getData()); TEST_EQUAL(bifd.getData(),bifd2.getData()); BIFD bifd3; bifd3.getData().resize(2,3); bifd3.getData()(1, 2) = 10012 + 1; // make sure at least one cell is different TEST_NOT_EQUAL(bifd.getData(),bifd3.getData()); } END_SECTION // Lots of methods with _0 and _1. // I'll deal with the _0 case first, // then copy/rename this for _1 START_SECTION((void setMapping_0( KeyType const & inside_low, KeyType const & outside_low, KeyType const & inside_high, KeyType const & outside_high ))) { BIFD bifd; bifd.setMapping_0(1,2,3,8); TEST_REAL_SIMILAR(bifd.getScale_0(),3); TEST_REAL_SIMILAR(bifd.getOffset_0(),-1); TEST_REAL_SIMILAR(bifd.getScale_1(),1); TEST_REAL_SIMILAR(bifd.getOffset_1(),0); } END_SECTION START_SECTION((void setMapping_0( KeyType const & scale, KeyType const & inside_low, KeyType const & outside_low ))) { BIFD bifd; bifd.setMapping_0(3,1,2); TEST_REAL_SIMILAR(bifd.getScale_0(),3); TEST_REAL_SIMILAR(bifd.getOffset_0(),-1); TEST_REAL_SIMILAR(bifd.getScale_1(),1); TEST_REAL_SIMILAR(bifd.getOffset_1(),0); } END_SECTION START_SECTION(void setOffset_0( KeyType const & offset )) { BIFD bifd; bifd.setOffset_0(987); BIFD const& bifd_cr(bifd); TEST_REAL_SIMILAR(bifd_cr.getOffset_0(),987); } END_SECTION START_SECTION(KeyType const& getOffset_0() const) { // see above, void setOffset_0( KeyType const & offset ) NOT_TESTABLE; } END_SECTION START_SECTION(void setScale_0( KeyType const & scale )) { BIFD bifd; bifd.setScale_0(987); BIFD const& bifd_cr(bifd); TEST_REAL_SIMILAR(bifd_cr.getScale_0(),987); } END_SECTION START_SECTION(KeyType const& getScale_0() const) { // see above, void setScale_0( KeyType const & scale ) NOT_TESTABLE; } END_SECTION START_SECTION(KeyType const& getInsideReferencePoint_0() const) { BIFD bifd; bifd.setMapping_0(1,4,3,8); TEST_REAL_SIMILAR(bifd.getInsideReferencePoint_0(),1); TEST_REAL_SIMILAR(bifd.getOutsideReferencePoint_0(),4); TEST_REAL_SIMILAR(bifd.getInsideReferencePoint_1(),0); TEST_REAL_SIMILAR(bifd.getOutsideReferencePoint_1(),0); } END_SECTION START_SECTION(KeyType const& getOutsideReferencePoint_0() const) { // see above, getInsideReferencePoint_0() NOT_TESTABLE; } END_SECTION START_SECTION(KeyType index2key_0( KeyType pos ) const) { BIFD bifd; bifd.setMapping_0(3,1,2); TEST_REAL_SIMILAR(bifd.index2key_0(0),-1); TEST_REAL_SIMILAR(bifd.index2key_1(0),0); } END_SECTION START_SECTION(KeyType key2index_0( KeyType pos ) const) { BIFD bifd; bifd.setMapping_0(3,1,2); TEST_REAL_SIMILAR(bifd.key2index_0(-1),0); TEST_REAL_SIMILAR(bifd.key2index_1(0),0); } END_SECTION START_SECTION(KeyType supportMax_0() const) { BIFD bifd; bifd.setMapping_0(3,1,2); bifd.setMapping_1(5,3,4); bifd.getData().resize(2,3); TEST_REAL_SIMILAR(bifd.index2key_0(0),-1); TEST_REAL_SIMILAR(bifd.index2key_0(1),2); TEST_REAL_SIMILAR(bifd.supportMin_0(),-4); TEST_REAL_SIMILAR(bifd.supportMax_0(),5); TEST_REAL_SIMILAR(bifd.index2key_1(0),-11); TEST_REAL_SIMILAR(bifd.index2key_1(2),-1); TEST_REAL_SIMILAR(bifd.supportMin_1(),-16); TEST_REAL_SIMILAR(bifd.supportMax_1(),4); } END_SECTION START_SECTION(KeyType supportMin_0() const) { // see above, supportMax_0 NOT_TESTABLE; } END_SECTION // here is the same stuff with _1 and _0 exchanged START_SECTION((void setMapping_1( KeyType const & inside_low, KeyType const & outside_low, KeyType const & inside_high, KeyType const & outside_high ))) { BIFD bifd; bifd.setMapping_1(1,2,3,8); TEST_REAL_SIMILAR(bifd.getScale_1(),3); TEST_REAL_SIMILAR(bifd.getOffset_1(),-1); TEST_REAL_SIMILAR(bifd.getScale_0(),1); TEST_REAL_SIMILAR(bifd.getOffset_0(),0); } END_SECTION START_SECTION((void setMapping_1( KeyType const & scale, KeyType const & inside_low, KeyType const & outside_low ))) { BIFD bifd; bifd.setMapping_1(3,1,2); TEST_REAL_SIMILAR(bifd.getScale_1(),3); TEST_REAL_SIMILAR(bifd.getOffset_1(),-1); TEST_REAL_SIMILAR(bifd.getScale_0(),1); TEST_REAL_SIMILAR(bifd.getOffset_0(),0); } END_SECTION START_SECTION(void setOffset_1( KeyType const & offset )) { BIFD bifd; bifd.setOffset_1(987); BIFD const& bifd_cr(bifd); TEST_REAL_SIMILAR(bifd_cr.getOffset_1(),987); } END_SECTION START_SECTION(KeyType const& getOffset_1() const) { // see above, void setOffset_1( KeyType const & offset ) NOT_TESTABLE; } END_SECTION START_SECTION(void setScale_1( KeyType const & scale )) { BIFD bifd; bifd.setScale_1(987); BIFD const& bifd_cr(bifd); TEST_REAL_SIMILAR(bifd_cr.getScale_1(),987); } END_SECTION START_SECTION(KeyType const& getScale_1() const) { // see above, void setScale_1( KeyType const & scale ) NOT_TESTABLE; } END_SECTION START_SECTION(KeyType const& getInsideReferencePoint_1() const) { BIFD bifd; bifd.setMapping_1(1,4,3,8); TEST_REAL_SIMILAR(bifd.getInsideReferencePoint_1(),1); TEST_REAL_SIMILAR(bifd.getOutsideReferencePoint_1(),4); TEST_REAL_SIMILAR(bifd.getInsideReferencePoint_0(),0); TEST_REAL_SIMILAR(bifd.getOutsideReferencePoint_0(),0); } END_SECTION START_SECTION(KeyType const& getOutsideReferencePoint_1() const) { // see above, getInsideReferencePoint_1() NOT_TESTABLE; } END_SECTION START_SECTION(KeyType index2key_1( KeyType pos ) const) { BIFD bifd; bifd.setMapping_1(3,1,2); TEST_REAL_SIMILAR(bifd.index2key_1(0),-1); TEST_REAL_SIMILAR(bifd.index2key_0(0),0); } END_SECTION START_SECTION(KeyType key2index_1( KeyType pos ) const) { BIFD bifd; bifd.setMapping_1(3,1,2); TEST_REAL_SIMILAR(bifd.key2index_1(-1),0); TEST_REAL_SIMILAR(bifd.key2index_0(0),0); } END_SECTION START_SECTION(KeyType supportMax_1() const) { BIFD bifd; bifd.setMapping_1(3,1,2); bifd.setMapping_0(5,3,4); bifd.getData().resize(3,2); TEST_REAL_SIMILAR(bifd.index2key_1(0),-1); TEST_REAL_SIMILAR(bifd.index2key_1(1),2); TEST_REAL_SIMILAR(bifd.supportMin_1(),-4); TEST_REAL_SIMILAR(bifd.supportMax_1(),5); TEST_REAL_SIMILAR(bifd.index2key_0(0),-11); TEST_REAL_SIMILAR(bifd.index2key_0(2),-1); TEST_REAL_SIMILAR(bifd.supportMin_0(),-16); TEST_REAL_SIMILAR(bifd.supportMax_0(),4); } END_SECTION START_SECTION(KeyType supportMin_1() const) { // see above, supportMax_1 NOT_TESTABLE; } END_SECTION START_SECTION(bool empty() const) { BIFD bifd; TEST_EQUAL(bifd.empty(),true); bifd.getData().resize(1,2); TEST_EQUAL(bifd.empty(),false); bifd.getData().resize(0,0); TEST_EQUAL(bifd.empty(),true); bifd.getData().resize(1,2); TEST_EQUAL(bifd.empty(),false); bifd.getData().resize(1,0); TEST_EQUAL(bifd.empty(),true); bifd.getData().resize(1,2); TEST_EQUAL(bifd.empty(),false); bifd.getData().resize(0,0); TEST_EQUAL(bifd.empty(),true); bifd.getData().resize(2,2); TEST_EQUAL(bifd.empty(),false); } END_SECTION START_SECTION((void addValue( KeyType arg_pos_0, KeyType arg_pos_1, ValueType arg_value ))) { #define verbose(a) // #define verbose(a) a for ( int i = -50; i <= 100; ++i ) { float p = i / 10.f; verbose(STATUS(i)); for ( int j = -50; j <= 100; ++j ) { float q = j / 10.f; verbose(STATUS("i: " << i)); verbose(STATUS("j: " << j)); BIFD bifd_small; bifd_small.getData().resize(5,5); bifd_small.getData().fill(0.0); bifd_small.setMapping_0( 0, 0, 5, 5 ); bifd_small.setMapping_1( 0, 0, 5, 5 ); bifd_small.addValue( p, q, 100 ); eigenView(bifd_small.getData()) = eigenView(bifd_small.getData()).unaryExpr([](double val) { return Math::round(val); }); verbose(STATUS(" " << bifd_small.getData())); BIFD bifd_big; bifd_big.getData().resize(15,15); bifd_big.getData().fill(0.0); bifd_big.setMapping_0( 5, 0, 10, 5 ); bifd_big.setMapping_1( 5, 0, 10, 5 ); bifd_big.addValue( p, q, 100 ); // Round the entries of the matrix in place eigenView(bifd_big.getData()) = eigenView(bifd_big.getData()).unaryExpr([](double val) { return Math::round(val); }); verbose(STATUS(bifd_big.getData())); BIFD::ContainerType big_submatrix; big_submatrix.resize(5,5); for ( int m = 0; m < 5; ++m ) for ( int n = 0; n < 5; ++n ) big_submatrix(m,n)=bifd_big.getData()(m+5,n+5); TEST_EQUAL(bifd_small.getData(),big_submatrix); } } #undef verbose } END_SECTION START_SECTION((ValueType value( KeyType arg_pos_0, KeyType arg_pos_1 ) const)) { #define verbose(a) // #define verbose(a) a // initialize random number generator (not platform independent, but at // least reproducible) srand(2007); TOLERANCE_ABSOLUTE(0.01); BIFD bifd_small; BIFD bifd_big; bifd_small.getData().resize(5,5); bifd_small.getData().fill(0.0); bifd_big.getData().resize(15,15); bifd_big.getData().fill(0.0); for ( int i = 0; i < 5; ++i ) { for ( int j = 0; j < 5; ++j ) { int num = int( floor(rand01() * 100.) ); bifd_small.getData()(i,j) = num; bifd_big.getData()(i+5,j+5) = num; } } bifd_small.setMapping_0( 0, 0, 5, 5 ); bifd_small.setMapping_1( 0, 0, 5, 5 ); bifd_big.setMapping_0( 5, 0, 10, 5 ); bifd_big.setMapping_1( 5, 0, 10, 5 ); Matrix<int> interpolated(151,151); // you can view this as an image in PGM format verbose(std::cout << "P2\n151 151\n100\n" << std::endl); for ( int i = -50; i <= 100; ++i ) { float p = i / 10.f; verbose(STATUS(i)); for ( int j = -50; j <= 100; ++j ) { float q = j / 10.f; verbose(STATUS("i: " << i)); verbose(STATUS("j: " << j)); TEST_REAL_SIMILAR(bifd_small.value(p,q),bifd_big.value(p,q)); interpolated(i+50,j+50) = int(bifd_small.value(p,q)); } } verbose(std::cout << interpolated << std::endl); #undef verbose } END_SECTION //----------------------------------------------------------- //----------------------------------------------------------- ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/LinearResamplerAlign_test.cpp
.cpp
15,309
557
// 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/Peak1D.h> #include <OpenMS/KERNEL/ChromatogramPeak.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <OpenMS/PROCESSING/RESAMPLING/LinearResamplerAlign.h> using namespace OpenMS; using namespace std; template <class SpectrumT> void check_results(SpectrumT spec) { double sum = 0.0; for (Size i = 0; i < spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 20); TEST_REAL_SIMILAR(spec[0].getIntensity(), 3 + 2); TEST_REAL_SIMILAR(spec[1].getIntensity(), 4 + 2.0 / 3 * 8); TEST_REAL_SIMILAR(spec[2].getIntensity(), 1.0 / 3 *8 +2 + 1.0 / 3); TEST_REAL_SIMILAR(spec[3].getIntensity(), 2.0 / 3); } /////////////////////////// START_TEST(LinearResamplerAlign, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MSSpectrum input_spectrum; input_spectrum.resize(5); input_spectrum[0].setMZ(0); input_spectrum[0].setIntensity(3.0f); input_spectrum[1].setMZ(0.5); input_spectrum[1].setIntensity(6.0f); input_spectrum[2].setMZ(1.); input_spectrum[2].setIntensity(8.0f); input_spectrum[3].setMZ(1.6); input_spectrum[3].setIntensity(2.0f); input_spectrum[4].setMZ(1.8); input_spectrum[4].setIntensity(1.0f); // A spacing of 0.75 will lead to a recalculation of intensities, each // resampled point gets intensities from raw data points that are at most +/- // spacing away. double default_spacing = 0.75; #if 1 START_SECTION(( template < template< typename > class SpecT, typename PeakType > void raster(SpecT< PeakType > &spectrum))) { MSSpectrum spec = input_spectrum; LinearResamplerAlign lr; Param param; param.setValue("spacing", default_spacing); lr.setParameters(param); lr.raster(spec); double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 20); TEST_REAL_SIMILAR(spec[0].getIntensity(), 3+2); TEST_REAL_SIMILAR(spec[1].getIntensity(), 4+2.0/3*8); TEST_REAL_SIMILAR(spec[2].getIntensity(), 1.0/3*8+2+1.0/3); TEST_REAL_SIMILAR(spec[3].getIntensity(), 2.0 / 3); } END_SECTION // it should also work with chromatograms START_SECTION([EXTRA] test_linear_res_chromat) { MSChromatogram chrom; chrom.resize(5); chrom[0].setRT(0); chrom[0].setIntensity(3.0f); chrom[1].setRT(0.5); chrom[1].setIntensity(6.0f); chrom[2].setRT(1.); chrom[2].setIntensity(8.0f); chrom[3].setRT(1.6); chrom[3].setIntensity(2.0f); chrom[4].setRT(1.8); chrom[4].setIntensity(1.0f); LinearResamplerAlign lr; Param param; param.setValue("spacing", default_spacing); lr.setParameters(param); lr.raster(chrom); check_results(chrom); } END_SECTION START_SECTION(( void raster(ConstPeakTypeIterator raw_it, ConstPeakTypeIterator raw_end, PeakTypeIterator resample_it, PeakTypeIterator resample_end))) { MSSpectrum spec = input_spectrum; MSSpectrum output_spectrum; output_spectrum.resize(4); // We want to resample the input spectrum at these m/z positions: 0, 0.75, 1.5 and 2.25 std::vector<double> mz_res_data(4); std::vector<double> int_res_data(4); output_spectrum[0].setMZ(0); output_spectrum[1].setMZ(0.75); output_spectrum[2].setMZ(1.5); output_spectrum[3].setMZ(2.25); LinearResamplerAlign lr; Param param; param.setValue("spacing", default_spacing); lr.setParameters(param); lr.raster(spec.begin(), spec.end(), output_spectrum.begin(), output_spectrum.end()); check_results(output_spectrum); } END_SECTION // it should also work with data vectors START_SECTION( ( template <typename PeakTypeIterator, typename ConstPeakTypeIterator> void raster(ConstPeakTypeIterator mz_raw_it, ConstPeakTypeIterator mz_raw_end, ConstPeakTypeIterator int_raw_it, ConstPeakTypeIterator int_raw_end, PeakTypeIterator mz_resample_it, PeakTypeIterator mz_resample_end, PeakTypeIterator int_resample_it, PeakTypeIterator int_resample_end ) )) { MSChromatogram spec; std::vector<double> mz_data(5); std::vector<double> int_data(5); mz_data[0] = 0; mz_data[1] = 0.5; mz_data[2] = 1.; mz_data[3] = 1.6; mz_data[4] = 1.8; int_data[0] = 3.0f; int_data[1] = 6.0f; int_data[2] = 8.0f; int_data[3] = 2.0f; int_data[4] = 1.0f; // We want to resample the input spectrum at these m/z positions: 0, 0.75, 1.5 and 2.25 std::vector<double> mz_res_data(4); std::vector<double> int_res_data(4); mz_res_data[0] = 0; mz_res_data[1] = 0.75; mz_res_data[2] = 1.5; mz_res_data[3] = 2.25; LinearResamplerAlign lr; Param param; param.setValue("spacing", default_spacing); lr.setParameters(param); lr.raster(mz_data.begin(), mz_data.end(), int_data.begin(), int_data.end(), mz_res_data.begin(), mz_res_data.end(), int_res_data.begin(), int_res_data.end()); // check_results(spec); double sum = 0.0; for (Size i=0; i<int_res_data.size(); ++i) { sum += int_res_data[i]; } TEST_REAL_SIMILAR(sum, 20); TEST_REAL_SIMILAR(int_res_data[0], 3+2); TEST_REAL_SIMILAR(int_res_data[1], 4+2.0/3*8); TEST_REAL_SIMILAR(int_res_data[2], 1.0/3*8+2+1.0/3); TEST_REAL_SIMILAR(int_res_data[3], 2.0 / 3); } END_SECTION // it should work with alignment to 0, 1.8 and give the same result START_SECTION((template < template< typename > class SpecT, typename PeakType > void raster_align(SpecT< PeakType > &spectrum, double start_pos, double end_pos))) { MSSpectrum spec = input_spectrum; LinearResamplerAlign lr; Param param; param.setValue("spacing",0.75); lr.setParameters(param); lr.raster_align(spec, 0, 1.8); check_results(spec); } END_SECTION // it should work with alignment to -0.25, 1.8 START_SECTION([EXTRA] test_linear_res_align_3) { MSSpectrum spec = input_spectrum; LinearResamplerAlign lr; Param param; param.setValue("spacing",0.5); lr.setParameters(param); lr.raster_align(spec, -0.25, 1.8); double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 20); TEST_REAL_SIMILAR(spec[0].getIntensity(), 1.5); TEST_REAL_SIMILAR(spec[1].getIntensity(), 1.5+3); TEST_REAL_SIMILAR(spec[2].getIntensity(), 3+4); TEST_REAL_SIMILAR(spec[3].getIntensity(), 4.0+ 0.6); TEST_REAL_SIMILAR(spec[4].getIntensity(), 1.4 + 0.9 ); TEST_REAL_SIMILAR(spec[5].getIntensity(), 0.1 ); } END_SECTION // it should work with alignment to -2.25, 1.8 START_SECTION([EXTRA] test_linear_res_align_4) { MSSpectrum spec = input_spectrum; LinearResamplerAlign lr; Param param; param.setValue("spacing",0.75); lr.setParameters(param); lr.raster_align(spec, -2.25, 1.8); double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 20); TEST_REAL_SIMILAR(spec[0].getIntensity(), 0); TEST_REAL_SIMILAR(spec[1].getIntensity(), 0); TEST_REAL_SIMILAR(spec[2].getIntensity(), 0); TEST_REAL_SIMILAR(spec[3].getIntensity(), 3+2); TEST_REAL_SIMILAR(spec[4].getIntensity(), 4+2.0/3*8); TEST_REAL_SIMILAR(spec[5].getIntensity(), 1.0/3*8+2+1.0/3); TEST_REAL_SIMILAR(spec[6].getIntensity(), 2.0 / 3); } END_SECTION // it should work with alignment to -0.25, 1.25 START_SECTION([EXTRA] test_linear_res_align_5) { MSSpectrum spec = input_spectrum; LinearResamplerAlign lr; Param param; param.setValue("spacing",0.5); lr.setParameters(param); lr.raster_align(spec, -0.25, 1.25); double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 20 - 2.4 -0.6); // missing points 1.75 and 2.25 which have intensity 2.4 together TEST_REAL_SIMILAR(spec[0].getIntensity(), 1.5); TEST_REAL_SIMILAR(spec[1].getIntensity(), 1.5+3); TEST_REAL_SIMILAR(spec[2].getIntensity(), 3+4); TEST_REAL_SIMILAR(spec[3].getIntensity(), 4.0);//+ 0.6); } END_SECTION // it should work with alignment to 0.25, 1.8 START_SECTION([EXTRA] test_linear_res_align_6) { MSSpectrum spec = input_spectrum; LinearResamplerAlign lr; Param param; param.setValue("spacing",0.5); lr.setParameters(param); lr.raster_align(spec, 0.25, 1.8); double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 20 - 1.5 -1.5 ); // we loose 1.5 on the left TEST_REAL_SIMILAR(spec[0].getIntensity(), 3); //+1.5); TEST_REAL_SIMILAR(spec[1].getIntensity(), 3+4); TEST_REAL_SIMILAR(spec[2].getIntensity(), 4.0+ 0.6); TEST_REAL_SIMILAR(spec[3].getIntensity(), 1.4 + 0.9 ); } END_SECTION // it should also work when we scale the m/z START_SECTION([EXTRA] test_linear_res_align_scaling) { MSSpectrum spec = input_spectrum; for (Size i = 0; i < spec.size(); i++) { spec[i].setMZ( spec[i].getMZ()*10 ); } LinearResamplerAlign lr; Param param; param.setValue("spacing", 5.0); lr.setParameters(param); lr.raster_align(spec, -2.5, 12.5); double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 20 - 2.4 -0.6); // missing points 1.75 and 2.25 which have intensity 2.4 together TEST_REAL_SIMILAR(spec[0].getIntensity(), 1.5); TEST_REAL_SIMILAR(spec[1].getIntensity(), 1.5+3); TEST_REAL_SIMILAR(spec[2].getIntensity(), 3+4); TEST_REAL_SIMILAR(spec[3].getIntensity(), 4.0); //+ 0.6); } END_SECTION #endif // it should work with ppm scaling START_SECTION([EXTRA] test_linear_res_align_7) { MSSpectrum spec = input_spectrum; // int = [3,6,8,2,1] // mz = [100, 101, 102, 103, 104] spec[0].setMZ(99 + 0.99/2.0); spec[1].setMZ(99.99 + 0.5); spec[2].setMZ(100.99 + 1.01/2.0); spec[3].setMZ(102 + 1.02 / 2.0); spec[4].setMZ(103.02 + 1.03 / 2.0); LinearResamplerAlign lr; Param param; param.setValue("spacing", 10000.0); param.setValue("ppm", "true"); lr.setParameters(param); lr.raster_align(spec, 99, 105); double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); std::cout << spec[i] << std::endl; } TEST_REAL_SIMILAR(sum, 20); TEST_REAL_SIMILAR(spec[0].getIntensity(), 1.5); TEST_REAL_SIMILAR(spec[1].getIntensity(), 4.4997); // 3 + 1.5 TEST_REAL_SIMILAR(spec[2].getIntensity(), 6.99911); // 3 + 4 TEST_REAL_SIMILAR(spec[3].getIntensity(), 5.0008); // 4 + 1 TEST_REAL_SIMILAR(spec[5].getIntensity(), 0.500101); } END_SECTION START_SECTION([EXTRA] test_linear_res_align_8) { MSSpectrum spec = input_spectrum; // int = [3,6,8,2,1] // mz = [100, 101, 102, 103, 104] for (Size i=0; i<spec.size(); ++i) { spec[i].setMZ(100 + i); } LinearResamplerAlign lr; Param param; param.setValue("spacing", 10000.0); param.setValue("ppm", "true"); lr.setParameters(param); lr.raster_align(spec, 99, 105); double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); std::cout << spec[i] << std::endl; } TEST_REAL_SIMILAR(sum, 20); TEST_REAL_SIMILAR(spec[1].getIntensity(), 2.97); TEST_REAL_SIMILAR(spec[2].getIntensity(), 5.97); TEST_REAL_SIMILAR(spec[3].getIntensity(), 8.09725); TEST_REAL_SIMILAR(spec[4].getIntensity(), 2.01129); TEST_REAL_SIMILAR(spec[5].getIntensity(), 0.951471); } END_SECTION #if 1 // also the interpolation should work START_SECTION((template < typename PeakTypeIterator > void raster_interpolate(PeakTypeIterator raw_it, PeakTypeIterator raw_end, PeakTypeIterator it, PeakTypeIterator resampled_end))) { MSSpectrum spec = input_spectrum; MSSpectrum resampled; int i = 0; double start_pos = 0.25; double end_pos = 2.0; double spacing = 0.5; int number_resampled_points = (int)(ceil((end_pos -start_pos) / spacing + 1)); resampled.resize(number_resampled_points); for (MSSpectrum::iterator it = resampled.begin(); it != resampled.end(); it++) { it->setMZ( start_pos + i*spacing); ++i; } LinearResamplerAlign lr; Param param; param.setValue("spacing",0.5); lr.setParameters(param); lr.raster_interpolate(spec.begin(), spec.end(), resampled.begin(), resampled.end() ); spec = resampled; double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(spec[0].getIntensity(), 4.5); TEST_REAL_SIMILAR(spec[1].getIntensity(), 7); TEST_REAL_SIMILAR(spec[2].getIntensity(), 5.5); TEST_REAL_SIMILAR(spec[3].getIntensity(), 1.25); } END_SECTION START_SECTION(( template < typename PeakTypeIterator, typename ConstPeakTypeIterator > void raster(ConstPeakTypeIterator raw_it, ConstPeakTypeIterator raw_end, PeakTypeIterator resample_it, PeakTypeIterator resample_end))) { MSSpectrum spec = input_spectrum; MSSpectrum resampled; int i = 0; double start_pos = 0; double end_pos = 2.25; double spacing = 0.75; int number_resampled_points = (int)(ceil((end_pos -start_pos) / spacing + 1)); resampled.resize(number_resampled_points); for (MSSpectrum::iterator it = resampled.begin(); it != resampled.end(); it++) { it->setMZ( start_pos + i*spacing); ++i; } // A spacing of 0.75 will lead to a recalculation of intensities, each // resampled point gets intensities from raw data points that are at most +/- // spacing away. LinearResamplerAlign lr; Param param; param.setValue("spacing",0.75); lr.setParameters(param); lr.raster(spec.begin(), spec.end(), resampled.begin(), resampled.end() ); spec = resampled; double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 20); TEST_REAL_SIMILAR(spec[0].getIntensity(), 3+2); TEST_REAL_SIMILAR(spec[1].getIntensity(), 4+2.0/3*8); TEST_REAL_SIMILAR(spec[2].getIntensity(), 1.0/3*8+2+1.0/3); TEST_REAL_SIMILAR(spec[3].getIntensity(), 2.0 / 3); } END_SECTION // it should accept nonsense input values START_SECTION([EXTRA] test_linear_res_align_input) { MSSpectrum spec = input_spectrum; LinearResamplerAlign lr; Param param; param.setValue("spacing",0.5); lr.setParameters(param); lr.raster_align(spec, 2.25, 1.8); double sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 0); spec = input_spectrum; lr.raster_align(spec, 0.25, -1.8); sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 0); spec = input_spectrum; lr.raster_align(spec, 2.25, 5.8); sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 0); spec = input_spectrum; lr.raster_align(spec, -2.25, -2.0); sum = 0.0; for (Size i=0; i<spec.size(); ++i) { sum += spec[i].getIntensity(); } TEST_REAL_SIMILAR(sum, 0); } END_SECTION #endif ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/LogStream_test.cpp
.cpp
17,954
589
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow, Stephan Aiche $ // $Authors: Chris Bielow, Stephan Aiche, Andreas Bertsch $ // -------------------------------------------------------------------------- /** Most of the tests, generously provided by the BALL people, taken from version 1.2 */ #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <fstream> #include <boost/regex.hpp> // OpenMP support #ifdef _OPENMP #include <omp.h> #endif /////////////////////////// using namespace OpenMS; using namespace Logger; using namespace std; class TestTarget : public LogStreamNotifier { public: void logNotify() override { notified = true; return; } bool notified; }; START_TEST(LogStream, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] OpenMP - test)) { // Test thread-local logging with OpenMP. // Note: Thread-local streams COPY the stream_list_ from global at initialization, // so we can't easily add a capture stream and expect thread-local loggers to use it. // Instead, we just verify that parallel logging doesn't crash or corrupt data. // Test 1: Basic parallel logging to cout (default stream) { const int num_iterations = 100; #ifdef _OPENMP omp_set_num_threads(4); #pragma omp parallel for #endif for (int i = 0; i < num_iterations; ++i) { // Each thread uses its own thread-local LogStream OPENMS_LOG_INFO << "iteration_" << i << endl; } // If we get here without crashing, the test passes TEST_EQUAL(true, true) } // Test 2: High-volume logging stress test { // create a long string that is of similar length as the buffer length to // ensure buffering and flushing works correctly LogStream.cpp even in a // multi-threaded environment. std::string long_str; for (int k = 0; k < 32768/2; k++) if (char(k) != 0) long_str += char(k); #ifdef _OPENMP omp_set_num_threads(8); #pragma omp parallel for #endif for (int i=0;i<10000;++i) { OPENMS_LOG_DEBUG << long_str << "1\n"; OPENMS_LOG_DEBUG << "2" << endl; OPENMS_LOG_INFO << "1\n"; OPENMS_LOG_INFO << "2" << endl; } // If we get here without crashing, the test passes TEST_EQUAL(true, true) } } END_SECTION LogStream* nullPointer = nullptr; START_SECTION(LogStream(LogStreamBuf *buf=0, bool delete_buf=true, std::ostream* stream)) { LogStream* l1 = new LogStream((LogStreamBuf*)nullptr); TEST_NOT_EQUAL(l1, nullPointer) delete l1; LogStreamBuf* lb2(new LogStreamBuf()); LogStream* l2 = new LogStream(lb2); TEST_NOT_EQUAL(l2, nullPointer) delete l2; } END_SECTION START_SECTION((virtual ~LogStream())) { ostringstream stream_by_logger; { LogStream* l1 = new LogStream(new LogStreamBuf()); l1->insert(stream_by_logger); *l1 << "flushtest" << endl; TEST_EQUAL(stream_by_logger.str(),"flushtest\n") *l1 << "unfinishedline..."; TEST_EQUAL(stream_by_logger.str(),"flushtest\n") delete l1; // testing if loggers' d'tor will distribute the unfinished line to its children... } TEST_EQUAL(stream_by_logger.str(),"flushtest\nunfinishedline...\n") } END_SECTION START_SECTION((LogStreamBuf* operator->())) { LogStream l1(new LogStreamBuf()); l1->sync(); // if it doesn't crash we're happy NOT_TESTABLE } END_SECTION START_SECTION((LogStreamBuf* rdbuf())) { LogStream l1(new LogStreamBuf()); // small workaround since TEST_NOT_EQUAL(l1.rdbuf, 0) would expand to // cout << ls.rdbuf() // which kills the cout buffer TEST_NOT_EQUAL((l1.rdbuf()==nullptr), true) } END_SECTION START_SECTION((void setLevel(std::string level))) { LogStream l1(new LogStreamBuf()); l1.setLevel("INFORMATION"); TEST_EQUAL(l1.getLevel(), "INFORMATION") } END_SECTION START_SECTION((std::string getLevel())) { LogStream l1(new LogStreamBuf()); TEST_EQUAL(l1.getLevel(), LogStreamBuf::UNKNOWN_LOG_LEVEL) l1.setLevel("FATAL_ERROR"); TEST_EQUAL(l1.getLevel(), "FATAL_ERROR") } END_SECTION START_SECTION((void insert(std::ostream &s))) { String filename; NEW_TMP_FILE(filename) LogStream l1(new LogStreamBuf()); ofstream s(filename.c_str(), std::ios::out); l1.insert(s); l1 << "1\n"; l1 << "2" << endl; TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("LogStream_test_general.txt")) } END_SECTION START_SECTION((void remove(std::ostream &s))) { LogStream l1(new LogStreamBuf()); ostringstream s; l1 << "BLA"<<endl; l1.insert(s); l1 << "to_stream"<<endl; l1.remove(s); // make sure we can remove it twice without harm l1.remove(s); l1 << "BLA2"<<endl; TEST_EQUAL(s.str(),"to_stream\n"); } END_SECTION START_SECTION(([EXTRA] LogSinkGuard - RAII removal and re-insertion)) { // Test 1: Normal scope exit - guard removes on construction, re-inserts on destruction { LogStream l1(new LogStreamBuf()); ostringstream s; l1.insert(s); l1 << "before_guard" << endl; TEST_EQUAL(s.str(), "before_guard\n") { LogSinkGuard guard(l1, s); // guard removes s immediately l1 << "while_guarded" << endl; TEST_EQUAL(s.str(), "before_guard\n") // no change, stream was removed by guard } // guard destructor re-inserts s l1 << "after_guard" << endl; TEST_EQUAL(s.str(), "before_guard\nafter_guard\n") // stream is back } // Test 2: Exception safety - stream should be re-inserted even on exception { LogStream l1(new LogStreamBuf()); ostringstream s; l1.insert(s); try { LogSinkGuard guard(l1, s); // guard removes s l1 << "in_try" << endl; throw std::runtime_error("test exception"); } catch (const std::exception&) { // guard destructor should have run, re-inserting s } l1 << "after_exception" << endl; TEST_EQUAL(s.str(), "after_exception\n") // stream was re-inserted despite exception } // Test 3: Multiple guards on same stream (nested removal/insertion) { LogStream l1(new LogStreamBuf()); ostringstream s; l1.insert(s); { LogSinkGuard guard1(l1, s); // guard1 removes s { LogSinkGuard guard2(l1, s); // guard2 removes s (already removed - no-op) l1 << "deeply_removed" << endl; } // guard2 re-inserts s l1 << "once_reinserted" << endl; } // guard1 re-inserts s (already present - safe/idempotent) l1 << "final" << endl; TEST_EQUAL(s.str(), "once_reinserted\nfinal\n") } } END_SECTION START_SECTION((void insertNotification(std::ostream &s, LogStreamNotifier &target))) { LogStream l1(new LogStreamBuf()); TestTarget target; ofstream os; target.registerAt(l1); target.notified = false; TEST_EQUAL(target.notified, false) l1 << "test" << std::endl; TEST_EQUAL(target.notified, true) } END_SECTION START_SECTION(([EXTRA]removeNotification)) { LogStream l1(new LogStreamBuf()); TestTarget target; ofstream os; target.registerAt(l1); target.unregister(); target.notified = false; TEST_EQUAL(target.notified, false) l1 << "test" << endl; TEST_EQUAL(target.notified, false) // make sure we can remove it twice target.unregister(); l1 << "test" << endl; TEST_EQUAL(target.notified, false) } END_SECTION START_SECTION((void setPrefix(const std::string &prefix))) { LogStream l1(new LogStreamBuf()); ostringstream stream_by_logger; l1.insert(stream_by_logger); l1.setLevel("DEVELOPMENT"); l1.setPrefix("%y"); //message type ("Error", "Warning", "Information", "-") l1 << " 2." << endl; l1.setPrefix("%T"); //time (HH:MM:SS) l1 << " 3." << endl; l1.setPrefix( "%t"); //time in short format (HH:MM) l1 << " 4." << endl; l1.setPrefix("%D"); //date (YYYY/MM/DD) l1 << " 5." << endl; l1.setPrefix("%d"); // date in short format (MM/DD) l1 << " 6." << endl; l1.setPrefix("%S"); //time and date (YYYY/MM/DD, HH:MM:SS) l1 << " 7." << endl; l1.setPrefix("%s"); //time and date in short format (MM/DD, HH:MM) l1 << " 8." << endl; l1.setPrefix("%%"); //percent sign (escape sequence) l1 << " 9." << endl; l1.setPrefix(""); //no prefix l1 << " 10." << endl; StringList to_validate_list = ListUtils::create<String>(String(stream_by_logger.str()),'\n'); TEST_EQUAL(to_validate_list.size(),10) StringList regex_list; regex_list.push_back("DEVELOPMENT 2\\."); regex_list.push_back("[0-2][0-9]:[0-5][0-9]:[0-5][0-9] 3\\."); regex_list.push_back("[0-2][0-9]:[0-5][0-9] 4\\."); regex_list.push_back("[0-9]+/[0-1][0-9]/[0-3][0-9] 5\\."); regex_list.push_back("[0-1][0-9]/[0-3][0-9] 6\\."); regex_list.push_back("[0-9]+/[0-1][0-9]/[0-3][0-9], [0-2][0-9]:[0-5][0-9]:[0-5][0-9] 7\\."); regex_list.push_back("[0-1][0-9]/[0-3][0-9], [0-2][0-9]:[0-5][0-9] 8\\."); regex_list.push_back("% 9\\."); regex_list.push_back(" 10\\."); for (Size i=0;i<regex_list.size();++i) { boost::regex rx(regex_list[i].c_str()); TEST_EQUAL(regex_match(to_validate_list[i], rx), true) } } END_SECTION START_SECTION((void setPrefix(const std::ostream &s, const std::string &prefix))) { LogStream l1(new LogStreamBuf()); ostringstream stream_by_logger; ostringstream stream_by_logger_otherprefix; l1.insert(stream_by_logger); l1.insert(stream_by_logger_otherprefix); l1.setPrefix(stream_by_logger_otherprefix, "BLABLA"); //message type ("Error", "Warning", "Information", "-") l1.setLevel("DEVELOPMENT"); l1.setPrefix(stream_by_logger, "%y"); //message type ("Error", "Warning", "Information", "-") l1 << " 2." << endl; l1.setPrefix(stream_by_logger, "%T"); //time (HH:MM:SS) l1 << " 3." << endl; l1.setPrefix(stream_by_logger, "%t"); //time in short format (HH:MM) l1 << " 4." << endl; l1.setPrefix(stream_by_logger, "%D"); //date (YYYY/MM/DD) l1 << " 5." << endl; l1.setPrefix(stream_by_logger, "%d"); // date in short format (MM/DD) l1 << " 6." << endl; l1.setPrefix(stream_by_logger, "%S"); //time and date (YYYY/MM/DD, HH:MM:SS) l1 << " 7." << endl; l1.setPrefix(stream_by_logger, "%s"); //time and date in short format (MM/DD, HH:MM) l1 << " 8." << endl; l1.setPrefix(stream_by_logger, "%%"); //percent sign (escape sequence) l1 << " 9." << endl; l1.setPrefix(stream_by_logger, ""); //no prefix l1 << " 10." << endl; StringList to_validate_list = ListUtils::create<String>(String(stream_by_logger.str()),'\n'); TEST_EQUAL(to_validate_list.size(),10) StringList to_validate_list2 = ListUtils::create<String>(String(stream_by_logger_otherprefix.str()),'\n'); TEST_EQUAL(to_validate_list2.size(),10) StringList regex_list; regex_list.push_back("DEVELOPMENT 2\\."); regex_list.push_back("[0-2][0-9]:[0-5][0-9]:[0-5][0-9] 3\\."); regex_list.push_back("[0-2][0-9]:[0-5][0-9] 4\\."); regex_list.push_back("[0-9]+/[0-1][0-9]/[0-3][0-9] 5\\."); regex_list.push_back("[0-1][0-9]/[0-3][0-9] 6\\."); regex_list.push_back("[0-9]+/[0-1][0-9]/[0-3][0-9], [0-2][0-9]:[0-5][0-9]:[0-5][0-9] 7\\."); regex_list.push_back("[0-1][0-9]/[0-3][0-9], [0-2][0-9]:[0-5][0-9] 8\\."); regex_list.push_back("% 9\\."); regex_list.push_back(" 10\\."); String other_stream_regex = "BLABLA [ 1][0-9]\\."; boost::regex rx2(other_stream_regex); // QRegExp rx2(other_stream_regex.c_str()); // QRegExpValidator v2(rx2, 0); for (Size i=0;i<regex_list.size();++i) { boost::regex rx(regex_list[i].c_str()); TEST_EQUAL(regex_match(to_validate_list[i], rx), true) TEST_EQUAL(regex_match(to_validate_list2[i], rx2), true) } } END_SECTION START_SECTION((void flush())) { LogStream l1(new LogStreamBuf()); ostringstream stream_by_logger; l1.insert(stream_by_logger); l1 << "flushtest" << endl; TEST_EQUAL(stream_by_logger.str(),"flushtest\n") l1 << "unfinishedline...\n"; TEST_EQUAL(stream_by_logger.str(),"flushtest\n") l1.flush(); TEST_EQUAL(stream_by_logger.str(),"flushtest\nunfinishedline...\n") } END_SECTION START_SECTION(([EXTRA]Test minimum string length of output)) { // taken from BALL tests, it seems that it checks if the logger crashs if one // uses longer lines NOT_TESTABLE LogStream l1(new LogStreamBuf()); l1 << "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" << endl; } END_SECTION START_SECTION(([EXTRA]Test log caching)) { String filename; NEW_TMP_FILE(filename) ofstream s(filename.c_str(), std::ios::out); { LogStream l1(new LogStreamBuf()); l1.insert(s); l1 << "This is a repeptitive message" << endl; l1 << "This is another repeptitive message" << endl; l1 << "This is a repeptitive message" << endl; l1 << "This is another repeptitive message" << endl; l1 << "This is a repeptitive message" << endl; l1 << "This is another repeptitive message" << endl; l1 << "This is a non-repetitive message" << endl; } TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("LogStream_test_caching.txt")) } END_SECTION START_SECTION(([EXTRA] Macro test - OPENMS_LOG_FATAL_ERROR)) { // remove cout/cerr streams from the appropriate logger // and append trackable ones // NOTE: clearCache() outputs cached messages, so call it BEFORE inserting test stream ostringstream stream_by_logger; { getThreadLocalLogFatal().rdbuf()->clearCache(); // outputs to old streams, then clears getThreadLocalLogFatal().removeAllStreams(); getThreadLocalLogFatal().insert(stream_by_logger); OPENMS_LOG_FATAL_ERROR << "1\n"; OPENMS_LOG_FATAL_ERROR << "2" << endl; getThreadLocalLogFatal().remove(stream_by_logger); } StringList to_validate_list = ListUtils::create<String>(String(stream_by_logger.str()),'\n'); TEST_EQUAL(to_validate_list.size(),3) boost::regex rx(R"(.*LogStream_test\.cpp\(\d+\): \d)"); for (Size i=0;i<to_validate_list.size() - 1;++i) // there is an extra line since we ended with endl { TEST_TRUE(regex_search(to_validate_list[i], rx)) } } END_SECTION START_SECTION(([EXTRA] Macro test - OPENMS_LOG_ERROR)) { // remove cout/cerr streams from the appropriate logger // and append trackable ones // NOTE: clearCache() outputs cached messages, so call it BEFORE inserting test stream String filename; NEW_TMP_FILE(filename) ofstream s(filename.c_str(), std::ios::out); { getThreadLocalLogError().rdbuf()->clearCache(); // outputs to old streams, then clears getThreadLocalLogError().removeAllStreams(); getThreadLocalLogError().insert(s); OPENMS_LOG_ERROR << "1\n"; OPENMS_LOG_ERROR << "2" << endl; getThreadLocalLogError().remove(s); } TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("LogStream_test_general_red.txt")) } END_SECTION START_SECTION(([EXTRA] Macro test - OPENMS_LOG_WARN)) { // remove cout/cerr streams from the appropriate logger // and append trackable ones // NOTE: clearCache() outputs cached messages, so call it BEFORE inserting test stream String filename; NEW_TMP_FILE(filename) ofstream s(filename.c_str(), std::ios::out); { getThreadLocalLogWarn().rdbuf()->clearCache(); // outputs to old streams, then clears getThreadLocalLogWarn().removeAllStreams(); getThreadLocalLogWarn().insert(s); OPENMS_LOG_WARN << "1\n"; OPENMS_LOG_WARN << "2" << endl; getThreadLocalLogWarn().remove(s); } TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("LogStream_test_general_yellow.txt")) } END_SECTION START_SECTION(([EXTRA] Macro test - OPENMS_LOG_INFO)) { // remove cout/cerr streams from the appropriate logger // and append trackable ones // NOTE: clearCache() outputs cached messages, so call it BEFORE inserting test stream String filename; NEW_TMP_FILE(filename) ofstream s(filename.c_str(), std::ios::out); { getThreadLocalLogInfo().rdbuf()->clearCache(); // outputs to old streams, then clears getThreadLocalLogInfo().removeAllStreams(); getThreadLocalLogInfo().insert(s); OPENMS_LOG_INFO << "1\n"; OPENMS_LOG_INFO << "2" << endl; getThreadLocalLogInfo().remove(s); } TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("LogStream_test_general.txt")) } END_SECTION START_SECTION(([EXTRA] Macro test - OPENMS_LOG_DEBUG)) { // remove cout/cerr streams from the appropriate logger // and append trackable ones // NOTE: clearCache() outputs cached messages, so call it BEFORE inserting test stream ostringstream stream_by_logger; { getThreadLocalLogDebug().rdbuf()->clearCache(); // outputs to old streams, then clears getThreadLocalLogDebug().removeAllStreams(); getThreadLocalLogDebug().insert(stream_by_logger); OPENMS_LOG_DEBUG << "1\n"; OPENMS_LOG_DEBUG << "2" << endl; getThreadLocalLogDebug().remove(stream_by_logger); } StringList to_validate_list = ListUtils::create<String>(String(stream_by_logger.str()),'\n'); TEST_EQUAL(to_validate_list.size(), 3) boost::regex rx(R"(.*LogStream_test\.cpp\(\d+\): \d)"); for (Size i=0;i<to_validate_list.size() - 1;++i) // there is an extra line since we ended with endl { TEST_TRUE(regex_search(to_validate_list[i], rx)) } } END_SECTION START_SECTION(([EXTRA] Test caching of empty lines)) { ostringstream stream_by_logger; { LogStream l1(new LogStreamBuf()); l1.insert(stream_by_logger); l1 << "No caching for the following empty lines" << std::endl; l1 << "\n\n\n" << std::endl; } TEST_EQUAL(stream_by_logger.str(), "No caching for the following empty lines\n\n\n\n\n") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CoarseIsotopeDistribution_test.cpp
.cpp
30,238
706
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Clemens Groepl, Andreas Bertsch, Chris Bielow $ // -------------------------------------------------------------------------- // /////////////////////////// // This one is going to be tested. #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h> #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h> /////////////////////////// // More headers #include <iostream> #include <iterator> #include <utility> #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> ///////////////////////////////////////////////////////////// START_TEST(CoarseIsotopePatternGenerator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshadow" #endif using namespace OpenMS; using namespace std; IsotopeDistribution* nullPointer = nullptr; START_SECTION(CoarseIsotopePatternGenerator()) { CoarseIsotopePatternGenerator* ptr = new CoarseIsotopePatternGenerator(); Size max_isotope = ptr->getMaxIsotope(); TEST_EQUAL(max_isotope, 0) TEST_EQUAL(ptr->getRoundMasses(), false) TEST_NOT_EQUAL(ptr, nullPointer) delete ptr; } END_SECTION START_SECTION(CoarseIsotopePatternGenerator(Size max_isotope)) { CoarseIsotopePatternGenerator* ptr = new CoarseIsotopePatternGenerator(117); Size max_isotope = ptr->getMaxIsotope(); TEST_EQUAL(max_isotope, 117) TEST_EQUAL(ptr->getRoundMasses(), false) TEST_NOT_EQUAL(ptr, nullPointer) delete ptr; } END_SECTION START_SECTION(CoarseIsotopePatternGenerator(Size max_isotope, bool calc_mass)) { CoarseIsotopePatternGenerator* ptr = new CoarseIsotopePatternGenerator(117, true); Size max_isotope = ptr->getMaxIsotope(); TEST_EQUAL(max_isotope, 117) TEST_EQUAL(ptr->getRoundMasses(), true) TEST_NOT_EQUAL(ptr, nullPointer) delete ptr; } END_SECTION CoarseIsotopePatternGenerator* solver = new CoarseIsotopePatternGenerator(); START_SECTION(~CoarseIsotopePatternGenerator()) CoarseIsotopePatternGenerator* ptr = new CoarseIsotopePatternGenerator(117); delete ptr; END_SECTION START_SECTION(void setRoundMasses(bool round_masses)) { CoarseIsotopePatternGenerator solver2 = CoarseIsotopePatternGenerator(); TEST_EQUAL(solver2.getRoundMasses(), false) solver2.setRoundMasses(true); TEST_EQUAL(solver2.getRoundMasses(), true) } END_SECTION START_SECTION(bool getRoundMasses() const) NOT_TESTABLE END_SECTION START_SECTION(void setMaxIsotope(Size max_isotope)) { IsotopeDistribution iso = solver->estimateFromPeptideWeight(1234.2); TEST_EQUAL(solver->getMaxIsotope(), 0) TEST_EQUAL(iso.getContainer().size(), 317) solver->setMaxIsotope(117); TEST_EQUAL(solver->getMaxIsotope(), 117) } END_SECTION START_SECTION(Size getMaxIsotope() const) NOT_TESTABLE END_SECTION START_SECTION(IsotopeDistribution convolve_(const CoarseIsotopePatternGenerator& isotope_distribution) const) { IsotopeDistribution iso1, iso2; solver->setMaxIsotope(1); IsotopeDistribution::ContainerType result = solver->convolve(iso1.getContainer(), iso2.getContainer()); TEST_EQUAL(result.size(), 1) TEST_EQUAL(result[0].getMZ(), 0) TEST_EQUAL(result[0].getIntensity(), 1) } END_SECTION START_SECTION(( [EXTRA CH]IsotopeDistribution run(const EmpiricalFormula&) const )) { EmpiricalFormula ef ("C6H12O6"); { CoarseIsotopePatternGenerator gen(3); IsotopeDistribution id = gen.run(ef); TEST_EQUAL(id.size(), 3) TEST_REAL_SIMILAR(id[0].getMZ(), 180.063) TEST_REAL_SIMILAR(id[0].getIntensity(), 0.923456) TEST_REAL_SIMILAR(id[2].getMZ(), 182.0701) TEST_REAL_SIMILAR(id[2].getIntensity(), 0.013232) } ef.setCharge(2); { CoarseIsotopePatternGenerator gen(3); IsotopeDistribution id = gen.run(ef); TEST_EQUAL(id.size(), 3) // TEST_REAL_SIMILAR(id[0].getMZ(), 180.063) TEST_REAL_SIMILAR(id[0].getMZ(), 182.077943) TEST_REAL_SIMILAR(id[0].getIntensity(), 0.923246) TEST_REAL_SIMILAR(id[2].getMZ(), 184.0846529) TEST_REAL_SIMILAR(id[2].getIntensity(), 0.0132435) } ef.setCharge(-2); { CoarseIsotopePatternGenerator gen(3); TEST_EXCEPTION(Exception::Precondition, gen.run(ef)); // negative charge not allowed } } END_SECTION START_SECTION(CoarseIsotopePatternGenerator& convolvePow_(Size factor)) { // IsotopeDistribution iso = EmpiricalFormula("C60H97N15O19").getIsotopeDistribution(CoarseIsotopePatternGenerator()); // for(auto elem : iso.getContainer()) // { // std::cout << elem.getMZ() << " " << elem.getIntensity() << std::endl; // } EmpiricalFormula ef("C222N190O110"); IsotopeDistribution id = ef.getIsotopeDistribution(CoarseIsotopePatternGenerator(11)); IsotopeDistribution::ContainerType container; container.push_back(IsotopeDistribution::MassAbundance(7084, 0.0349429)); container.push_back(IsotopeDistribution::MassAbundance(7085, 0.109888)); container.push_back(IsotopeDistribution::MassAbundance(7086, 0.180185)); container.push_back(IsotopeDistribution::MassAbundance(7087, 0.204395)); container.push_back(IsotopeDistribution::MassAbundance(7088, 0.179765)); container.push_back(IsotopeDistribution::MassAbundance(7089, 0.130358)); container.push_back(IsotopeDistribution::MassAbundance(7090, 0.0809864)); container.push_back(IsotopeDistribution::MassAbundance(7091, 0.0442441)); container.push_back(IsotopeDistribution::MassAbundance(7092, 0.0216593)); container.push_back(IsotopeDistribution::MassAbundance(7093, 0.00963707)); container.push_back(IsotopeDistribution::MassAbundance(7094, 0.0039406)); for (Size i = 0; i != id.size(); ++i) { TEST_EQUAL(round(id.getContainer()[i].getMZ()), container[i].getMZ()) TEST_REAL_SIMILAR(id.getContainer()[i].getIntensity(), container[i].getIntensity()) } // test gapped isotope distributions, e.g. bromide 79,81 (missing 80) { EmpiricalFormula ef("Br2"); IsotopeDistribution id = ef.getIsotopeDistribution(CoarseIsotopePatternGenerator(5)); container.clear(); // the expected results as pairs of // [nominal mass, probability] // derived via convolution of elemental probabilities; the sum of all probabilities is 1 // For Br2, this is simply the product of Bromine x Bromine, which // has a light isotope (79 Da, ~50% probability) and a heavy isotope (81 Da, ~50% probability) container.push_back(IsotopeDistribution::MassAbundance(158, 0.2569476)); // 79+79, ~ 0.5 * 0.5 container.push_back(IsotopeDistribution::MassAbundance(159, 0.0)); // this mass cannot be explained by two Br atoms container.push_back(IsotopeDistribution::MassAbundance(160, 0.49990478)); // 79+81 (or 81+79), ~ 0.5 * 0.5 + 0.5 * 0.5 container.push_back(IsotopeDistribution::MassAbundance(161, 0.0)); // same as mass 159 container.push_back(IsotopeDistribution::MassAbundance(162, 0.24314761)); // 81+81, ~ 0.5 * 0.5 for (Size i = 0; i != id.size(); ++i) { TEST_EQUAL(round(id.getContainer()[i].getMZ()), container[i].getMZ()) TEST_REAL_SIMILAR(id.getContainer()[i].getIntensity(), container[i].getIntensity()) } } { // testing a formula which has more than one element (here: C and Br), since the internal computation is different // The convolution is similar to the one above, but add another convolution step with Carbon (hence the lightest mass is 12 Da heavier) EmpiricalFormula ef("CBr2"); IsotopeDistribution id = ef.getIsotopeDistribution(CoarseIsotopePatternGenerator(7)); container.clear(); container.push_back(IsotopeDistribution::MassAbundance(170, 0.254198270573)); container.push_back(IsotopeDistribution::MassAbundance(171, 0.002749339427)); container.push_back(IsotopeDistribution::MassAbundance(172, 0.494555798854)); container.push_back(IsotopeDistribution::MassAbundance(173, 0.005348981146)); container.push_back(IsotopeDistribution::MassAbundance(174, 0.240545930573)); container.push_back(IsotopeDistribution::MassAbundance(175, 0.002601679427)); for (Size i = 0; i != id.size(); ++i) { TEST_EQUAL(round(id.getContainer()[i].getMZ()), container[i].getMZ()) TEST_REAL_SIMILAR(id.getContainer()[i].getIntensity(), container[i].getIntensity()) } } } END_SECTION START_SECTION(IsotopeDistribution estimateFromWeightAndComp(double average_weight, double C, double H, double N, double O, double S, double P)) { // We are testing that the parameterized version matches the hardcoded version. IsotopeDistribution iso; IsotopeDistribution iso2; solver->setMaxIsotope(3); iso = solver->estimateFromWeightAndComp(1000.0, 4.9384, 7.7583, 1.3577, 1.4773, 0.0417, 0.0); iso2 = solver->estimateFromPeptideWeight(1000.0); TEST_EQUAL(iso.begin()->getIntensity(),iso2.begin()->getIntensity()); TEST_EQUAL(iso.begin()->getMZ(),iso2.begin()->getMZ()); } END_SECTION START_SECTION(IsotopeDitribution CoarseIsotopePatternGenerator::estimateFromPeptideWeight(double average_weight)) { // hard to test as this is an rough estimate IsotopeDistribution iso; solver->setMaxIsotope(3); iso = solver->estimateFromPeptideWeight(100.0); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.949735) TEST_REAL_SIMILAR(iso.begin()->getMZ(), 100.170); iso = solver->estimateFromPeptideWeight(1000.0); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.586906) TEST_REAL_SIMILAR(iso.begin()->getMZ(), 999.714); iso = solver->estimateFromPeptideWeight(10000.0); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.046495) TEST_REAL_SIMILAR(iso.begin()->getMZ(), 9994.041); solver->setRoundMasses(true); iso = solver->estimateFromPeptideWeight(100.0); TEST_REAL_SIMILAR(iso.begin()->getMZ(), 100); iso = solver->estimateFromPeptideWeight(1000.0); TEST_REAL_SIMILAR(iso.begin()->getMZ(), 1000); iso = solver->estimateFromPeptideWeight(10000.0); TEST_REAL_SIMILAR(iso.begin()->getMZ(), 9994); solver->setRoundMasses(false); } END_SECTION START_SECTION(IsotopeDitribution CoarseIsotopePatternGenerator::approximateFromPeptideWeight(double mass, int num_peaks)) { std::vector<float> masses_to_test = {20, 300, 1000, 2500}; for (auto mass = masses_to_test.begin(); mass != masses_to_test.end(); ++mass) { IsotopeDistribution approximation = CoarseIsotopePatternGenerator::approximateFromPeptideWeight(*mass); solver->setMaxIsotope(approximation.size()); IsotopeDistribution coarse_truth = solver->estimateFromPeptideWeight(*mass); // compute KL divergence (Sum over all x: P(x) * log(P(x) / Q(x)), where P is a distribution and Q its approximation double KL = 0; double sum = 0.0; for (UInt peak = 0; peak != approximation.size() && peak != coarse_truth.size(); ++peak) // coarse_truth.size() is 18, although approximation.size() = 20 for mass = 20 { double Px = coarse_truth[peak].getIntensity(); double Qx = approximation[peak].getIntensity(); sum += Qx; if (Px != 0) // KL is 0 for Px = 0 { KL += Px * log(Px / Qx); } } TEST_REAL_SIMILAR(sum, 1.0); TEST_EQUAL(0 < KL && KL < 0.05, true); } } END_SECTION START_SECTION(IsotopeDitribution CoarseIsotopePatternGenerator::approximateIntensities(double mass, int num_peaks)) { std::vector<Int> masses_to_test = {20, 300, 1000, 2500}; for (auto mass = masses_to_test.begin(); mass != masses_to_test.end(); ++mass) { std::vector<double> approximation = CoarseIsotopePatternGenerator::approximateIntensities(*mass); solver->setMaxIsotope(approximation.size()); IsotopeDistribution coarse_truth = solver->estimateFromPeptideWeight(*mass); // compute KL divergence (Sum over all x: P(x) * log(P(x) / Q(x)), where P is a distribution and Q its approximation double KL = 0; double sum = 0.0; for (UInt peak = 0; peak != approximation.size() && peak != coarse_truth.size(); ++peak)// coarse_truth.size() is 18, although approximation.size() = 20 for mass = 20 { double Px = coarse_truth[peak].getIntensity(); double Qx = approximation[peak]; sum += Qx; if (Px != 0)// KL is 0 for Px = 0 { KL += Px * log(Px / Qx); } } TEST_REAL_SIMILAR(sum, 1.0); TEST_EQUAL(0 < KL && KL < 0.05, true); } } END_SECTION START_SECTION(IsotopeDistribution CoarseIsotopePatternGenerator::estimateForFragmentFromPeptideWeightAndS(double average_weight_precursor, UInt S_precursor, double average_weight_fragment, UInt S_fragment, const std::vector<UInt>& precursor_isotopes)) { IsotopeDistribution iso; IsotopeDistribution iso2; std::set<UInt> precursor_isotopes; solver->setMaxIsotope(0); // We're isolating the M+2 precursor isotopes precursor_isotopes.insert(2); // These are regression tests, but the results also follow an expected pattern. // With 0 sulfurs, it should be somewhat unlikely for the fragment to be M+2. iso = solver->estimateForFragmentFromPeptideWeightAndS(200.0, 0, 100.0, 0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.rbegin()->getIntensity(), 0.355445559123552) // At such a small size, the regular averagine method should also result in 0 sulfurs. // The approximate EmpiricalFormulas should be the same, and therefore so should // their isotopic distributions. iso2 = solver->estimateForFragmentFromPeptideWeight(200.0, 100.0, precursor_isotopes); iso2.renormalize(); IsotopeDistribution::ConstIterator it1(iso.begin()), it2(iso2.begin()); for (; it1 != iso.end(); ++it1, ++it2) { TEST_EQUAL(it1->getMZ(), it2->getMZ()) TEST_REAL_SIMILAR(it2->getIntensity(), it2->getIntensity()) } // With the only sulfur being in the fragment, it's much more likely that the fragment // is M+2. iso = solver->estimateForFragmentFromPeptideWeightAndS(200.0, 1, 100.0, 1, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.rbegin()->getIntensity(), 0.900804974056174) // Both sulfurs are in the fragment, so it's even more likely for the fragment to be M+2 iso = solver->estimateForFragmentFromPeptideWeightAndS(200.0, 2, 100.0, 2, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.rbegin()->getIntensity(), 0.947862830751023) // All 3 sulfurs are in the fragment iso = solver->estimateForFragmentFromPeptideWeightAndS(200.0, 3, 100.0, 3, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.rbegin()->getIntensity(), 0.969454586761089) // Any more sulfurs while keeping the masses constant would violate the function preconditions } END_SECTION START_SECTION(IsotopeDistribution CoarseIsotopePatternGenerator::estimateFromPeptideWeightAndS(double average_weight_precursor, UInt S)) { IsotopeDistribution iso; IsotopeDistribution iso2; // These are regression tests, but the results also follow an expected pattern. // With 0 sulfurs, it should be very unlikely for this tiny peptide to be M+2. solver->setMaxIsotope(3); iso = solver->estimateFromPeptideWeightAndS(100.0, 0); iso.renormalize(); TEST_REAL_SIMILAR(iso.rbegin()->getIntensity(), 0.00290370998965918) // At such a small size, the regular averagine method should also result in 0 sulfurs. // The approximate EmpiricalFormulas should be the same, and therefore so should // their isotopic distributions. iso2 = solver->estimateFromPeptideWeightAndS(100.0, 0); iso2.renormalize(); IsotopeDistribution::ConstIterator it1(iso.begin()), it2(iso2.begin()); for (; it1 != iso.end(); ++it1, ++it2) { TEST_EQUAL(it1->getMZ(), it2->getMZ()); TEST_REAL_SIMILAR(it2->getIntensity(), it2->getIntensity()) } // With one sulfur, it's more likely that the precursor is M+2 compared to having 0 sulfurs. iso = solver->estimateFromPeptideWeightAndS(100.0, 1); iso.renormalize(); TEST_REAL_SIMILAR(iso.rbegin()->getIntensity(), 0.0439547771832361) // With two sulfurs, the M+2 isotope is more likely iso = solver->estimateFromPeptideWeightAndS(100.0, 2); iso.renormalize(); TEST_REAL_SIMILAR(iso.rbegin()->getIntensity(), 0.0804989104418586) // With three sulfurs, the M+2 isotope is even more likely iso = solver->estimateFromPeptideWeightAndS(100.0, 3); iso.renormalize(); TEST_REAL_SIMILAR(iso.rbegin()->getIntensity(), 0.117023432503842) // Any more sulfurs while keeping the masses constant would violate the function preconditions } END_SECTION START_SECTION(IsotopeDistribution estimateFromRNAWeight(double average_weight)) { // hard to test as this is an rough estimate IsotopeDistribution iso; solver->setMaxIsotope(3); iso = solver->estimateFromRNAWeight(100.0); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.958166) iso = solver->estimateFromRNAWeight(1000.0); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.668538) iso = solver->estimateFromRNAWeight(10000.0); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.080505) } END_SECTION START_SECTION(IsotopeDistribution CoarseIsotopePatternGenerator::estimateFromDNAWeight(double average_weight)) { // hard to test as this is an rough estimate IsotopeDistribution iso; solver->setMaxIsotope(3); iso = solver->estimateFromDNAWeight(100.0); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.958166) iso = solver->estimateFromDNAWeight(1000.0); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.657083) iso = solver->estimateFromDNAWeight(10000.0); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.075138) } END_SECTION START_SECTION(IsotopeDistribution estimateForFragmentFromPeptideWeight(double average_weight_precursor, double average_weight_fragment, const std::set<UInt>& precursor_isotopes)) { IsotopeDistribution iso; solver->setMaxIsotope(0); std::set<UInt> precursor_isotopes; // We're isolating the M0 and M+1 precursor isotopes precursor_isotopes.insert(0); precursor_isotopes.insert(1); // These are regression tests, but the results also follow an expected pattern. // All the fragments from the M0 precursor will also be monoisotopic, while a fragment // that is half the mass of the precursor and coming from the M+1 precursor will be // roughly 50/50 monoisotopic/M+1. // For such a small peptide, the M0 precursor isotope is much more abundant than M+1. // Therefore, it's much more likely this fragment will be monoisotopic. iso = solver->estimateForFragmentFromPeptideWeight(200.0, 100.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.954654801320083) TEST_REAL_SIMILAR(iso.begin()->getMZ(), 100.170); // This peptide is large enough that the M0 and M+1 precursors are similar in abundance. // However, since the fragment is only 1/20th the mass of the precursor, it's // much more likely for the extra neutron to be on the complementary fragment. // Therefore, it's still much more likely this fragment will be monoisotopic. iso = solver->estimateForFragmentFromPeptideWeight(2000.0, 100.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.975984866212216) // The size of the precursor should have no effect on the mass of the fragment TEST_REAL_SIMILAR(iso.begin()->getMZ(), 100.170); // Same explanation as the previous example. iso = solver->estimateForFragmentFromPeptideWeight(20000.0, 100.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.995783521351781) // Like the first example, the fragment is half the mass of the precursor so // the fragments from the M+1 precursor will be roughly 50/50 monoisotopic/M+1. // However, this time the peptide is larger than the first example, so the M0 // and M+1 precursors are also roughly 50/50 in abundance. Therefore, the // probability of the M0 fragment should be in the 75% range. // i.e. (100% * 50%) + (50% * 50%) = 75% // M0 frags due to M0 precursor^ ^M0 frags due to M+1 precursor iso = solver->estimateForFragmentFromPeptideWeight(2000.0, 1000.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.741290977639283) TEST_REAL_SIMILAR(iso.begin()->getMZ(), 999.714); // Same explanation as the second example, except now the M+1 precursor is // more abundant than the M0 precursor. But, the fragment is so small that // it's still more likely for the fragment to be monoisotopic. iso = solver->estimateForFragmentFromPeptideWeight(20000.0, 1000.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.95467154987681) // Same explanation as above. iso = solver->estimateForFragmentFromPeptideWeight(20000.0, 10000.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.542260764523188) // If the fragment is identical to the precursor, then the distribution // should be the same as if it was just a precursor that wasn't isolated. iso = solver->estimateForFragmentFromPeptideWeight(200.0, 200.0, precursor_isotopes); IsotopeDistribution iso_precursor; iso_precursor = solver->estimateFromPeptideWeight(200.0); IsotopeDistribution::ConstIterator it1(iso.begin()), it2(iso_precursor.begin()); for (; it1 != iso.end(); ++it1, ++it2) { TEST_EQUAL(it1->getMZ(), it2->getMZ()) TEST_REAL_SIMILAR(it2->getIntensity(), it2->getIntensity()) } solver->setRoundMasses(true); // Rounded masses iso = solver->estimateForFragmentFromPeptideWeight(200.0, 100.0, precursor_isotopes); TEST_EQUAL(iso.begin()->getMZ(), 100); solver->setRoundMasses(false); } END_SECTION START_SECTION(IsotopeDistribution CoarseIsotopePatternGenerator::estimateForFragmentFromDNAWeight(double average_weight_precursor, double average_weight_fragment, const std::set<UInt>& precursor_isotopes)) { IsotopeDistribution iso; solver->setMaxIsotope(0); std::set<UInt> precursor_isotopes; // We're isolating the M0 and M+1 precursor isotopes precursor_isotopes.insert(0); precursor_isotopes.insert(1); // These are regression tests, but the results also follow an expected pattern. // See the comments in estimateForFragmentFromPeptideWeight for an explanation. iso = solver->estimateForFragmentFromDNAWeight(200.0, 100.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.963845242419331) iso = solver->estimateForFragmentFromDNAWeight(2000.0, 100.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.978300783455351) iso = solver->estimateForFragmentFromDNAWeight(20000.0, 100.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.995652529512413) iso = solver->estimateForFragmentFromDNAWeight(2000.0, 1000.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.776727852910751) iso = solver->estimateForFragmentFromDNAWeight(20000.0, 1000.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.95504592203456) iso = solver->estimateForFragmentFromDNAWeight(20000.0, 10000.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.555730613643729) iso = solver->estimateForFragmentFromDNAWeight(200.0, 200.0, precursor_isotopes); IsotopeDistribution iso_precursor; solver->setMaxIsotope(2); iso_precursor = solver->estimateFromDNAWeight(200.0); IsotopeDistribution::ConstIterator it1(iso.begin()), it2(iso_precursor.begin()); for (; it1 != iso.end(); ++it1, ++it2) { TEST_EQUAL(it1->getMZ(), it2->getMZ()) TEST_REAL_SIMILAR(it2->getIntensity(), it2->getIntensity()) } } END_SECTION START_SECTION(IsotopeDistribution CoarseIsotopePatternGenerator::estimateForFragmentFromRNAWeight(double average_weight_precursor, double average_weight_fragment, const std::set<UInt>& precursor_isotopes)) { IsotopeDistribution iso; solver->setMaxIsotope(0); std::set<UInt> precursor_isotopes; // We're isolating the M0 and M+1 precursor isotopes precursor_isotopes.insert(0); precursor_isotopes.insert(1); // These are regression tests, but the results also follow an expected pattern. // See the comments in estimateForFragmentFromPeptideWeight for an explanation. iso = solver->estimateForFragmentFromRNAWeight(200.0, 100.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.963845242419331) iso = solver->estimateForFragmentFromRNAWeight(2000.0, 100.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.977854088814216) iso = solver->estimateForFragmentFromRNAWeight(20000.0, 100.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.995465661923629) iso = solver->estimateForFragmentFromRNAWeight(2000.0, 1000.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.784037437107401) iso = solver->estimateForFragmentFromRNAWeight(20000.0, 1000.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.955768644474843) iso = solver->estimateForFragmentFromRNAWeight(20000.0, 10000.0, precursor_isotopes); iso.renormalize(); TEST_REAL_SIMILAR(iso.begin()->getIntensity(), 0.558201381343203) iso = solver->estimateForFragmentFromRNAWeight(200.0, 200.0, precursor_isotopes); IsotopeDistribution iso_precursor; solver->setMaxIsotope(2); iso_precursor = solver->estimateFromRNAWeight(200.0); IsotopeDistribution::ConstIterator it1(iso.begin()), it2(iso_precursor.begin()); for (; it1 != iso.end(); ++it1, ++it2) { TEST_EQUAL(it1->getMZ(), it2->getMZ()) TEST_REAL_SIMILAR(it2->getIntensity(), it2->getIntensity()) } } END_SECTION START_SECTION(IsotopeDistribution calcFragmentIsotopeDist(const CoarseIsotopePatternGenerator & comp_fragment_isotope_distribution, const std::set<UInt>& precursor_isotopes, const double fragment_mono_mass)) { EmpiricalFormula ef_complementary_fragment = EmpiricalFormula("C2"); EmpiricalFormula ef_fragment = EmpiricalFormula("C1"); // The input to calcFragmentIsotopeDist should be isotope distributions // where the solver used atomic numbers for the mass field IsotopeDistribution iso1(ef_fragment.getIsotopeDistribution(CoarseIsotopePatternGenerator(11, true))); // fragment IsotopeDistribution iso2(ef_complementary_fragment.getIsotopeDistribution(CoarseIsotopePatternGenerator(11, true))); // complementary fragment std::set<UInt> precursor_isotopes; precursor_isotopes.insert(0); precursor_isotopes.insert(1); precursor_isotopes.insert(2); IsotopeDistribution iso3; solver->setMaxIsotope(0); iso3 = solver->calcFragmentIsotopeDist(iso1, iso2, precursor_isotopes, ef_fragment.getMonoWeight()); iso3.renormalize(); // Need the distribution with accurate masses for the next comparison // because that's what the solver used for the fragment distribution IsotopeDistribution iso1_calc_mass(ef_fragment.getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); // fragment IsotopeDistribution::ConstIterator it1(iso1_calc_mass.begin()), it2(iso3.begin()); // By isolating all the precursor isotopes, the fragment isotopic distribution of a fragment molecule // should be the same as if it was the precursor. The probabilities can be slightly different due to // numerical issues. for (; it1 != iso1_calc_mass.end(); ++it1, ++it2) { TEST_EQUAL(it1->getMZ(), it2->getMZ()) TEST_REAL_SIMILAR(it1->getIntensity(), it2->getIntensity()) } precursor_isotopes.erase(precursor_isotopes.find(2)); solver->setMaxIsotope(0); IsotopeDistribution iso4 = solver->calcFragmentIsotopeDist(iso1, iso2, precursor_isotopes, ef_fragment.getMonoWeight()); iso4.renormalize(); TEST_EQUAL(iso1_calc_mass.getContainer()[0].getMZ(), iso4.getContainer()[0].getMZ()) TEST_EQUAL(iso1_calc_mass.getContainer()[1].getMZ(), iso4.getContainer()[1].getMZ()) // Now that we're not isolating every precursor isotope, the probabilities should NOT be similar. // Since there's no TEST_REAL_NOT_SIMILAR, we test their similarity to the values they should be TEST_REAL_SIMILAR(iso1.getContainer()[0].getIntensity(), 0.989300) TEST_REAL_SIMILAR(iso1.getContainer()[1].getIntensity(), 0.010700) TEST_REAL_SIMILAR(iso4.getContainer()[0].getIntensity(), 0.989524) TEST_REAL_SIMILAR(iso4.getContainer()[1].getIntensity(), 0.010479) solver->setRoundMasses(true); IsotopeDistribution iso5 = solver->calcFragmentIsotopeDist(iso1, iso2, precursor_isotopes, ef_fragment.getMonoWeight()); double result_mass[] = { 12.0, 13.0033548378 }; double result_rounded_mass[] = { 12, 13 }; Size i = 0; // making sure that the masses are correct depending on whether we asked the IsotopeDistribution solver // to return rounded masses for (it1 = iso3.begin(), it2 = iso5.begin(); it1 != iso3.end(); ++it1, ++it2, ++i) { TEST_REAL_SIMILAR(it1->getMZ(), result_mass[i]) TEST_EQUAL(it2->getMZ(), result_rounded_mass[i]) } solver->setRoundMasses(false); } END_SECTION delete solver; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST #ifdef __clang__ #pragma clang diagnostic pop #endif
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MascotRemoteQuery_test.cpp
.cpp
1,787
74
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Andreas Bertsch, Daniel Jameson, Chris Bielow$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/MascotRemoteQuery.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MascotRemoteQuery, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MascotRemoteQuery* ptr = nullptr; MascotRemoteQuery* nullPointer = nullptr; START_SECTION(MascotRemoteQuery(QObject *parent=0)) { ptr = new MascotRemoteQuery(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~MascotRemoteQuery()) { delete ptr; } END_SECTION START_SECTION((void setQuerySpectra(const String &exp))) { MascotRemoteQuery query; query.setQuerySpectra("BEGIN IONS\n1 1\n1 1\nEND IONS"); NOT_TESTABLE } END_SECTION START_SECTION((const QByteArray& getMascotXMLResponse() const )) { MascotRemoteQuery query; TEST_EQUAL(query.getMascotXMLResponse().size(), 0) } END_SECTION START_SECTION((bool hasError() const )) { MascotRemoteQuery query; TEST_EQUAL(query.hasError(), false) } END_SECTION START_SECTION((const String& getErrorMessage() const )) { MascotRemoteQuery query; TEST_STRING_EQUAL(query.getErrorMessage(), "") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/HyperScore_test.cpp
.cpp
3,278
98
// 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, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/ANALYSIS/ID/HyperScore.h> /////////////////////////// #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> using namespace OpenMS; using namespace std; START_TEST(HyperScore, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// HyperScore* ptr = nullptr; HyperScore* null_ptr = nullptr; TheoreticalSpectrumGenerator tsg; Param param = tsg.getParameters(); param.setValue("add_metainfo", "true"); tsg.setParameters(param); START_SECTION(HyperScore()) { ptr = new HyperScore(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~HyperScore()) { delete ptr; } END_SECTION START_SECTION((static double compute(double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm, const PeakSpectrum &exp_spectrum, const RichPeakSpectrum &theo_spectrum))) { PeakSpectrum exp_spectrum; PeakSpectrum theo_spectrum; AASequence peptide = AASequence::fromString("PEPTIDE"); // empty spectrum tsg.getSpectrum(theo_spectrum, peptide, 1, 1); TEST_REAL_SIMILAR(HyperScore::compute(0.1, false, exp_spectrum, theo_spectrum), 0.0); // full match, 11 identical masses, identical intensities (=1) tsg.getSpectrum(exp_spectrum, peptide, 1, 1); TEST_REAL_SIMILAR(HyperScore::compute(0.1, false, exp_spectrum, theo_spectrum), 13.8516496); TEST_REAL_SIMILAR(HyperScore::compute(10, true, exp_spectrum, theo_spectrum), 13.8516496); exp_spectrum.clear(true); theo_spectrum.clear(true); // no match tsg.getSpectrum(exp_spectrum, peptide, 1, 3); tsg.getSpectrum(theo_spectrum, AASequence::fromString("YYYYYY"), 1, 3); TEST_REAL_SIMILAR(HyperScore::compute(1e-5, false, exp_spectrum, theo_spectrum), 0.0); exp_spectrum.clear(true); theo_spectrum.clear(true); // full match, 33 identical masses, identical intensities (=1) tsg.getSpectrum(exp_spectrum, peptide, 1, 3); tsg.getSpectrum(theo_spectrum, peptide, 1, 3); TEST_REAL_SIMILAR(HyperScore::compute(0.1, false, exp_spectrum, theo_spectrum), 67.8210771); TEST_REAL_SIMILAR(HyperScore::compute(10, true, exp_spectrum, theo_spectrum), 67.8210771); // full match if ppm tolerance and partial match for Da tolerance for (Size i = 0; i < theo_spectrum.size(); ++i) { double mz = pow( theo_spectrum[i].getMZ(), 2); exp_spectrum[i].setMZ(mz); theo_spectrum[i].setMZ(mz + 9 * 1e-6 * mz); // +9 ppm error } TEST_REAL_SIMILAR(HyperScore::compute(0.1, false, exp_spectrum, theo_spectrum), 3.401197); TEST_REAL_SIMILAR(HyperScore::compute(10, true, exp_spectrum, theo_spectrum), 67.8210771); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IonDetector_test.cpp
.cpp
9,131
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/test_config.h> /////////////////////////// #include <OpenMS/METADATA/IonDetector.h> /////////////////////////// #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; START_TEST(IonDetector, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// IonDetector* ptr = nullptr; IonDetector* nullPointer = nullptr; START_SECTION((IonDetector())) ptr = new IonDetector(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~IonDetector())) delete ptr; END_SECTION START_SECTION((Int getOrder() const)) IonDetector tmp; TEST_EQUAL(tmp.getOrder(),0) END_SECTION START_SECTION((void setOrder(Int order))) IonDetector tmp; tmp.setOrder(4711); TEST_EQUAL(tmp.getOrder(),4711) END_SECTION START_SECTION((Type getType() const)) IonDetector tmp; TEST_EQUAL(tmp.getType(),IonDetector::Type::TYPENULL); END_SECTION START_SECTION((void setType(Type type))) IonDetector tmp; tmp.setType(IonDetector::Type::ELECTRONMULTIPLIER); TEST_EQUAL(tmp.getType(),IonDetector::Type::ELECTRONMULTIPLIER); END_SECTION START_SECTION((double getADCSamplingFrequency() const )) IonDetector tmp; TEST_EQUAL(tmp.getADCSamplingFrequency(),0); END_SECTION START_SECTION((void setADCSamplingFrequency(double ADC_sampling_frequency))) IonDetector tmp; tmp.setADCSamplingFrequency(47.11); TEST_REAL_SIMILAR(tmp.getADCSamplingFrequency(),47.11); END_SECTION START_SECTION((double getResolution() const )) IonDetector tmp; TEST_EQUAL(tmp.getResolution(),0); END_SECTION START_SECTION((void setResolution(double resolution))) IonDetector tmp; tmp.setResolution(47.11); TEST_REAL_SIMILAR(tmp.getResolution(),47.11); END_SECTION START_SECTION((AcquisitionMode getAcquisitionMode() const)) IonDetector tmp; TEST_EQUAL(tmp.getAcquisitionMode(),IonDetector::AcquisitionMode::ACQMODENULL); END_SECTION START_SECTION((void setAcquisitionMode(AcquisitionMode acquisition_mode))) IonDetector tmp; tmp.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); TEST_EQUAL(tmp.getAcquisitionMode(),IonDetector::AcquisitionMode::PULSECOUNTING); END_SECTION START_SECTION((IonDetector(const IonDetector& source))) IonDetector tmp; tmp.setResolution(47.11); tmp.setADCSamplingFrequency(47.21); tmp.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); tmp.setType(IonDetector::Type::ELECTRONMULTIPLIER); tmp.setMetaValue("label",String("label")); tmp.setOrder(45); IonDetector tmp2(tmp); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_REAL_SIMILAR(tmp2.getResolution(),47.11); TEST_REAL_SIMILAR(tmp2.getADCSamplingFrequency(),47.21); TEST_EQUAL(tmp2.getAcquisitionMode(),IonDetector::AcquisitionMode::PULSECOUNTING); TEST_EQUAL(tmp2.getType(),IonDetector::Type::ELECTRONMULTIPLIER); TEST_EQUAL(tmp2.getOrder(),45) END_SECTION START_SECTION((IonDetector& operator= (const IonDetector& source))) IonDetector tmp; tmp.setResolution(47.11); tmp.setADCSamplingFrequency(47.21); tmp.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); tmp.setType(IonDetector::Type::ELECTRONMULTIPLIER); tmp.setMetaValue("label",String("label")); tmp.setOrder(45); IonDetector tmp2; tmp2 = tmp; TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_REAL_SIMILAR(tmp2.getResolution(),47.11); TEST_REAL_SIMILAR(tmp2.getADCSamplingFrequency(),47.21); TEST_EQUAL(tmp2.getAcquisitionMode(),IonDetector::AcquisitionMode::PULSECOUNTING); TEST_EQUAL(tmp2.getType(),IonDetector::Type::ELECTRONMULTIPLIER); TEST_EQUAL(tmp2.getOrder(),45) tmp2 = IonDetector(); TEST_EQUAL(tmp2.getMetaValue("label").isEmpty(), true); TEST_REAL_SIMILAR(tmp2.getResolution(),0.0); TEST_REAL_SIMILAR(tmp2.getADCSamplingFrequency(),0.0); TEST_EQUAL(tmp2.getAcquisitionMode(),IonDetector::AcquisitionMode::ACQMODENULL); TEST_EQUAL(tmp2.getType(),IonDetector::Type::TYPENULL); TEST_EQUAL(tmp2.getOrder(),0) END_SECTION START_SECTION((bool operator== (const IonDetector& rhs) const)) IonDetector edit,empty; TEST_EQUAL(edit==empty,true); edit.setResolution(47.11); TEST_EQUAL(edit==empty,false); edit = empty; edit.setADCSamplingFrequency(47.21); TEST_EQUAL(edit==empty,false); edit = empty; edit.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); TEST_EQUAL(edit==empty,false); edit = empty; edit.setType(IonDetector::Type::ELECTRONMULTIPLIER); TEST_EQUAL(edit==empty,false); edit = empty; edit.setMetaValue("label",String("label")); TEST_EQUAL(edit==empty,false); edit = empty; edit.setOrder(45); TEST_EQUAL(edit==empty,false); END_SECTION START_SECTION((bool operator!= (const IonDetector& rhs) const)) IonDetector edit,empty; TEST_EQUAL(edit!=empty,false); edit.setResolution(47.11); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setADCSamplingFrequency(47.21); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setType(IonDetector::Type::ELECTRONMULTIPLIER); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setMetaValue("label",String("label")); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setOrder(45); TEST_EQUAL(edit!=empty,true); END_SECTION START_SECTION((static StringList getAllNamesOfType())) StringList names = IonDetector::getAllNamesOfType(); TEST_EQUAL(names.size(), static_cast<size_t>(IonDetector::Type::SIZE_OF_TYPE)); TEST_EQUAL(names[static_cast<size_t>(IonDetector::Type::ELECTRONMULTIPLIER)], "Electron multiplier"); END_SECTION START_SECTION((static StringList getAllNamesOfAcquisitionMode())) StringList names = IonDetector::getAllNamesOfAcquisitionMode(); TEST_EQUAL(names.size(), static_cast<size_t>(IonDetector::AcquisitionMode::SIZE_OF_ACQUISITIONMODE)); TEST_EQUAL(names[static_cast<size_t>(IonDetector::AcquisitionMode::PULSECOUNTING)], "Pulse counting"); END_SECTION START_SECTION(([EXTRA] std::hash<IonDetector>)) { // Test that equal detectors have equal hashes IonDetector d1, d2; d1.setType(IonDetector::Type::ELECTRONMULTIPLIER); d1.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); d1.setResolution(47.11); d1.setADCSamplingFrequency(47.21); d1.setOrder(45); d2.setType(IonDetector::Type::ELECTRONMULTIPLIER); d2.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); d2.setResolution(47.11); d2.setADCSamplingFrequency(47.21); d2.setOrder(45); std::hash<IonDetector> hasher; TEST_EQUAL(hasher(d1), hasher(d2)) // Test that hash changes when values change IonDetector d3; d3.setType(IonDetector::Type::PHOTOMULTIPLIER); d3.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); d3.setResolution(47.11); d3.setADCSamplingFrequency(47.21); d3.setOrder(45); TEST_NOT_EQUAL(hasher(d1), hasher(d3)) IonDetector d4; d4.setType(IonDetector::Type::ELECTRONMULTIPLIER); d4.setAcquisitionMode(IonDetector::AcquisitionMode::ADC); d4.setResolution(47.11); d4.setADCSamplingFrequency(47.21); d4.setOrder(45); TEST_NOT_EQUAL(hasher(d1), hasher(d4)) IonDetector d5; d5.setType(IonDetector::Type::ELECTRONMULTIPLIER); d5.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); d5.setResolution(100.0); d5.setADCSamplingFrequency(47.21); d5.setOrder(45); TEST_NOT_EQUAL(hasher(d1), hasher(d5)) IonDetector d6; d6.setType(IonDetector::Type::ELECTRONMULTIPLIER); d6.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); d6.setResolution(47.11); d6.setADCSamplingFrequency(100.0); d6.setOrder(45); TEST_NOT_EQUAL(hasher(d1), hasher(d6)) IonDetector d7; d7.setType(IonDetector::Type::ELECTRONMULTIPLIER); d7.setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING); d7.setResolution(47.11); d7.setADCSamplingFrequency(47.21); d7.setOrder(100); TEST_NOT_EQUAL(hasher(d1), hasher(d7)) // Test use in unordered_set std::unordered_set<IonDetector> detector_set; detector_set.insert(d1); TEST_EQUAL(detector_set.size(), 1) detector_set.insert(d2); // same as d1 TEST_EQUAL(detector_set.size(), 1) // should not increase detector_set.insert(d3); TEST_EQUAL(detector_set.size(), 2) // Test use in unordered_map std::unordered_map<IonDetector, int> detector_map; detector_map[d1] = 42; TEST_EQUAL(detector_map[d1], 42) TEST_EQUAL(detector_map[d2], 42) // d2 == d1, should return same value } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MzTabFile_test.cpp
.cpp
4,835
165
// 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/FORMAT/MzTabFile.h> #include <OpenMS/FORMAT/MzTab.h> #include <OpenMS/FORMAT/TextFile.h> /////////////////////////// using namespace OpenMS; using namespace std; class MzTabFile2 : public MzTabFile { public: String generateMzTabPSMSectionRow2_(const MzTabPSMSectionRow& row, const vector<String>& optional_columns, const MzTabMetaData& meta) const { size_t n_columns = 0; return generateMzTabSectionRow_(row, optional_columns, meta, n_columns); } }; START_TEST(MzTabFile, "$Id$") ///////////////////////////////////////////////////////////// MzTabFile* ptr = nullptr; MzTabFile* null_ptr = nullptr; START_SECTION(MzTabFile()) { ptr = new MzTabFile(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(void load(const String& filename, MzTab& mzTab) ) MzTab mzTab; MzTabFile().load(OPENMS_GET_TEST_DATA_PATH("MzTabFile_SILAC.mzTab"), mzTab); END_SECTION START_SECTION(void store(const String& filename, MzTab& mzTab) ) { std::vector<String> files_to_test; files_to_test.push_back("MzTabFile_SILAC.mzTab"); files_to_test.push_back("MzTabFile_SILAC2.mzTab"); files_to_test.push_back("MzTabFile_labelfree.mzTab"); files_to_test.push_back("MzTabFile_iTRAQ.mzTab"); files_to_test.push_back("MzTabFile_Cytidine.mzTab"); for (std::vector<String>::const_iterator sit = files_to_test.begin(); sit != files_to_test.end(); ++sit) { // load mzTab MzTab mzTab; MzTabFile().load(OPENMS_GET_TEST_DATA_PATH(*sit), mzTab); // store mzTab String stored_mzTab; NEW_TMP_FILE(stored_mzTab) MzTabFile().store(stored_mzTab, mzTab); // compare original and stored mzTab (discarding row order and spaces) TextFile file1; TextFile file2; file1.load(stored_mzTab); file2.load(OPENMS_GET_TEST_DATA_PATH(*sit)); std::sort(file1.begin(), file1.end()); std::sort(file2.begin(), file2.end()); for (TextFile::Iterator it = file1.begin(); it != file1.end(); ++it) { it->substitute(" ",""); } for (TextFile::Iterator it = file2.begin(); it != file2.end(); ++it) { it->substitute(" ",""); } String tmpfile1; String tmpfile2; NEW_TMP_FILE(tmpfile1) NEW_TMP_FILE(tmpfile2) file1.store(tmpfile1); file2.store(tmpfile2); TEST_FILE_SIMILAR(tmpfile1.c_str(), tmpfile2.c_str()) } } END_SECTION START_SECTION(~MzTabFile()) { delete ptr; } END_SECTION START_SECTION(generateMzTabPSMSectionRow_(const MzTabPSMSectionRow& row, const vector<String>& optional_columns) const) { MzTabFile2 mzTab; MzTabPSMSectionRow row; MzTabOptionalColumnEntry e; MzTabString s; row.sequence.fromCellString("NDYKAPPQPAPGK"); row.PSM_ID.fromCellString("38"); row.accession.fromCellString("IPI:B1"); row.unique.fromCellString("1"); row.database.fromCellString("null"); row.database_version.fromCellString("null"); row.search_engine.fromCellString("[, , Percolator, ]"); row.search_engine_score[0].fromCellString("51.9678841193106"); e.first = "Percolator_score"; s.fromCellString("0.359083"); e.second = s; row.opt_.push_back(e); e.first = "Percolator_qvalue"; s.fromCellString("0.00649874"); e.second = s; row.opt_.push_back(e); e.first = "Percolator_PEP"; s.fromCellString("0.0420992"); e.second = s; row.opt_.push_back(e); e.first = "search_engine_sequence"; s.fromCellString("NDYKAPPQPAPGK"); e.second = s; row.opt_.push_back(e); // Tests /////////////////////////////// vector<String> optional_columns; optional_columns.push_back("Percolator_score"); optional_columns.push_back("Percolator_qvalue"); optional_columns.push_back("EMPTY"); optional_columns.push_back("Percolator_PEP"); optional_columns.push_back("search_engine_sequence"); optional_columns.push_back("AScore_1"); MzTabMetaData m{}; String strRow(mzTab.generateMzTabPSMSectionRow2_(row, optional_columns, m)); std::vector<String> substrings; strRow.split('\t', substrings); TEST_EQUAL(substrings[substrings.size() - 1],"null") TEST_EQUAL(substrings[substrings.size() - 2],"NDYKAPPQPAPGK") TEST_EQUAL(substrings[substrings.size() - 3],"0.0420992") TEST_EQUAL(substrings[substrings.size() - 4],"null") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/InternalCalibration_test.cpp
.cpp
8,023
197
// 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/PROCESSING/CALIBRATION/InternalCalibration.h> /////////////////////////// #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/MATH/MathFunctions.h> #include <OpenMS/SYSTEM/File.h> using namespace OpenMS; using namespace std; START_TEST(InternalCalibration, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// InternalCalibration* ptr = nullptr; InternalCalibration* nullPointer = nullptr; START_SECTION(InternalCalibration()) { ptr = new InternalCalibration(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~InternalCalibration()) { delete ptr; } END_SECTION START_SECTION(Size fillCalibrants(const PeakMap exp, const std::vector<InternalCalibration::LockMass>& ref_masses, double tol_ppm, bool lock_require_mono, bool lock_require_iso, CalibrationData& failed_lock_masses, bool verbose = true)) PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("InternalCalibration_2_lockmass.mzML.gz"), exp); std::vector<InternalCalibration::LockMass> ref_masses; ref_masses.push_back(InternalCalibration::LockMass(327.25353, 1, 1)); ref_masses.push_back(InternalCalibration::LockMass(362.29065, 1, 1)); ref_masses.push_back(InternalCalibration::LockMass(680.48022, 1, 1)); InternalCalibration ic; CalibrationData failed_locks; Size cal_count = ic.fillCalibrants(exp, ref_masses, 25.0, true, false, failed_locks, true); // no 'require_iso', since the example data has really high C13 mass error (up to 7ppm to +1 iso) TEST_EQUAL(cal_count, 21 * 3); // 21 MS1 scans, 3 calibrants each END_SECTION PeptideIdentificationList peps; std::vector<ProteinIdentification> prots; IdXMLFile().load(File::find("./examples/BSA/BSA1_OMSSA.idXML"), prots, peps); START_SECTION(Size fillCalibrants(const FeatureMap& fm, double tol_ppm)) FeatureMap fm; fm.setUnassignedPeptideIdentifications(peps); InternalCalibration ic; Size cal_count = ic.fillCalibrants(fm, 100.0); TEST_EQUAL(cal_count, 44); // all pep IDs cal_count = ic.fillCalibrants(fm, 10.0); TEST_EQUAL(cal_count, 37); // a few outliers IDs removed END_SECTION START_SECTION(Size fillCalibrants(const PeptideIdentificationList& pep_ids, double tol_ppm)) InternalCalibration ic; Size cal_count = ic.fillCalibrants(peps, 100.0); TEST_EQUAL(cal_count, 44); cal_count = ic.fillCalibrants(peps, 10.0); TEST_EQUAL(cal_count, 37); TEST_EQUAL(ic.getCalibrationPoints().size(), cal_count) END_SECTION START_SECTION(const CalibrationData& getCalibrationPoints() const) NOT_TESTABLE // tested above END_SECTION START_SECTION(bool calibrate(PeakMap& exp, const IntList& target_mslvl, MZTrafoModel::MODELTYPE model_type, double rt_chunk, bool use_RANSAC, double post_ppm_median, double post_ppm_MAD, const String& file_models, const String& file_residuals)) InternalCalibration ic; ic.fillCalibrants(peps, 3.0); PeakMap exp; MzMLFile().load(File::find("./examples/BSA/BSA1.mzML"), exp); MZTrafoModel::setRANSACSeed(0); MZTrafoModel::setRANSACParams(Math::RANSACParam(2, 1000, 1.0, 30, true)); bool success = ic.calibrate(exp, std::vector<Int>(1, 1), MZTrafoModel::MODELTYPE::LINEAR, -1, true, 1.0, 1.0); TEST_EQUAL(success, true) END_SECTION PeakMap::SpectrumType spec; spec.push_back(Peak1D(250.0, 1000.0)); spec.push_back(Peak1D(500.0, 1000.0)); spec.push_back(Peak1D(750.0, 1000.0)); spec.push_back(Peak1D(1000.0, 1000.0)); std::vector<Precursor> pcs; Precursor pc; pc.setMZ(123.0); pcs.push_back(pc); pc.setMZ(456.0); pcs.push_back(pc); spec.setPrecursors(pcs); START_SECTION(static void applyTransformation(std::vector<Precursor>& pcs, const MZTrafoModel& trafo)) MZTrafoModel trafo; trafo.setCoefficients(-100.0, 0.0, 0.0); std::vector<Precursor> pcs2 = pcs; InternalCalibration::applyTransformation(pcs2, trafo); TEST_REAL_SIMILAR(pcs2[0].getMZ(), pcs[0].getMZ() - Math::ppmToMass(-100.0, 123.0)); TEST_REAL_SIMILAR(pcs2[1].getMZ(), pcs[1].getMZ() - Math::ppmToMass(-100.0, 456.0)); //test for meta value "mz_raw" ABORT_IF(!pcs2[0].metaValueExists("mz_raw")); TEST_REAL_SIMILAR(pcs2[0].getMetaValue("mz_raw"), 123); ABORT_IF(!pcs2[1].metaValueExists("mz_raw")); TEST_REAL_SIMILAR(pcs2[1].getMetaValue("mz_raw"), 456); END_SECTION START_SECTION(static void applyTransformation(PeakMap::SpectrumType& spec, const IntList& target_mslvl, const MZTrafoModel& trafo)) MZTrafoModel trafo; trafo.setCoefficients(-100.0, 0.0, 0.0); PeakMap::SpectrumType spec2 = spec; TEST_EQUAL(spec, spec2); InternalCalibration::applyTransformation(spec2, std::vector<Int>(1, 1), trafo); TEST_NOT_EQUAL(spec, spec2); TEST_REAL_SIMILAR(spec2[0].getMZ(), spec[0].getMZ() - Math::ppmToMass(-100.0, 250.0)); TEST_REAL_SIMILAR(spec2[1].getMZ(), spec[1].getMZ() - Math::ppmToMass(-100.0, 500.0)); TEST_EQUAL(spec2.getPrecursors()[0], pcs[0]); // unchanged, since PCs belong to MS-level 0 TEST_EQUAL(spec2.getPrecursors()[1], pcs[1]); // unchanged, since PCs belong to MS-level 0 spec2 = spec; spec2.setMSLevel(2); PeakMap::SpectrumType spec2_noPC = spec2; spec2_noPC.getPrecursors().resize(0); // remove PC's InternalCalibration::applyTransformation(spec2, std::vector<Int>(1, 1), trafo); TEST_REAL_SIMILAR(spec2.getPrecursors()[0].getMZ(), pcs[0].getMZ() - Math::ppmToMass(-100.0, 123.0)); TEST_REAL_SIMILAR(spec2.getPrecursors()[1].getMZ(), pcs[1].getMZ() - Math::ppmToMass(-100.0, 456.0)); spec2.getPrecursors().resize(0); // remove PC's TEST_EQUAL(spec2_noPC, spec2); // everything else should be unchanged END_SECTION START_SECTION(static void applyTransformation(PeakMap& exp, const IntList& target_mslvl, const MZTrafoModel& trafo)) MZTrafoModel trafo; trafo.setCoefficients(-100.0, 0.0, 0.0); // observed m/z are 100ppm lower than reference PeakMap::SpectrumType spec2 = spec; spec2.setMSLevel(2); // will not be calibrated, except for its PC PeakMap exp; exp.addSpectrum(spec); exp.addSpectrum(spec2); exp.addSpectrum(spec); InternalCalibration::applyTransformation(exp, std::vector<Int>(1, 1), trafo); TEST_NOT_EQUAL(exp[0], spec); TEST_REAL_SIMILAR(exp[0][0].getMZ(), spec[0].getMZ() + Math::ppmToMass(-1 * -100.0, 250.0)); TEST_REAL_SIMILAR(exp[0][1].getMZ(), spec[1].getMZ() + Math::ppmToMass(-1 *-100.0, 500.0)); TEST_REAL_SIMILAR(spec.getPrecursors()[0].getMZ(), exp[0].getPrecursors()[0].getMZ()); TEST_REAL_SIMILAR(spec.getPrecursors()[1].getMZ(), exp[0].getPrecursors()[1].getMZ()); TEST_NOT_EQUAL(exp[1], spec2); TEST_REAL_SIMILAR(exp[1][0].getMZ(), spec2[0].getMZ()); TEST_REAL_SIMILAR(exp[1][1].getMZ(), spec2[1].getMZ()); TEST_REAL_SIMILAR(spec2.getPrecursors()[0].getMZ(), exp[1].getPrecursors()[0].getMZ() + Math::ppmToMass(-100.0, 123.0)); TEST_REAL_SIMILAR(spec2.getPrecursors()[1].getMZ(), exp[1].getPrecursors()[1].getMZ() + Math::ppmToMass(-100.0, 456.0)); TEST_NOT_EQUAL(exp[2], spec); TEST_REAL_SIMILAR(exp[2][0].getMZ(), spec[0].getMZ() + Math::ppmToMass(-1 *-100.0, 250.0)); TEST_REAL_SIMILAR(exp[2][1].getMZ(), spec[1].getMZ() + Math::ppmToMass(-1 *-100.0, 500.0)); TEST_REAL_SIMILAR(spec.getPrecursors()[0].getMZ(), exp[2].getPrecursors()[0].getMZ()); TEST_REAL_SIMILAR(spec.getPrecursors()[1].getMZ(), exp[2].getPrecursors()[1].getMZ()); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ChromatogramTools_test.cpp
.cpp
4,364
165
// 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/KERNEL/ChromatogramTools.h> #include <OpenMS/KERNEL/StandardTypes.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ChromatogramTools, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ChromatogramTools* ptr = nullptr; ChromatogramTools* nullPointer = nullptr; START_SECTION(ChromatogramTools()) { ptr = new ChromatogramTools(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~ChromatogramTools()) { delete ptr; } END_SECTION START_SECTION((ChromatogramTools(const ChromatogramTools &))) { ChromatogramTools tmp; ChromatogramTools tmp2(tmp); NOT_TESTABLE } END_SECTION START_SECTION(template <typename ExperimentType> void convertChromatogramsToSpectra(ExperimentType& exp)) { PeakMap exp; MSChromatogram chrom1, chrom2; chrom1.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); Precursor pre1, pre2; pre1.setMZ(100.1); pre2.setMZ(100.2); Product pro1, pro2; pro1.setMZ(200.1); pro2.setMZ(200.2); chrom1.setPrecursor(pre1); chrom1.setProduct(pro1); chrom2.setPrecursor(pre2); chrom2.setProduct(pro2); chrom2.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); ChromatogramPeak peak1, peak2, peak3; peak1.setRT(0.1); peak2.setRT(0.2); peak3.setRT(0.3); chrom1.push_back(peak1); chrom1.push_back(peak2); chrom2.push_back(peak2); chrom2.push_back(peak2); exp.addChromatogram(chrom1); exp.addChromatogram(chrom2); TEST_EQUAL(exp.size(), 0) TEST_EQUAL(exp.getChromatograms().size(), 2) ChromatogramTools().convertChromatogramsToSpectra(exp); TEST_EQUAL(exp.size(), 4) TEST_EQUAL(exp.getChromatograms().size(), 0) TEST_REAL_SIMILAR(exp[0][0].getMZ(), 200.1) TEST_EQUAL(exp[0].getPrecursors().size(), 1) TEST_REAL_SIMILAR(exp[0].getPrecursors().begin()->getMZ(), 100.1) } END_SECTION START_SECTION(template <typename ExperimentType> void convertSpectraToChromatograms(ExperimentType& exp, bool remove_spectra = false)) { PeakSpectrum spec1, spec2, spec3, spec4, spec5; spec1.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SRM); spec2.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SRM); spec3.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SRM); spec4.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SRM); spec5.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM); Precursor prec1, prec2; prec1.setMZ(500.1); prec2.setMZ(500.2); Peak1D p; p.setMZ(100.1); p.setIntensity(20000000); spec1.push_back(p); spec1.setRT(0.1); spec1.getPrecursors().push_back(prec1); p.setMZ(100.2); p.setIntensity(30000000); spec2.push_back(p); spec2.setRT(0.3); spec2.getPrecursors().push_back(prec2); p.setMZ(100.1); p.setIntensity(40000000); spec3.push_back(p); spec3.setRT(0.4); spec3.getPrecursors().push_back(prec1); p.setMZ(100.2); p.setIntensity(50000000); spec4.push_back(p); spec4.setRT(0.5); spec4.getPrecursors().push_back(prec2); PeakMap exp; exp.addSpectrum(spec1); exp.addSpectrum(spec2); exp.addSpectrum(spec3); exp.addSpectrum(spec4); exp.addSpectrum(spec5); PeakMap exp2 = exp; TEST_EQUAL(exp.size(), 5) TEST_EQUAL(exp.getChromatograms().size(), 0) ChromatogramTools().convertSpectraToChromatograms(exp); TEST_EQUAL(exp.size(), 5) TEST_EQUAL(exp.getChromatograms().size(), 2) TEST_EQUAL(exp2.size(), 5) TEST_EQUAL(exp2.getChromatograms().size(), 0) ChromatogramTools().convertSpectraToChromatograms(exp2, true); TEST_EQUAL(exp2.size(), 1) TEST_EQUAL(exp2.getChromatograms().size(), 2) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MRMFeatureQC_test.cpp
.cpp
1,207
46
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Douglas McCloskey $ // $Authors: Douglas McCloskey $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/KERNEL/MRMFeature.h> #include <OpenMS/KERNEL/Feature.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/FORMAT/QcMLFile.h> #include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureQC.h> using namespace OpenMS; using namespace std; START_TEST(MRMFeatureQC, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MRMFeatureQC* ptr = nullptr; MRMFeatureQC* nullPointer = nullptr; START_SECTION(MRMFeatureQC()) { ptr = new MRMFeatureQC(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~MRMFeatureQC()) { delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/HPLC_test.cpp
.cpp
5,494
231
// 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/HPLC.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(HPLC, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// HPLC* ptr = nullptr; HPLC* nullPointer = nullptr; START_SECTION(HPLC()) ptr = new HPLC(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~HPLC()) delete ptr; END_SECTION START_SECTION(Gradient& getGradient()) HPLC tmp; TEST_EQUAL(tmp.getGradient().getEluents().size(),0); END_SECTION START_SECTION(void setGradient(const Gradient& gradient)) HPLC tmp; Gradient g; g.addEluent("A"); tmp.setGradient(g); TEST_EQUAL(tmp.getGradient().getEluents().size(),1); TEST_EQUAL(tmp.getGradient().getEluents()[0],"A"); END_SECTION START_SECTION(const Gradient& getGradient() const) HPLC tmp; tmp.getGradient().addEluent("A"); TEST_EQUAL(tmp.getGradient().getEluents().size(),1); TEST_EQUAL(tmp.getGradient().getEluents()[0],"A"); END_SECTION START_SECTION(UInt getFlux() const) HPLC tmp; TEST_EQUAL(tmp.getFlux(),0); END_SECTION START_SECTION(void setFlux(UInt flux)) HPLC tmp; tmp.setFlux(5); TEST_EQUAL(tmp.getFlux(),5); END_SECTION START_SECTION(UInt getPressure() const) HPLC tmp; TEST_EQUAL(tmp.getPressure(),0); END_SECTION START_SECTION(void setPressure(UInt pressure)) HPLC tmp; tmp.setPressure(5); TEST_EQUAL(tmp.getPressure(),5); END_SECTION START_SECTION(Int getTemperature() const) HPLC tmp; TEST_EQUAL(tmp.getTemperature(),21); END_SECTION START_SECTION(void setTemperature(Int temperature)) HPLC tmp; tmp.setTemperature(5); TEST_EQUAL(tmp.getTemperature(),5); END_SECTION START_SECTION(String getComment() const) HPLC tmp; TEST_EQUAL(tmp.getComment(),""); END_SECTION START_SECTION(void setComment(String comment)) HPLC tmp; tmp.setComment("comment"); TEST_EQUAL(tmp.getComment(),"comment"); END_SECTION START_SECTION(const String& getInstrument() const) HPLC tmp; TEST_EQUAL(tmp.getInstrument(),""); END_SECTION START_SECTION(void setInstrument(const String& instrument)) HPLC tmp; tmp.setInstrument("instrument"); TEST_EQUAL(tmp.getInstrument(),"instrument"); END_SECTION START_SECTION(const String& getColumn() const) HPLC tmp; TEST_EQUAL(tmp.getColumn(),""); END_SECTION START_SECTION(void setColumn(const String& column)) HPLC tmp; tmp.setColumn("column"); TEST_EQUAL(tmp.getColumn(),"column"); END_SECTION START_SECTION(HPLC(const HPLC& source)) HPLC tmp; tmp.setInstrument("instrument"); tmp.setComment("comment"); tmp.setColumn("column"); tmp.setPressure(5); tmp.setFlux(6); tmp.setTemperature(7); HPLC tmp2(tmp); TEST_EQUAL(tmp2.getInstrument(),"instrument"); TEST_EQUAL(tmp2.getComment(),"comment"); TEST_EQUAL(tmp2.getColumn(),"column"); TEST_EQUAL(tmp2.getPressure(),5); TEST_EQUAL(tmp2.getFlux(),6); TEST_EQUAL(tmp2.getTemperature(),7); END_SECTION START_SECTION(HPLC& operator = (const HPLC& source)) HPLC tmp; tmp.setInstrument("instrument"); tmp.setComment("comment"); tmp.setColumn("column"); tmp.setPressure(5); tmp.setFlux(6); tmp.setTemperature(7); HPLC tmp2(tmp); TEST_EQUAL(tmp2.getInstrument(),"instrument"); TEST_EQUAL(tmp2.getComment(),"comment"); TEST_EQUAL(tmp2.getColumn(),"column"); TEST_EQUAL(tmp2.getPressure(),5); TEST_EQUAL(tmp2.getFlux(),6); TEST_EQUAL(tmp2.getTemperature(),7); tmp2 = HPLC(); TEST_EQUAL(tmp2.getInstrument(),""); TEST_EQUAL(tmp2.getComment(),""); TEST_EQUAL(tmp2.getColumn(),""); TEST_EQUAL(tmp2.getPressure(),0); TEST_EQUAL(tmp2.getFlux(),0); TEST_EQUAL(tmp2.getTemperature(),21); END_SECTION START_SECTION(bool operator == (const HPLC& source) const) HPLC edit, empty; TEST_EQUAL(edit==empty,true); edit.setInstrument("instrument"); TEST_EQUAL(edit==empty,false); edit = empty; edit.setComment("comment"); TEST_EQUAL(edit==empty,false); edit = empty; edit.setColumn("column"); TEST_EQUAL(edit==empty,false); edit = empty; edit.setPressure(5); TEST_EQUAL(edit==empty,false); edit = empty; edit.setFlux(6); TEST_EQUAL(edit==empty,false); edit = empty; edit.setTemperature(7); TEST_EQUAL(edit==empty,false); END_SECTION START_SECTION(bool operator != (const HPLC& source) const) HPLC edit, empty; TEST_EQUAL(edit!=empty,false); edit.setInstrument("instrument"); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setComment("comment"); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setColumn("column"); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setPressure(5); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setFlux(6); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setTemperature(7); TEST_EQUAL(edit!=empty,true); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GammaDistributionFitter_test.cpp
.cpp
4,236
113
// 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/MATH/STATISTICS/GammaDistributionFitter.h> /////////////////////////// using namespace OpenMS; using namespace Math; using namespace std; START_TEST(GammaDistributionFitter, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// GammaDistributionFitter* ptr = nullptr; GammaDistributionFitter* nullPointer = nullptr; START_SECTION(GammaDistributionFitter()) { ptr = new GammaDistributionFitter(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~GammaDistributionFitter()) { delete ptr; } END_SECTION START_SECTION((GammaDistributionFitResult fit(std::vector< DPosition< 2 > > & points))) { DPosition<2> pos; vector<DPosition<2> > points; pos.setX(0.0001); pos.setY(0.1); points.push_back(pos); pos.setX(0.0251); pos.setY(0.3); points.push_back(pos); pos.setX(0.0501); pos.setY(0); points.push_back(pos); pos.setX(0.0751); pos.setY(0.7); points.push_back(pos); pos.setX(0.1001); pos.setY(0); points.push_back(pos); pos.setX(0.1251); pos.setY(1.6); points.push_back(pos); pos.setX(0.1501); pos.setY(0); points.push_back(pos); pos.setX(0.1751); pos.setY(2.1); points.push_back(pos); pos.setX(0.2001); pos.setY(0); points.push_back(pos); pos.setX(0.2251); pos.setY(3.7); points.push_back(pos); pos.setX(0.2501); pos.setY(0); points.push_back(pos); pos.setX(0.2751); pos.setY(4); points.push_back(pos); pos.setX(0.3001); pos.setY(0); points.push_back(pos); pos.setX(0.3251); pos.setY(3); points.push_back(pos); pos.setX(0.3501); pos.setY(0); points.push_back(pos); pos.setX(0.3751); pos.setY(2.6); points.push_back(pos); pos.setX(0.4001); pos.setY(0); points.push_back(pos); pos.setX(0.4251); pos.setY(3); points.push_back(pos); pos.setX(0.4501); pos.setY(0); points.push_back(pos); pos.setX(0.4751); pos.setY(3); points.push_back(pos); pos.setX(0.5001); pos.setY(0); points.push_back(pos); pos.setX(0.5251); pos.setY(2.5); points.push_back(pos); pos.setX(0.5501); pos.setY(0); points.push_back(pos); pos.setX(0.5751); pos.setY(1.7); points.push_back(pos); pos.setX(0.6001); pos.setY(0); points.push_back(pos); pos.setX(0.6251); pos.setY(1); points.push_back(pos); pos.setX(0.6501); pos.setY(0); points.push_back(pos); pos.setX(0.6751); pos.setY(0.5); points.push_back(pos); pos.setX(0.7001); pos.setY(0); points.push_back(pos); pos.setX(0.7251); pos.setY(0.3); points.push_back(pos); pos.setX(0.7501); pos.setY(0); points.push_back(pos); pos.setX(0.7751); pos.setY(0.4); points.push_back(pos); pos.setX(0.8001); pos.setY(0); points.push_back(pos); pos.setX(0.8251); pos.setY(0); points.push_back(pos); pos.setX(0.8501); pos.setY(0); points.push_back(pos); pos.setX(0.8751); pos.setY(0.1); points.push_back(pos); pos.setX(0.9001); pos.setY(0); points.push_back(pos); pos.setX(0.9251); pos.setY(0.1); points.push_back(pos); pos.setX(0.9501); pos.setY(0); points.push_back(pos); pos.setX(0.9751); pos.setY(0.2); points.push_back(pos); GammaDistributionFitter::GammaDistributionFitResult init_param(1.0, 3.0); ptr = new GammaDistributionFitter; ptr->setInitialParameters(init_param); GammaDistributionFitter::GammaDistributionFitResult result = ptr->fit(points); TOLERANCE_ABSOLUTE(0.01) TEST_REAL_SIMILAR(result.b, 7.25) TEST_REAL_SIMILAR(result.p, 3.11) } END_SECTION START_SECTION((void setInitialParameters(const GammaDistributionFitResult & result))) { GammaDistributionFitter f1; GammaDistributionFitter::GammaDistributionFitResult result (1.0, 5.0); f1.setInitialParameters(result); NOT_TESTABLE //implicitly tested in fit method } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CachedMzMLHandler_test.cpp
.cpp
14,184
398
// 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/HANDLERS/CachedMzMLHandler.h> /////////////////////////// #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/MzMLFile.h> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshadow" #endif using namespace OpenMS; using namespace OpenMS::Internal; using namespace std; void cacheFile(CachedMzMLHandler& cache, std::string & tmp_filename, PeakMap& exp) { NEW_TMP_FILE(tmp_filename); // Load experiment MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) TEST_EQUAL(exp.getNrChromatograms() > 0, true) // Cache the experiment to a temporary file cache.writeMemdump(exp, tmp_filename); // Create the index from the given file cache.createMemdumpIndex(tmp_filename); } START_TEST(CachedMzMLHandler, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CachedMzMLHandler* ptr = nullptr; CachedMzMLHandler* nullPointer = nullptr; START_SECTION(CachedMzMLHandler()) { ptr = new CachedMzMLHandler(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~CachedMzMLHandler()) { delete ptr; } END_SECTION // see also MSDataCachedConsumer_test.cpp -> consumeSpectrum // this is a complete test of the caching object START_SECTION(( [EXTRA] testCaching)) { std::string tmp_filename; NEW_TMP_FILE(tmp_filename); // Load experiment PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) TEST_EQUAL(exp.getNrChromatograms() > 0, true) // Cache the experiment to a temporary file CachedMzMLHandler cache; cache.writeMemdump(exp, tmp_filename); // Check whether spectra were written to disk correctly... { // Create the index from the given file cache.createMemdumpIndex(tmp_filename); std::vector<std::streampos> spectra_index = cache.getSpectraIndex(); TEST_EQUAL(spectra_index.size(), 4) std::ifstream ifs_(tmp_filename.c_str(), std::ios::binary); // retrieve the spectrum (old interface) OpenSwath::BinaryDataArrayPtr mz_array(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity_array(new OpenSwath::BinaryDataArray); int ms_level = -1; double rt = -1.0; for (int i = 0; i < 4; i++) { ifs_.seekg(spectra_index[i]); CachedMzMLHandler::readSpectrumFast(mz_array, intensity_array, ifs_, ms_level, rt); TEST_EQUAL(mz_array->data.size(), exp.getSpectrum(i).size()) TEST_EQUAL(intensity_array->data.size(), exp.getSpectrum(i).size()) } // retrieve the spectrum (new interface) ms_level = -1; rt = -1.0; for (int i = 0; i < 4; i++) { ifs_.seekg(spectra_index[i]); std::vector<OpenSwath::BinaryDataArrayPtr> darray = CachedMzMLHandler::readSpectrumFast(ifs_, ms_level, rt); TEST_EQUAL(darray.size() >= 2, true) mz_array = darray[0]; intensity_array = darray[1]; TEST_EQUAL(mz_array->data.size(), exp.getSpectrum(i).size()) TEST_EQUAL(intensity_array->data.size(), exp.getSpectrum(i).size()) } // test spec 1 ifs_.seekg(spectra_index[1]); std::vector<OpenSwath::BinaryDataArrayPtr> darray = CachedMzMLHandler::readSpectrumFast(ifs_, ms_level, rt); TEST_EQUAL(darray.size(), 4) TEST_EQUAL(darray[0]->description, "") // mz TEST_EQUAL(darray[1]->description, "") // intensity TEST_EQUAL(darray[2]->description, "signal to noise array") TEST_EQUAL(darray[3]->description, "user-defined name") } // Check whether chromatograms were written to disk correctly... { // Create the index from the given file cache.createMemdumpIndex(tmp_filename); std::vector<std::streampos> chrom_index = cache.getChromatogramIndex();; TEST_EQUAL(chrom_index.size(), 2) std::ifstream ifs_(tmp_filename.c_str(), std::ios::binary); // retrieve the chromatogram OpenSwath::BinaryDataArrayPtr time_array(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity_array(new OpenSwath::BinaryDataArray); for (int i = 0; i < 2; i++) { ifs_.seekg(chrom_index[i]); CachedMzMLHandler::readChromatogramFast(time_array, intensity_array, ifs_); TEST_EQUAL(time_array->data.size(), exp.getChromatogram(i).size()) TEST_EQUAL(intensity_array->data.size(), exp.getChromatogram(i).size()) } // retrieve the chromatogram (new interface) for (int i = 0; i < 2; i++) { ifs_.seekg(chrom_index[i]); std::vector<OpenSwath::BinaryDataArrayPtr> darray = CachedMzMLHandler::readChromatogramFast(ifs_); TEST_EQUAL(darray.size() >= 2, true) time_array = darray[0]; intensity_array = darray[1]; TEST_EQUAL(time_array->data.size(), exp.getChromatogram(i).size()) TEST_EQUAL(intensity_array->data.size(), exp.getChromatogram(i).size()) } } } END_SECTION START_SECTION(( void writeMemdump(MapType& exp, String out ))) { std::string tmp_filename; NEW_TMP_FILE(tmp_filename); // Load experiment PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) TEST_EQUAL(exp.getNrChromatograms() > 0, true) // Cache the experiment to a temporary file CachedMzMLHandler cache; cache.writeMemdump(exp, tmp_filename); NOT_TESTABLE // not testable independently, see testCaching } END_SECTION START_SECTION(( void writeMetadata(MapType exp, String out_meta, bool addCacheMetaValue=false) )) { std::string tmp_filename; NEW_TMP_FILE(tmp_filename); // Load experiment PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) TEST_EQUAL(exp.getNrChromatograms() > 0, true) // Cache the experiment to a temporary file CachedMzMLHandler cache; PeakMap meta_exp; // without adding the cache value, the meta data of the two experiments should be equal cache.writeMetadata(exp, tmp_filename, false); MzMLFile().load(tmp_filename, meta_exp); TEST_EQUAL( (ExperimentalSettings)(meta_exp), (ExperimentalSettings)(exp) ) TEST_EQUAL( (SpectrumSettings)(meta_exp.getSpectrum(0)), (SpectrumSettings)(exp.getSpectrum(0)) ) TEST_EQUAL( (ChromatogramSettings)(meta_exp.getChromatogram(0)), (ChromatogramSettings)(exp.getChromatogram(0)) ) // without adding the cache value, the meta data except the "cache" meta value should be equal cache.writeMetadata(exp, tmp_filename, true); MzMLFile().load(tmp_filename, meta_exp); TEST_EQUAL( (ExperimentalSettings)(meta_exp), (ExperimentalSettings)(exp) ) } END_SECTION // Create a single CachedMzML file and use it for the following computations // (may be somewhat faster) std::string tmp_filename; PeakMap exp; CachedMzMLHandler cache_; cacheFile(cache_, tmp_filename, exp); START_SECTION(( void readMemdump(MapType& exp_reading, String filename) const )) { std::string tmp_filename; PeakMap exp; CachedMzMLHandler cache; cacheFile(cache, tmp_filename, exp); PeakMap exp_new; cache.readMemdump(exp_new, tmp_filename); TEST_EQUAL(exp_new.size(), exp.size()) TEST_EQUAL(exp_new.getChromatograms().size(), exp.getChromatograms().size()) std::string unused_tmp_filename; NEW_TMP_FILE(unused_tmp_filename); TEST_EXCEPTION(Exception::FileNotFound, cache.readMemdump(exp_new, unused_tmp_filename) ) TEST_EXCEPTION(Exception::ParseError, cache.readMemdump(exp_new, OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML") ) ) } END_SECTION START_SECTION(( void createMemdumpIndex(String filename) )) { std::string tmp_filename; NEW_TMP_FILE(tmp_filename); // Load experiment PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) // Cache the experiment to a temporary file CachedMzMLHandler cache; cache.writeMemdump(exp, tmp_filename); // create the memory dump cache.createMemdumpIndex(tmp_filename); // check whether we actually did read something TEST_EQUAL( cache.getSpectraIndex().size(), 4); TEST_EQUAL( cache.getChromatogramIndex().size(), 2); // Test error conditions std::string unused_tmp_filename; NEW_TMP_FILE(unused_tmp_filename); TEST_EXCEPTION(Exception::FileNotFound, cache.createMemdumpIndex(unused_tmp_filename) ) TEST_EXCEPTION(Exception::ParseError, cache.createMemdumpIndex(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML") ) ) } END_SECTION START_SECTION(( const std::vector<std::streampos>& getSpectraIndex() const )) { TEST_EQUAL( cache_.getSpectraIndex().size(), 4); } END_SECTION START_SECTION(( const std::vector<std::streampos>& getChromatogramIndex() const )) { TEST_EQUAL( cache_.getChromatogramIndex().size(), 2); } END_SECTION START_SECTION(static inline void readSpectrumFast(OpenSwath::BinaryDataArrayPtr data1, OpenSwath::BinaryDataArrayPtr data2, std::ifstream& ifs, int& ms_level, double& rt)) { // Check whether spectra were written to disk correctly... { // Create the index from the given file std::vector<std::streampos> spectra_index = cache_.getSpectraIndex(); TEST_EQUAL(spectra_index.size(), 4) std::ifstream ifs_(tmp_filename.c_str(), std::ios::binary); // retrieve the spectrum OpenSwath::BinaryDataArrayPtr mz_array(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity_array(new OpenSwath::BinaryDataArray); ifs_.seekg(spectra_index[0]); int ms_level = -1; double rt = -1.0; CachedMzMLHandler::readSpectrumFast(mz_array, intensity_array, ifs_, ms_level, rt); TEST_EQUAL(!mz_array->data.empty(), true) TEST_EQUAL(mz_array->data.size(), exp.getSpectrum(0).size()) TEST_EQUAL(intensity_array->data.size(), exp.getSpectrum(0).size()) TEST_EQUAL(ms_level, 1) TEST_REAL_SIMILAR(rt, 5.1) for (Size i = 0; i < mz_array->data.size(); i++) { TEST_REAL_SIMILAR(mz_array->data[i], exp.getSpectrum(0)[i].getMZ()) TEST_REAL_SIMILAR(intensity_array->data[i], exp.getSpectrum(0)[i].getIntensity()) } } // Check error conditions { // Create the index from the given file std::vector<std::streampos> spectra_index = cache_.getSpectraIndex(); TEST_EQUAL(spectra_index.size(), 4) std::ifstream ifs_(tmp_filename.c_str(), std::ios::binary); // retrieve the spectrum OpenSwath::BinaryDataArrayPtr mz_array(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity_array(new OpenSwath::BinaryDataArray); int ms_level = -1; double rt = -1.0; // should not read before the file starts ifs_.seekg( -1 ); TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, CachedMzMLHandler::readSpectrumFast(mz_array, intensity_array, ifs_, ms_level, rt), "filestream in: Read an invalid spectrum length, something is wrong here. Aborting.") // should not read after the file ends ifs_.seekg(spectra_index.back() * 20); TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, CachedMzMLHandler::readSpectrumFast(mz_array, intensity_array, ifs_, ms_level, rt), "filestream in: Read an invalid spectrum length, something is wrong here. Aborting.") } } END_SECTION START_SECTION( static inline void readChromatogramFast(OpenSwath::BinaryDataArrayPtr data1, OpenSwath::BinaryDataArrayPtr data2, std::ifstream& ifs) ) { // Check whether chromatograms were written to disk correctly... { // Create the index from the given file std::vector<std::streampos> chrom_index = cache_.getChromatogramIndex();; TEST_EQUAL(chrom_index.size(), 2) std::ifstream ifs_(tmp_filename.c_str(), std::ios::binary); // retrieve the chromatogram OpenSwath::BinaryDataArrayPtr time_array(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity_array(new OpenSwath::BinaryDataArray); ifs_.seekg(chrom_index[0]); CachedMzMLHandler::readChromatogramFast(time_array, intensity_array, ifs_); TEST_EQUAL(!time_array->data.empty(), true) TEST_EQUAL(time_array->data.size(), exp.getChromatogram(0).size()) TEST_EQUAL(intensity_array->data.size(), exp.getChromatogram(0).size()) for (Size i = 0; i < time_array->data.size(); i++) { TEST_REAL_SIMILAR(time_array->data[i], exp.getChromatogram(0)[i].getRT()) TEST_REAL_SIMILAR(intensity_array->data[i], exp.getChromatogram(0)[i].getIntensity()) } } // Check error conditions { // Create the index from the given file std::vector<std::streampos> chrom_index = cache_.getChromatogramIndex();; TEST_EQUAL(chrom_index.size(), 2) std::ifstream ifs_(tmp_filename.c_str(), std::ios::binary); // retrieve the chromatogram OpenSwath::BinaryDataArrayPtr time_array(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity_array(new OpenSwath::BinaryDataArray); // should not read before the file starts ifs_.seekg( -1 ); TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, CachedMzMLHandler::readChromatogramFast(time_array, intensity_array, ifs_), "filestream in: Read an invalid chromatogram length, something is wrong here. Aborting.") // should not read after the file ends ifs_.seekg(chrom_index.back() * 20); TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, CachedMzMLHandler::readChromatogramFast(time_array, intensity_array, ifs_), "filestream in: Read an invalid chromatogram length, something is wrong here. Aborting.") } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST #ifdef __clang__ #pragma clang diagnostic pop #endif
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DIAHelper_test.cpp
.cpp
21,074
598
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Witold Wolski, Hannes Roest $ // $Authors: Witold Wolski, Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/ANALYSIS/OPENSWATH/DIAHelper.h> #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <iterator> #include <iomanip> #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> using namespace std; using namespace OpenMS; //using namespace OpenMS::OpenSWATH; /////////////////////////// START_TEST(DIAHelper, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// OpenSwath::SpectrumPtr imSpec(new OpenSwath::Spectrum()); { OpenSwath::BinaryDataArrayPtr mass(new OpenSwath::BinaryDataArray); mass->data.push_back(100.); mass->data.push_back(101.); mass->data.push_back(102.); mass->data.push_back(103.); mass->data.push_back(104.); mass->data.push_back(105.); mass->data.push_back(106.); OpenSwath::BinaryDataArrayPtr intensity(new OpenSwath::BinaryDataArray); intensity->data.push_back(1.); intensity->data.push_back(1.); intensity->data.push_back(1.); intensity->data.push_back(1.); intensity->data.push_back(1.); intensity->data.push_back(1.); intensity->data.push_back(1.); OpenSwath::BinaryDataArrayPtr ion_mobility(new OpenSwath::BinaryDataArray); ion_mobility->data.push_back(1.); ion_mobility->data.push_back(2.); ion_mobility->data.push_back(3.); ion_mobility->data.push_back(4.); ion_mobility->data.push_back(5.); ion_mobility->data.push_back(6.); ion_mobility->data.push_back(7.); ion_mobility->description = "Ion Mobility"; imSpec->setMZArray( mass ); imSpec->setIntensityArray( intensity ); imSpec->getDataArrays().push_back( ion_mobility ); } OpenSwath::SpectrumPtr spec(new OpenSwath::Spectrum()); { OpenSwath::BinaryDataArrayPtr mass(new OpenSwath::BinaryDataArray); mass->data.push_back(100.); mass->data.push_back(101.); mass->data.push_back(102.); mass->data.push_back(103.); mass->data.push_back(104.); mass->data.push_back(105.); mass->data.push_back(106.); OpenSwath::BinaryDataArrayPtr intensity(new OpenSwath::BinaryDataArray); intensity->data.push_back(1.); intensity->data.push_back(1.); intensity->data.push_back(1.); intensity->data.push_back(1.); intensity->data.push_back(1.); intensity->data.push_back(1.); intensity->data.push_back(1.); spec->setMZArray( mass ); spec->setIntensityArray( intensity ); } START_SECTION(bool integrateWindow(const OpenSwath::SpectrumPtr& spectrum, double & mz, double & im, double & intensity, RangeMZ range_mz, RangeMobility im_range, bool centroided)) { RangeMobility empty_im_range; // empty im range for testing // IM range from 2 to 5 RangeMobility nonempty_im_range(3.5); nonempty_im_range.minSpanIfSingular(3); //Mz range from 101 to 103 RangeMZ mz_range(102.); mz_range.minSpanIfSingular(2.); // not in ppm // //mz range from 101 to 109 RangeMZ mz_range_2(105.); mz_range_2.minSpanIfSingular(8.); // not in ppm { //Test integration of empty spectrum OpenSwath::SpectrumPtr emptySpec(new OpenSwath::Spectrum()); double mz(0), intens(0), im(0); DIAHelpers::integrateWindow(emptySpec, mz, im, intens, mz_range, empty_im_range); TEST_REAL_SIMILAR(mz, -1); TEST_REAL_SIMILAR(im, -1); TEST_REAL_SIMILAR(intens, 0); } { // Test spectrum without ion mobility while asking for ion mobility filtering, should throw an exception double mz(0), intens(0), im(0); // unfortunately TEST_EXCEPTION_WITH_MESSAGE was failing for me so test without TEST_EXCEPTION(Exception::MissingInformation, DIAHelpers::integrateWindow(spec, mz, im, intens, mz_range, nonempty_im_range)); //TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, DIAHelpers::integrateWindow(spec, mz, im, intens, mz_range, nonempty_im_range), "a"); // //TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, DIAHelpers::integrateWindow(spec, mz, im, intens, mz_range, nonempty_im_range), "Cannot integrate with drift time if no drift time is available"); } { // Test ion mobility enhanced array with no ion mobility windows, although IM is present it should be ignored double mz(0), intens(0), im(0); DIAHelpers::integrateWindow(imSpec, mz, im, intens, mz_range, empty_im_range); TEST_REAL_SIMILAR (mz, 101.5); TEST_REAL_SIMILAR (intens, 2); TEST_REAL_SIMILAR (im, -1); // since no IM, this value should be -1 } { // Test With Ion Mobility (Condition 1/2) double mz(0), intens(0), im(0); DIAHelpers::integrateWindow(imSpec, mz, im, intens, mz_range_2, nonempty_im_range); TEST_REAL_SIMILAR (im, 3.5); TEST_REAL_SIMILAR (intens, 4); } { // Test with Ion Mobility (Condition 2/2) double mz(0), intens(0), im(0); DIAHelpers::integrateWindow(imSpec, mz, im, intens, mz_range, nonempty_im_range); TEST_REAL_SIMILAR (im, 2.5); TEST_REAL_SIMILAR (intens, 2); } } END_SECTION START_SECTION(bool integrateWindow(const SpectrumSequence& spectra, double & mz, double & im, double & intensity, RangeMZ mz_range, const RangeMobility& im_range, bool centroided)) { RangeMobility empty_im_range; // empty im range for testing // IM range from 2 to 5 RangeMobility nonempty_im_range(3.5); nonempty_im_range.minSpanIfSingular(3); //Mz range from 101 to 103 RangeMZ mz_range(102.); // not in ppm mz_range.minSpanIfSingular(2.); //mz range from 101 to 109 RangeMZ mz_range_2(105.); mz_range_2.minSpanIfSingular(8.); // not in ppm { // Test integration of empty array std::vector<OpenSwath::SpectrumPtr> emptySpecArr; double mz(0), intens(0), im(0); DIAHelpers::integrateWindow(emptySpecArr, mz, im, intens, mz_range, empty_im_range); TEST_REAL_SIMILAR(mz, -1); TEST_REAL_SIMILAR(im, -1); TEST_REAL_SIMILAR(intens, 0); } { //Test integration of empty spectrum OpenSwath::SpectrumPtr emptySpec(new OpenSwath::Spectrum()); std::vector<OpenSwath::SpectrumPtr> specArrEmptySpectrum; double mz(0), intens(0), im(0); specArrEmptySpectrum.push_back(emptySpec); DIAHelpers::integrateWindow(specArrEmptySpectrum, mz, im, intens, mz_range, empty_im_range); TEST_REAL_SIMILAR(mz, -1); TEST_REAL_SIMILAR(im, -1); TEST_REAL_SIMILAR(intens, 0); } { // Test ion mobility enhanced array with no ion mobility windows, although IM is present it should be ignored std::vector<OpenSwath::SpectrumPtr> specArr; double mz(0), intens(0), im(0); specArr.push_back(imSpec); DIAHelpers::integrateWindow(specArr, mz, im, intens, mz_range, empty_im_range); TEST_REAL_SIMILAR (mz, 101.5); TEST_REAL_SIMILAR (intens, 2); TEST_REAL_SIMILAR (im, -1); // since no IM, this value should be -1 } { // Test With Ion Mobility (Condition 1/2) std::vector<OpenSwath::SpectrumPtr> specArr; double mz(0), intens(0), im(0); specArr.push_back(imSpec); DIAHelpers::integrateWindow(specArr, mz, im, intens, mz_range_2, nonempty_im_range); TEST_REAL_SIMILAR (im, 3.5); TEST_REAL_SIMILAR (intens, 4); } { // Test with Ion Mobility (Condition 2/2) std::vector<OpenSwath::SpectrumPtr> specArr; double mz(0), intens(0), im(0); specArr.push_back(imSpec); DIAHelpers::integrateWindow(specArr, mz, im, intens, mz_range, nonempty_im_range); TEST_REAL_SIMILAR (im, 2.5); TEST_REAL_SIMILAR (intens, 2); } } END_SECTION START_SECTION(void integrateWindows(const OpenSwath::SpectrumPtr& spectra, const std::vector<double> & windowsCenter, double width, std::vector<double> & integratedWindowsIntensity, std::vector<double> & integratedWindowsMZ, std::vector<double> & integratedWindowsIm, const RangeMobility& im_range, bool remZero)) { RangeMobility empty_im_range; // empty im range for testing RangeMobility nonempty_im_range(3.5); nonempty_im_range.minSpanIfSingular(3); { // Test empty spectrum (with non empty windows) - remove zeros OpenSwath::SpectrumPtr emptySpec(new OpenSwath::Spectrum()); std::vector<double> windows, intInt, intMz, intIm; windows.push_back(101.); windows.push_back(103.); windows.push_back(105.); DIAHelpers::integrateWindows(emptySpec, windows, 2, intInt, intMz, intIm, empty_im_range, true); TEST_EQUAL (intInt.empty(), true); TEST_EQUAL (intIm.empty(), true); TEST_EQUAL (intMz.empty(), true); } { // Test empty spectrum (with non empty windows) - Don't remove zeros OpenSwath::SpectrumPtr emptySpec(new OpenSwath::Spectrum()); std::vector<OpenSwath::SpectrumPtr> specArr; std::vector<double> windows, intInt, intMz, intIm; windows.push_back(101.); windows.push_back(103.); windows.push_back(105.); DIAHelpers::integrateWindows(emptySpec, windows, 2, intInt, intMz, intIm, empty_im_range, false); TEST_EQUAL (intInt.size(), intMz.size() ) TEST_EQUAL (intInt.size(), intIm.size() ) TEST_EQUAL (intInt.size(), 3) TEST_REAL_SIMILAR (intInt[0], 0) TEST_REAL_SIMILAR (intInt[1], 0) TEST_REAL_SIMILAR (intInt[2], 0) TEST_REAL_SIMILAR (intMz[0], 101.) // should be middle of window TEST_REAL_SIMILAR (intMz[1], 103.) // should be middle of window TEST_REAL_SIMILAR (intMz[2], 105.) // should be middle of window TEST_REAL_SIMILAR (intIm[0], -1) // should be avg. drift TEST_REAL_SIMILAR (intIm[1], -1) // should be avg. drift TEST_REAL_SIMILAR (intIm[2], -1) // should be avg. drift } { // Test non empty spectrum with no im std::vector<double> windows, intInt, intMz, intIm; windows.push_back(101.); windows.push_back(103.); windows.push_back(105.); DIAHelpers::integrateWindows(spec, windows, 2, intInt, intMz, intIm, empty_im_range); TEST_EQUAL (intInt.size(), intMz.size() ) TEST_EQUAL (intInt.size(), intIm.size() ) TEST_EQUAL (intInt.size(), 3) TEST_REAL_SIMILAR (intInt[0], 2) TEST_REAL_SIMILAR (intMz[0], 100.5); TEST_REAL_SIMILAR (intIm[0], -1); // std::cout << "print Int" << std::endl; // std::copy(intInt.begin(), intInt.end(), // std::ostream_iterator<double>(std::cout, " ")); // std::cout << std::endl << "print mz" << intMz.size() << std::endl; // std::cout << intMz[0] << " " << intMz[1] << " " << intMz[2] << std::endl; // std::copy(intMz.begin(), intMz.end(), // std::ostream_iterator<double>(std::cout, " ")); } { // Test non empty spectrum with ion mobility std::vector<double> windows, intInt, intMz, intIm; windows.push_back(102.); DIAHelpers::integrateWindows(imSpec, windows, 2, intInt, intMz, intIm, nonempty_im_range); TEST_EQUAL (intInt.size(), intMz.size() ) TEST_EQUAL (intInt.size(), intIm.size() ) TEST_EQUAL (intInt.size(), 1) TEST_REAL_SIMILAR (intInt[0], 2) TEST_REAL_SIMILAR (intMz[0], 101.5); TEST_REAL_SIMILAR (intIm[0], 2.5); /* std::cout << "print Int" << std::endl; std::copy(intInt.begin(), intInt.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl << "print mz" << intMz.size() << std::endl; std::cout << intMz[0] << " " << intMz[1] << " " << intMz[2] << std::endl; std::copy(intMz.begin(), intMz.end(), std::ostream_iterator<double>(std::cout, " ")); */ } } END_SECTION START_SECTION(void integrateWindows(const SpectrumSequence& spectrum, const std::vector<double> & windowsCenter, double width, std::vector<double> & integratedWindowsIntensity, std::vector<double> & integratedWindowsMZ, std::vector<double> & integratedWindowsIm, const RangeMobility& im_range, bool remZero)) { RangeMobility empty_im_range; // empty im range for testing RangeMobility nonempty_im_range(3.5); nonempty_im_range.minSpanIfSingular(3); { // Test empty windows OpenSwath::SpectrumPtr emptySpec(new OpenSwath::Spectrum()); std::vector<OpenSwath::SpectrumPtr> specArr; std::vector<double> windows, intInt, intMz, intIm; specArr.push_back(emptySpec); // message test_exception not working, default to without message for now //TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, DIAHelpers::integrateWindows(specArr, windows, 2, intInt, intMz, intIm, empty_im_range), "No windows supplied!"); TEST_EXCEPTION(Exception::MissingInformation, DIAHelpers::integrateWindows(specArr, windows, 2, intInt, intMz, intIm, empty_im_range)); } { // Test empty spectrum (with non empty windows) - remove zeros OpenSwath::SpectrumPtr emptySpec(new OpenSwath::Spectrum()); std::vector<OpenSwath::SpectrumPtr> specArr; std::vector<double> windows, intInt, intMz, intIm; specArr.push_back(emptySpec); windows.push_back(101.); windows.push_back(103.); windows.push_back(105.); DIAHelpers::integrateWindows(specArr, windows, 2, intInt, intMz, intIm, nonempty_im_range, true); TEST_EQUAL (intInt.empty(), true); TEST_EQUAL (intIm.empty(), true); TEST_EQUAL (intMz.empty(), true); } { // Test empty spectrum (with non empty windows) - Don't remove zeros OpenSwath::SpectrumPtr emptySpec(new OpenSwath::Spectrum()); std::vector<OpenSwath::SpectrumPtr> specArr; std::vector<double> windows, intInt, intMz, intIm; specArr.push_back(emptySpec); windows.push_back(101.); windows.push_back(103.); windows.push_back(105.); DIAHelpers::integrateWindows(specArr, windows, 2, intInt, intMz, intIm, empty_im_range, false); TEST_EQUAL (intInt.size(), intMz.size() ) TEST_EQUAL (intInt.size(), intIm.size() ) TEST_EQUAL (intInt.size(), 3) TEST_REAL_SIMILAR (intInt[0], 0) TEST_REAL_SIMILAR (intInt[1], 0) TEST_REAL_SIMILAR (intInt[2], 0) TEST_REAL_SIMILAR (intMz[0], 101.) // should be middle of window TEST_REAL_SIMILAR (intMz[1], 103.) // should be middle of window TEST_REAL_SIMILAR (intMz[2], 105.) // should be middle of window TEST_REAL_SIMILAR (intIm[0], -1) // should be avg. drift TEST_REAL_SIMILAR (intIm[1], -1) // should be avg. drift TEST_REAL_SIMILAR (intIm[2], -1) // should be avg. drift } { // Test non empty spectrum with no im std::vector<OpenSwath::SpectrumPtr> specArr; std::vector<double> windows, intInt, intMz, intIm; windows.push_back(101.); windows.push_back(103.); windows.push_back(105.); specArr.push_back(spec); DIAHelpers::integrateWindows(specArr, windows, 2, intInt, intMz, intIm, empty_im_range); TEST_EQUAL (intInt.size(), intMz.size() ) TEST_EQUAL (intInt.size(), intIm.size() ) TEST_EQUAL (intInt.size(), 3) TEST_REAL_SIMILAR (intInt[0], 2) TEST_REAL_SIMILAR (intMz[0], 100.5); TEST_REAL_SIMILAR (intIm[0], -1); // std::cout << "print Int" << std::endl; // std::copy(intInt.begin(), intInt.end(), // std::ostream_iterator<double>(std::cout, " ")); // std::cout << std::endl << "print mz" << intMz.size() << std::endl; // std::cout << intMz[0] << " " << intMz[1] << " " << intMz[2] << std::endl; // std::copy(intMz.begin(), intMz.end(), // std::ostream_iterator<double>(std::cout, " ")); } { // Test non empty spectrum with ion mobility std::vector<OpenSwath::SpectrumPtr> specArr; std::vector<double> windows, intInt, intMz, intIm; windows.push_back(102.); specArr.push_back(imSpec); DIAHelpers::integrateWindows(specArr, windows, 2, intInt, intMz, intIm, nonempty_im_range); TEST_EQUAL (intInt.size(), intMz.size() ) TEST_EQUAL (intInt.size(), intIm.size() ) TEST_EQUAL (intInt.size(), 1) TEST_REAL_SIMILAR (intInt[0], 2) TEST_REAL_SIMILAR (intMz[0], 101.5); TEST_REAL_SIMILAR (intIm[0], 2.5); /* std::cout << "print Int" << std::endl; std::copy(intInt.begin(), intInt.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl << "print mz" << intMz.size() << std::endl; std::cout << intMz[0] << " " << intMz[1] << " " << intMz[2] << std::endl; std::copy(intMz.begin(), intMz.end(), std::ostream_iterator<double>(std::cout, " ")); */ } } END_SECTION START_SECTION([EXTRA] void adjustExtractionWindow(double& right, double& left, const double& mz_extract_window, const bool& mz_extraction_ppm)) { // test absolute { double left(500.0), right(500.0); OpenMS::DIAHelpers::adjustExtractionWindow(right, left, 0.5, false); TEST_REAL_SIMILAR(left, 500 - 0.25); TEST_REAL_SIMILAR(right, 500 + 0.25); } // test ppm { double left(500.0), right(500.0); OpenMS::DIAHelpers::adjustExtractionWindow(right, left, 10, true); TEST_REAL_SIMILAR(left, 500 - 500 * 5 /1e6); TEST_REAL_SIMILAR(right, 500 + 500 * 5 /1e6); } // test case where extraction leads to a negative number, should correct this to the 0 bounds (no ppm) // Note since this is very unlikely with ppm, this functionality is currently not implemented in ppm { double left(500.0), right(500.0); OpenMS::DIAHelpers::adjustExtractionWindow(right, left, 1000, false); TEST_REAL_SIMILAR(left, 0) TEST_REAL_SIMILAR(right, 500 + 500) } } END_SECTION START_SECTION([EXTRA] getBYSeries_test) { TheoreticalSpectrumGenerator generator; Param p; p.setValue("add_metainfo", "true", "Adds the type of peaks as metainfo to the peaks, like y8+, [M-H2O+2H]++"); generator.setParameters(p); String sequence = "SYVAWDR"; std::vector<double> bseries, yseries; OpenMS::AASequence a = OpenMS::AASequence::fromString(sequence); OpenMS::DIAHelpers::getBYSeries(a, bseries, yseries, &generator); bseries.clear(); OpenMS::DIAHelpers::getTheorMasses(a, bseries, &generator); } END_SECTION #if 0 START_SECTION([EXTRA] getAveragineIsotopeDistribution_test) { std::vector<std::pair<double, double> > tmp; OpenMS::DIAHelpers::getAveragineIsotopeDistribution(100., tmp); TEST_EQUAL(tmp.size() == 4, true); double mass1[] = { 100, 101.00048, 102.00096, 103.00144 }; double int1[] = { 0.9496341, 0.0473560, 0.0029034, 0.0001064 }; double * mm = &mass1[0]; double * ii = &int1[0]; for (unsigned int i = 0; i < tmp.size(); ++i, ++mm, ++ii) { std::cout << "mass :" << std::setprecision(10) << tmp[i].first << "intensity :" << tmp[i].second << std::endl; TEST_REAL_SIMILAR(tmp[i].first, *mm); TEST_REAL_SIMILAR(tmp[i].second, *ii); } tmp.clear(); OpenMS::DIAHelpers::getAveragineIsotopeDistribution(30., tmp); double mass2[] = { 30, 31.0005, 32.001, 33.0014 }; double int2[] = { 0.987254, 0.012721, 2.41038e-05, 2.28364e-08 }; mm = &mass2[0]; ii = &int2[0]; for (unsigned int i = 0; i < tmp.size(); ++i, ++mm, ++ii) { std::cout << "mass :" << tmp[i].first << "intensity :" << tmp[i].second << std::endl; std::cout << "mass :" << std::setprecision(10) << tmp[i].first << "intensity :" << tmp[i].second << std::endl; std::cout << i << "dm" << *mm - tmp[i].first << " di " << *ii - tmp[i].second << std::endl; TEST_REAL_SIMILAR(tmp[i].first, *mm) TEST_REAL_SIMILAR(tmp[i].second, *ii) } tmp.clear(); OpenMS::DIAHelpers::getAveragineIsotopeDistribution(110., tmp); for (unsigned int i = 0; i < tmp.size(); ++i) { std::cout << "mass :" << tmp[i].first << "intensity :" << tmp[i].second << std::endl; } tmp.clear(); OpenMS::DIAHelpers::getAveragineIsotopeDistribution(120., tmp); for (unsigned int i = 0; i < tmp.size(); ++i) { std::cout << "mass :" << tmp[i].first << "intensity :" << tmp[i].second << std::endl; } tmp.clear(); OpenMS::DIAHelpers::getAveragineIsotopeDistribution(300., tmp); for (unsigned int i = 0; i < tmp.size(); ++i) { std::cout << "mass :" << tmp[i].first << "intensity :" << tmp[i].second << std::endl; } tmp.clear(); OpenMS::DIAHelpers::getAveragineIsotopeDistribution(500., tmp); for (unsigned int i = 0; i < tmp.size(); ++i) { std::cout << "mass :" << tmp[i].first << "intensity :" << tmp[i].second << std::endl; } } END_SECTION START_SECTION([EXTRA] addIsotopesToSpec_test) { std::vector<std::pair<double, double> > tmp_, out; tmp_.push_back(std::make_pair(100., 100.)); tmp_.push_back(std::make_pair(200., 300.)); tmp_.push_back(std::make_pair(300., 200.)); OpenMS::DIAHelpers::addIsotopes2Spec(tmp_, out); std::cout << "addIsotopesToSpec_test" << std::endl; for (unsigned int i = 0; i < out.size(); ++i) { std::cout << out[i].first << " " << out[i].second << std::endl; } } END_SECTION #endif ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FastLowessSmoothing_test.cpp
.cpp
9,750
228
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Erhan Kenar, Holger Franken $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/PROCESSING/SMOOTHING/FastLowessSmoothing.h> #include <boost/random/mersenne_twister.hpp> #include <boost/random/normal_distribution.hpp> /////////////////////////// using namespace OpenMS; using namespace std; double targetFunction(double x) { return 10 + 20*x + 40*x*x; } START_TEST(FastLowessSmoothing, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION([FastLowessSmoothing_Original tests]void smoothData(const DoubleVector&, const DoubleVector&, DoubleVector&)) { /* * These are the original tests described in the FORTRAN code. We should be able to reproduce those. * * X values: * 1 2 3 4 5 (10)6 8 10 12 14 50 * * Y values: * 18 2 15 6 10 4 16 11 7 3 14 17 20 12 9 13 1 8 5 19 * * * YS values with F = .25, NSTEPS = 0, DELTA = 0.0 * 13.659 11.145 8.701 9.722 10.000 (10)11.300 13.000 6.440 5.596 * 5.456 18.998 * * YS values with F = .25, NSTEPS = 0 , DELTA = 3.0 * 13.659 12.347 11.034 9.722 10.511 (10)11.300 13.000 6.440 5.596 * 5.456 18.998 * * YS values with F = .25, NSTEPS = 2, DELTA = 0.0 * 14.811 12.115 8.984 9.676 10.000 (10)11.346 13.000 6.734 5.744 * 5.415 18.998 */ double xval[] = {1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 50 }; double yval[] = { 18, 2, 15, 6, 10, 4, 16, 11, 7, 3, 14, 17, 20, 12, 9, 13, 1, 8, 5, 19}; double ys_1[] = { 13.659, 11.145, 8.701, 9.722, 10.000, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 13.000, 6.440, 5.596, 5.456, 18.998}; double ys_2[] = {13.659, 12.347, 11.034, 9.722, 10.511, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 11.300, 13.000, 6.440, 5.596, 5.456, 18.998}; double ys_3[] = { 14.811, 12.115, 8.984, 9.676, 10.000, 11.346, 11.346, 11.346, 11.346, 11.346, 11.346, 11.346, 11.346, 11.346, 11.346, 13.000, 6.734, 5.744, 5.415, 18.998}; // the original test has limited numerical accuracy TOLERANCE_RELATIVE(1e-4); TOLERANCE_ABSOLUTE(1e-3); { std::vector< double > v_xval; std::vector< double > v_yval; for (size_t i = 0; i < 20; i++) { v_xval.push_back(xval[i]); v_yval.push_back(yval[i]); } // YS values with F = .25, NSTEPS = 0, DELTA = 0.0 { std::vector< double > out(20), tmp1(20), tmp2(20); FastLowessSmoothing::lowess(v_xval, v_yval, 0.25, 0, 0.0, out); for (size_t i = 0; i < 20; i++) { TEST_REAL_SIMILAR(out[i], ys_1[i]); } } // YS values with F = .25, NSTEPS = 0 , DELTA = 3.0 { std::vector< double > out(20), tmp1(20), tmp2(20); FastLowessSmoothing::lowess(v_xval, v_yval, 0.25, 0, 3.0, out); for (size_t i = 0; i < 20; i++) { TEST_REAL_SIMILAR(out[i], ys_2[i]); } } // YS values with F = .25, NSTEPS = 2, DELTA = 0.0 { std::vector< double > out(20), tmp1(20), tmp2(20); FastLowessSmoothing::lowess(v_xval, v_yval, 0.25, 2, 0.0, out); for (size_t i = 0; i < 20; i++) { TEST_REAL_SIMILAR(out[i], ys_3[i]); } } } } END_SECTION START_SECTION([FastLowessSmoothing_cars]void smoothData(const DoubleVector&, const DoubleVector&, DoubleVector&)) { /* In R require(graphics) plot(cars, main = "lowess(cars)") lines(lowess(cars), col = 2) lines(lowess(cars, f = .2), col = 3) legend(5, 120, c(paste("f = ", c("2/3", ".2"))), lty = 1, col = 2:3) The data below is what we expect from the R function when running the cars example. */ TOLERANCE_RELATIVE(4e-7); int speed[] = {4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16, 16, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 20, 20, 20, 20, 20, 22, 23, 24, 24, 24, 24, 25}; int dist[] = { 2, 10, 4, 22, 16, 10, 18, 26, 34, 17, 28, 14, 20, 24, 28, 26, 34, 34, 46, 26, 36, 60, 80, 20, 26, 54, 32, 40, 32, 40, 50, 42, 56, 76, 84, 36, 46, 68, 32, 48, 52, 56, 64, 66, 54, 70, 92, 93, 120, 85}; double expected_1[] = {4.965459, 4.965459, 13.124495, 13.124495, 15.858633, 18.579691, 21.280313, 21.280313, 21.280313, 24.129277, 24.129277, 27.119549, 27.119549, 27.119549, 27.119549, 30.027276, 30.027276, 30.027276, 30.027276, 32.962506, 32.962506, 32.962506, 32.962506, 36.757728, 36.757728, 36.757728, 40.435075, 40.435075, 43.463492, 43.463492, 43.463492, 46.885479, 46.885479, 46.885479, 46.885479, 50.793152, 50.793152, 50.793152, 56.491224, 56.491224, 56.491224, 56.491224, 56.491224, 67.585824, 73.079695, 78.643164, 78.643164, 78.643164, 78.643164, 84.328698}; double expected_2[] = {6.030408, 6.030408, 12.678893, 12.678893, 15.383796, 18.668847, 22.227571, 22.227571, 22.227571, 23.306483, 23.306483, 21.525372, 21.525372, 21.525372, 21.525372, 34.882735, 34.882735, 34.882735, 34.882735, 47.059947, 47.059947, 47.059947, 47.059947, 37.937118, 37.937118, 37.937118, 36.805260, 36.805260, 46.267862, 46.267862, 46.267862, 65.399825, 65.399825, 65.399825, 65.399825, 48.982482, 48.982482, 48.982482, 51.001919, 51.001919, 51.001919, 51.001919, 51.001919, 66.000000, 71.873554, 82.353574, 82.353574, 82.353574, 82.353574, 92.725141}; std::vector<double> x, y, y_noisy, out; for (Size i = 0; i < 50; i++) { x.push_back(speed[i]); y.push_back(dist[i]); } FastLowessSmoothing::lowess(x, y, out); for (Size i = 0; i < out.size(); ++i) { TEST_REAL_SIMILAR(out[i], expected_1[i]); } out.clear(); double delta = 0.01 * (x[ x.size()-1 ] - x[0]); // x is sorted FastLowessSmoothing::lowess(x, y, 0.2, 3, delta, out); for (Size i = 0; i < out.size(); ++i) { TEST_REAL_SIMILAR(out[i], expected_2[i]); } // numerical identity with the C++ function TOLERANCE_RELATIVE(4e-7); TOLERANCE_ABSOLUTE(1e-4); double expected_3[] = {4.96545927718688, 4.96545927718688, 13.1244950396665, 13.1244950396665, 15.8586333820983, 18.5796905142177, 21.2803125785285, 21.2803125785285, 21.2803125785285, 24.1292771489265, 24.1292771489265, 27.1195485506035, 27.1195485506035, 27.1195485506035, 27.1195485506035, 30.027276331154, 30.027276331154, 30.027276331154, 30.027276331154, 32.9625061361576, 32.9625061361576, 32.9625061361576, 32.9625061361576, 36.7577283416497, 36.7577283416497, 36.7577283416497, 40.4350745619887, 40.4350745619887, 43.4634917818176, 43.4634917818176, 43.4634917818176, 46.885478946024, 46.885478946024, 46.885478946024, 46.885478946024, 50.7931517254206, 50.7931517254206, 50.7931517254206, 56.4912240928772, 56.4912240928772, 56.4912240928772, 56.4912240928772, 56.4912240928772, 67.5858242314312, 73.0796952693701, 78.6431635544, 78.6431635544, 78.6431635544, 78.6431635544, 84.3286980968344}; double expected_4[] = {6.03040788454055, 6.03040788454055, 12.6788932684282, 12.6788932684282, 15.3837960614806, 18.6688467170581, 22.2275706232724, 22.2275706232724, 22.2275706232724, 23.3064828196959, 23.3064828196959, 21.52537248518, 21.52537248518, 21.52537248518, 21.52537248518, 34.8827348652577, 34.8827348652577, 34.8827348652577, 34.8827348652577, 47.0599472320042, 47.0599472320042, 47.0599472320042, 47.0599472320042, 37.9371179560115, 37.9371179560115, 37.9371179560115, 36.8052597644327, 36.8052597644327, 46.2678618410954, 46.2678618410954, 46.2678618410954, 65.3998245907766, 65.3998245907766, 65.3998245907766, 65.3998245907766, 48.9824817807382, 48.9824817807382, 48.9824817807382, 51.0019185064708, 51.0019185064708, 51.0019185064708, 51.0019185064708, 51.0019185064708, 65.9999999999999, 71.8735541744287, 82.3535742388261, 82.3535742388261, 82.3535742388261, 82.3535742388261, 92.7251407107177}; out.clear(); FastLowessSmoothing::lowess(x, y, out); for (Size i = 0; i < out.size(); ++i) { TEST_REAL_SIMILAR(out[i], expected_3[i]); } out.clear(); FastLowessSmoothing::lowess(x, y, 0.2, 3, delta, out); for (Size i = 0; i < out.size(); ++i) { TEST_REAL_SIMILAR(out[i], expected_4[i]); } } END_SECTION // trying to fit a quadratic function -> wont work so well, obviously TOLERANCE_RELATIVE(1.06); START_SECTION([FastLowessSmoothing]void smoothData(const DoubleVector&, const DoubleVector&, DoubleVector&)) { std::vector<double> x, y, y_noisy, out, expect; //exact data -> sample many points for (Size i = 1; i <= 10000; ++i) { x.push_back(i/500.0); y.push_back(targetFunction(i/500.0)); expect.push_back(targetFunction(i/500.0)); } //noisy data // make some noise boost::random::mt19937 rnd_gen_; for (Size i = 0; i < y.size(); ++i) { boost::normal_distribution<float> udist (y.at(i), 0.05); y_noisy.push_back( udist(rnd_gen_) ); } FastLowessSmoothing::lowess(x, y, 0.02, 3, 0.2, out); for (Size i = 0; i < out.size(); ++i) { TEST_REAL_SIMILAR(out[i], expect[i]); } out.clear(); FastLowessSmoothing::lowess(x, y_noisy, 0.02, 3, 0.2, out); for (Size i = 0; i < out.size(); ++i) { TEST_REAL_SIMILAR(out[i], expect[i]); } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MultiplexSatelliteProfile_test.cpp
.cpp
1,430
45
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Lars Nilse $ // $Authors: Lars Nilse $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FEATUREFINDER/MultiplexSatelliteProfile.h> using namespace OpenMS; START_TEST(MultiplexSatelliteProfile, "$Id$") MultiplexSatelliteProfile* nullPointer = nullptr; MultiplexSatelliteProfile* ptr; START_SECTION(MultiplexSatelliteProfile(double rt, double mz, double intensity)) MultiplexSatelliteProfile satellite(2565.3, 618.4, 1000.0); TEST_EQUAL(satellite.getMZ(), 618.4); ptr = new MultiplexSatelliteProfile(2565.3, 618.4, 1000.0); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION START_SECTION(size_t getMZ()) MultiplexSatelliteProfile satellite(2565.3, 618.4, 1000.0); TEST_REAL_SIMILAR(satellite.getMZ(), 618.4); END_SECTION START_SECTION(size_t getRT()) MultiplexSatelliteProfile satellite(2565.3, 618.4, 1000.0); TEST_REAL_SIMILAR(satellite.getRT(), 2565.3); END_SECTION START_SECTION(size_t getIntensity()) MultiplexSatelliteProfile satellite(2565.3, 618.4, 1000.0); TEST_REAL_SIMILAR(satellite.getIntensity(), 1000.0); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MapAlignmentAlgorithmIdentification_test.cpp
.cpp
4,664
137
// 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/ANALYSIS/MAPMATCHING/MapAlignmentAlgorithmIdentification.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <iostream> using namespace std; using namespace OpenMS; ///////////////////////////////////////////////////////////// START_TEST(MapAlignmentAlgorithmIdentification, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MapAlignmentAlgorithmIdentification* ptr = nullptr; MapAlignmentAlgorithmIdentification* nullPointer = nullptr; START_SECTION((MapAlignmentAlgorithmIdentification())) ptr = new MapAlignmentAlgorithmIdentification(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~MapAlignmentAlgorithmIdentification())) delete ptr; END_SECTION vector<PeptideIdentificationList > peptides(2); vector<ProteinIdentification> proteins; IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MapAlignmentAlgorithmIdentification_test_1.idXML"), proteins, peptides[0]); IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MapAlignmentAlgorithmIdentification_test_2.idXML"), proteins, peptides[1]); MapAlignmentAlgorithmIdentification aligner; aligner.setLogType(ProgressLogger::CMD); Param params = aligner.getParameters(); params.setValue("peptide_score_threshold", 0.0); aligner.setParameters(params); vector<double> reference_rts; // needed later START_SECTION((template <typename DataType> void align(std::vector<DataType>& data, std::vector<TransformationDescription>& transformations, Int reference_index = -1))) { // alignment without reference: vector<TransformationDescription> transforms; aligner.align(peptides, transforms); TEST_EQUAL(transforms.size(), 2); TEST_EQUAL(transforms[0].getDataPoints().size(), 10); TEST_EQUAL(transforms[1].getDataPoints().size(), 10); reference_rts.reserve(10); for (Size i = 0; i < transforms[0].getDataPoints().size(); ++i) { // both RT transforms should map to a common RT scale: TEST_REAL_SIMILAR(transforms[0].getDataPoints()[i].second, transforms[1].getDataPoints()[i].second); reference_rts.push_back(transforms[0].getDataPoints()[i].first); } // alignment with internal reference: transforms.clear(); aligner.align(peptides, transforms, 0); TEST_EQUAL(transforms.size(), 2); TEST_EQUAL(transforms[0].getModelType(), "identity"); TEST_EQUAL(transforms[1].getDataPoints().size(), 10); for (Size i = 0; i < transforms[1].getDataPoints().size(); ++i) { // RT transform should map to RT scale of the reference: TEST_REAL_SIMILAR(transforms[1].getDataPoints()[i].second, reference_rts[i]); } // algorithm works the same way for other input data types -> no extra tests } END_SECTION START_SECTION((template <typename DataType> void setReference(DataType& data))) { // alignment with external reference: aligner.setReference(peptides[0]); peptides.erase(peptides.begin()); vector<TransformationDescription> transforms; aligner.align(peptides, transforms); TEST_EQUAL(transforms.size(), 1); TEST_EQUAL(transforms[0].getDataPoints().size(), 10); for (Size i = 0; i < transforms[0].getDataPoints().size(); ++i) { // RT transform should map to RT scale of the reference: TEST_REAL_SIMILAR(transforms[0].getDataPoints()[i].second, reference_rts[i]); } } END_SECTION // can't test protected methods... // START_SECTION((void computeMedians_(SeqToList&, SeqToValue&, bool))) // { // map<String, DoubleList> seq_to_list; // map<String, double> seq_to_value; // seq_to_list["ABC"] << -1.0 << 2.5 << 0.5 << -3.5; // seq_to_list["DEF"] << 1.5 << -2.5 << -1; // computeMedians_(seq_to_list, seq_to_value, false); // TEST_EQUAL(seq_to_value.size(), 2); // TEST_EQUAL(seq_to_value["ABC"], -0.25); // TEST_EQUAL(seq_to_value["DEF"], -1); // seq_to_value.clear(); // computeMedians_(seq_to_list, seq_to_value, true); // should be sorted now // TEST_EQUAL(seq_to_value.size(), 2); // TEST_EQUAL(seq_to_value["ABC"], -0.25); // TEST_EQUAL(seq_to_value["DEF"], -1); // } // END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GaussModel_test.cpp
.cpp
5,515
207
// 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/GaussModel.h> /////////////////////////// START_TEST(GaussModel, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace OpenMS::Math; using std::stringstream; // default ctor GaussModel* ptr = nullptr; GaussModel* nullPointer = nullptr; START_SECTION((GaussModel())) ptr = new GaussModel(); TEST_EQUAL(ptr->getName(), "GaussModel") TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION // destructor START_SECTION((virtual ~GaussModel())) delete ptr; END_SECTION // assignment operator START_SECTION((virtual GaussModel& operator=(const GaussModel &source))) GaussModel gm1; BasicStatistics<> stat; stat.setMean(680.1); stat.setVariance(2.0); gm1.setScalingFactor(10.0); gm1.setInterpolationStep(0.3); Param tmp; tmp.setValue("bounding_box:min",678.9); tmp.setValue("bounding_box:max",789.0 ); tmp.setValue("statistics:variance",stat.variance() ); tmp.setValue("statistics:mean",stat.mean() ); gm1.setParameters(tmp); GaussModel gm2; gm2 = gm1; GaussModel gm3; gm3.setScalingFactor(10.0); gm3.setInterpolationStep(0.3); gm3.setParameters(tmp); gm1 = GaussModel(); TEST_EQUAL(gm3.getParameters(), gm2.getParameters()) END_SECTION // copy ctor START_SECTION((GaussModel(const GaussModel& source))) GaussModel gm1; BasicStatistics<> stat; stat.setMean(680.1); stat.setVariance(2.0); gm1.setScalingFactor(10.0); gm1.setInterpolationStep(0.3); Param tmp; tmp.setValue("bounding_box:min",678.9); tmp.setValue("bounding_box:max",789.0 ); tmp.setValue("statistics:variance",stat.variance() ); tmp.setValue("statistics:mean",stat.mean() ); gm1.setParameters(tmp); GaussModel gm2(gm1); GaussModel gm3; gm3.setScalingFactor(10.0); gm3.setInterpolationStep(0.3); gm3.setParameters(tmp); gm1 = GaussModel(); TEST_EQUAL(gm3.getParameters(), gm2.getParameters()) END_SECTION START_SECTION([EXTRA] DefaultParamHandler::setParameters(...)) TOLERANCE_ABSOLUTE(0.001) GaussModel gm1; gm1.setScalingFactor(10.0); Param tmp; tmp.setValue("bounding_box:min",678.9); tmp.setValue("bounding_box:max",789.0 ); tmp.setValue("statistics:variance",2.0); tmp.setValue("statistics:mean",679.1); gm1.setParameters(tmp); gm1.setOffset(680.0); TEST_REAL_SIMILAR(gm1.getCenter(), 680.2) GaussModel gm2; gm2.setParameters( gm1.getParameters() ); std::vector<Peak1D> dpa1; std::vector<Peak1D> dpa2; gm1.getSamples(dpa1); gm2.getSamples(dpa2); TOLERANCE_ABSOLUTE(0.0000001) TEST_EQUAL(dpa1.size(),dpa2.size()) ABORT_IF(dpa1.size()!=dpa2.size()); for (Size i=0; i<dpa1.size(); ++i) { TEST_REAL_SIMILAR(dpa1[i].getPosition()[0],dpa2[i].getPosition()[0]) TEST_REAL_SIMILAR(dpa1[i].getIntensity(),dpa2[i].getIntensity()) } END_SECTION START_SECTION(([EXTRA]void setParam(const BasicStatistics&,CoordinateType,CoordinateType))) GaussModel gm1; BasicStatistics<> stat; stat.setMean(0.0); stat.setVariance(1.0); gm1.setInterpolationStep(0.001); Param tmp; tmp.setValue("bounding_box:min",-4.0); tmp.setValue("bounding_box:max",4.0 ); tmp.setValue("statistics:variance",stat.variance() ); tmp.setValue("statistics:mean",stat.mean() ); gm1.setParameters(tmp); TEST_REAL_SIMILAR(gm1.getCenter(), 0.0) TOLERANCE_ABSOLUTE(0.001) TEST_REAL_SIMILAR(gm1.getIntensity(-1.0), 0.24197072); TEST_REAL_SIMILAR(gm1.getIntensity(0.0), 0.39894228); TEST_REAL_SIMILAR(gm1.getIntensity(1.0), 0.24197072); TEST_REAL_SIMILAR(gm1.getIntensity(2.0), 0.05399097); gm1.setInterpolationStep(0.2); gm1.setSamples(); TEST_REAL_SIMILAR(gm1.getIntensity(-1.0), 0.24197072); TEST_REAL_SIMILAR(gm1.getIntensity(0.0), 0.39894228); TEST_REAL_SIMILAR(gm1.getIntensity(1.0), 0.24197072); TEST_REAL_SIMILAR(gm1.getIntensity(2.0), 0.05399097); gm1.setScalingFactor(10.0); gm1.setSamples(); TEST_REAL_SIMILAR(gm1.getIntensity(-1.0), 2.4197072); TEST_REAL_SIMILAR(gm1.getIntensity(0.0), 3.9894228); TEST_REAL_SIMILAR(gm1.getIntensity(1.0), 2.4197072); TEST_REAL_SIMILAR(gm1.getIntensity(2.0), 0.5399097); END_SECTION START_SECTION((void setOffset(CoordinateType offset))) TOLERANCE_ABSOLUTE(0.001) GaussModel gm1; gm1.setScalingFactor(10.0); Param tmp; tmp.setValue("bounding_box:min",678.9); tmp.setValue("bounding_box:max",789.0 ); tmp.setValue("statistics:variance",2.0); tmp.setValue("statistics:mean",679.1); gm1.setParameters(tmp); gm1.setOffset(680.0); TEST_REAL_SIMILAR(gm1.getCenter(), 680.2) END_SECTION START_SECTION( CoordinateType getCenter() const ) TOLERANCE_ABSOLUTE(0.001) GaussModel gm1; gm1.setScalingFactor(10.0); Param tmp; tmp.setValue("bounding_box:min",650.0); tmp.setValue("bounding_box:max",750.0 ); tmp.setValue("statistics:variance",2.0); tmp.setValue("statistics:mean",679.1); gm1.setParameters(tmp); TEST_REAL_SIMILAR(gm1.getCenter(), 679.1) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BinaryTreeNode_test.cpp
.cpp
1,392
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/DATASTRUCTURES/BinaryTreeNode.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(BinaryTreeNode, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// BinaryTreeNode* ptr = 0; BinaryTreeNode* null_ptr = 0; START_SECTION(BinaryTreeNode()) { ptr = new BinaryTreeNode(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~BinaryTreeNode()) { delete ptr; } END_SECTION START_SECTION((BinaryTreeNode(const Size i, const Size j, const float x))) { // TODO } END_SECTION START_SECTION((~BinaryTreeNode())) { // TODO } END_SECTION START_SECTION((BinaryTreeNode(const BinaryTreeNode &source))) { // TODO } END_SECTION START_SECTION((BinaryTreeNode& operator=(const BinaryTreeNode &source))) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ItraqFourPlexQuantitationMethod_test.cpp
.cpp
4,949
169
// 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 <OpenMS/ANALYSIS/QUANTITATION/ItraqFourPlexQuantitationMethod.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/Matrix.h> using namespace OpenMS; using namespace std; START_TEST(ItraqFourPlexQuantitationMethod, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ItraqFourPlexQuantitationMethod* ptr = nullptr; ItraqFourPlexQuantitationMethod* null_ptr = nullptr; START_SECTION(ItraqFourPlexQuantitationMethod()) { ptr = new ItraqFourPlexQuantitationMethod(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~ItraqFourPlexQuantitationMethod()) { delete ptr; } END_SECTION START_SECTION((const String& getMethodName() const )) { ItraqFourPlexQuantitationMethod quant_meth; TEST_STRING_EQUAL(quant_meth.getMethodName(), "itraq4plex") } END_SECTION START_SECTION((ItraqFourPlexQuantitationMethod(const ItraqFourPlexQuantitationMethod &other))) { ItraqFourPlexQuantitationMethod qm; Param p = qm.getParameters(); p.setValue("channel_114_description", "new_description"); p.setValue("reference_channel", 116); qm.setParameters(p); ItraqFourPlexQuantitationMethod qm2(qm); IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation(); TEST_STRING_EQUAL(channel_list[0].description, "new_description") TEST_EQUAL(qm2.getReferenceChannel(), 2) } END_SECTION START_SECTION((ItraqFourPlexQuantitationMethod& operator=(const ItraqFourPlexQuantitationMethod &rhs))) { ItraqFourPlexQuantitationMethod qm; Param p = qm.getParameters(); p.setValue("channel_114_description", "new_description"); p.setValue("reference_channel", 116); qm.setParameters(p); ItraqFourPlexQuantitationMethod qm2; qm2 = qm; IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation(); TEST_STRING_EQUAL(channel_list[0].description, "new_description") TEST_EQUAL(qm2.getReferenceChannel(), 2) } END_SECTION START_SECTION((const IsobaricChannelList& getChannelInformation() const )) { ItraqFourPlexQuantitationMethod quant_meth; IsobaricQuantitationMethod::IsobaricChannelList channel_list = quant_meth.getChannelInformation(); TEST_EQUAL(channel_list.size(), 4) ABORT_IF(channel_list.size() != 4) // descriptions are empty by default TEST_STRING_EQUAL(channel_list[0].description, "") TEST_STRING_EQUAL(channel_list[1].description, "") TEST_STRING_EQUAL(channel_list[2].description, "") TEST_STRING_EQUAL(channel_list[3].description, "") // check masses&co TEST_EQUAL(channel_list[0].name, 114) TEST_EQUAL(channel_list[0].id, 0) TEST_EQUAL(channel_list[0].center, 114.1112) TEST_EQUAL(channel_list[1].name, 115) TEST_EQUAL(channel_list[1].id, 1) TEST_EQUAL(channel_list[1].center, 115.1082) TEST_EQUAL(channel_list[2].name, 116) TEST_EQUAL(channel_list[2].id, 2) TEST_EQUAL(channel_list[2].center, 116.1116) TEST_EQUAL(channel_list[3].name, 117) TEST_EQUAL(channel_list[3].id, 3) TEST_EQUAL(channel_list[3].center, 117.1149) } END_SECTION START_SECTION((Size getNumberOfChannels() const )) { ItraqFourPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getNumberOfChannels(), 4) } END_SECTION START_SECTION((virtual Matrix<double> getIsotopeCorrectionMatrix() const )) { ItraqFourPlexQuantitationMethod quant_meth; // we only check the default matrix here Matrix<double> m = quant_meth.getIsotopeCorrectionMatrix(); TEST_EQUAL(m.rows(), 4) TEST_EQUAL(m.cols(), 4) ABORT_IF(m.rows() != 4) ABORT_IF(m.cols() != 4) /** 0.929 0.02 0 0 0.059 0.923 0.03 0.001 0.002 0.056 0.924 0.04 0 0.001 0.045 0.923 */ double real_m[4][4] = {{0.929, 0.02, 0, 0}, {0.059, 0.923, 0.03, 0.001}, {0.002, 0.056, 0.924, 0.04}, {0, 0.001, 0.045, 0.923}}; for (Size i = 0; i < m.rows(); ++i) { for (Size j = 0; j < m.cols(); ++j) { TEST_REAL_SIMILAR(m(i,j), real_m[i][j]) } } } END_SECTION START_SECTION((virtual Size getReferenceChannel() const )) { ItraqFourPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getReferenceChannel(), 0) Param p; p.setValue("reference_channel",115); quant_meth.setParameters(p); TEST_EQUAL(quant_meth.getReferenceChannel(), 1) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GlobalExceptionHandler_test.cpp
.cpp
1,088
45
// 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/CONCEPT/GlobalExceptionHandler.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(GlobalExceptionHandler, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// GlobalExceptionHandler* ptr = 0; GlobalExceptionHandler* null_ptr = 0; START_SECTION(GlobalExceptionHandler()) { ptr = new GlobalExceptionHandler(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~GlobalExceptionHandler()) { delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FeatureXMLFile_test.cpp
.cpp
13,680
369
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Marc Sturm, Chris Bielow, Clemens Groepl $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/FORMAT/OPTIONS/FeatureFileOptions.h> #include <OpenMS/FORMAT/FileHandler.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> using namespace OpenMS; using namespace std; DRange<1> makeRange(double a, double b) { DPosition<1> pa(a), pb(b); return DRange<1>(pa, pb); } /////////////////////////// START_TEST(FeatureXMLFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FeatureXMLFile * ptr = nullptr; FeatureXMLFile* nullPointer = nullptr; START_SECTION((FeatureXMLFile())) { ptr = new FeatureXMLFile(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((~FeatureXMLFile())) { delete ptr; } END_SECTION START_SECTION((Size loadSize(const String &filename))) { FeatureMap e; FeatureXMLFile dfmap_file; //test exception TEST_EXCEPTION(Exception::FileNotFound, dfmap_file.loadSize("dummy/dummy.MzData")) // real test Size r = dfmap_file.loadSize(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML")); TEST_EQUAL(r, 2); // again, to test if reset internally works r = dfmap_file.loadSize(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML")); TEST_EQUAL(r, 2); } END_SECTION START_SECTION((void load(const String &filename, FeatureMap&feature_map))) { TOLERANCE_ABSOLUTE(0.01) FeatureMap e; FeatureXMLFile dfmap_file; //test exception TEST_EXCEPTION(Exception::FileNotFound, dfmap_file.load("dummy/dummy.MzData", e)) // real test dfmap_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML"), e); TEST_EQUAL(e.getIdentifier(), "lsid"); //test DocumentIdentifier addition TEST_STRING_EQUAL(e.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML")); TEST_STRING_EQUAL(FileTypes::typeToName(e.getLoadedFileType()), "featureXML"); TEST_EQUAL(e.size(), 2) TEST_REAL_SIMILAR(e[0].getRT(), 25) TEST_REAL_SIMILAR(e[0].getMZ(), 0) TEST_REAL_SIMILAR(e[0].getIntensity(), 300) TEST_EQUAL(e[0].getMetaValue("stringparametername"), "stringparametervalue") TEST_EQUAL((UInt)e[0].getMetaValue("intparametername"), 4) TEST_REAL_SIMILAR((double)e[0].getMetaValue("floatparametername"), 4.551) TEST_REAL_SIMILAR(e[1].getRT(), 0) TEST_REAL_SIMILAR(e[1].getMZ(), 35) TEST_REAL_SIMILAR(e[1].getIntensity(), 500) //data processing TEST_EQUAL(e.getDataProcessing().size(), 2) TEST_STRING_EQUAL(e.getDataProcessing()[0].getSoftware().getName(), "Software1") TEST_STRING_EQUAL(e.getDataProcessing()[0].getSoftware().getVersion(), "0.91a") TEST_EQUAL(e.getDataProcessing()[0].getProcessingActions().size(), 1) TEST_EQUAL(e.getDataProcessing()[0].getProcessingActions().count(DataProcessing::DEISOTOPING), 1) TEST_STRING_EQUAL(e.getDataProcessing()[0].getMetaValue("name"), "dataProcessing") TEST_STRING_EQUAL(e.getDataProcessing()[1].getSoftware().getName(), "Software2") TEST_STRING_EQUAL(e.getDataProcessing()[1].getSoftware().getVersion(), "0.92a") TEST_EQUAL(e.getDataProcessing()[1].getProcessingActions().size(), 2) TEST_EQUAL(e.getDataProcessing()[1].getProcessingActions().count(DataProcessing::SMOOTHING), 1) TEST_EQUAL(e.getDataProcessing()[1].getProcessingActions().count(DataProcessing::BASELINE_REDUCTION), 1) //protein identifications TEST_EQUAL(e.getProteinIdentifications().size(), 2) TEST_EQUAL(e.getProteinIdentifications()[0].getHits().size(), 2) TEST_EQUAL(e.getProteinIdentifications()[0].getHits()[0].getSequence(), "ABCDEFG") TEST_EQUAL(e.getProteinIdentifications()[0].getHits()[1].getSequence(), "HIJKLMN") TEST_EQUAL(e.getProteinIdentifications()[1].getHits().size(), 1) TEST_EQUAL(e.getProteinIdentifications()[1].getHits()[0].getSequence(), "OPQREST") //peptide identifications TEST_EQUAL(e[0].getPeptideIdentifications().size(), 2) TEST_EQUAL(e[0].getPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(e[0].getPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("A")) TEST_EQUAL(e[0].getPeptideIdentifications()[1].getHits().size(), 2) TEST_EQUAL(e[0].getPeptideIdentifications()[1].getHits()[0].getSequence(), AASequence::fromString("C")) TEST_EQUAL(e[0].getPeptideIdentifications()[1].getHits()[1].getSequence(), AASequence::fromString("D")) TEST_EQUAL(e[1].getPeptideIdentifications().size(), 1) TEST_EQUAL(e[1].getPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(e[1].getPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("E")) //unassigned peptide identifications TEST_EQUAL(e.getUnassignedPeptideIdentifications().size(), 2) TEST_EQUAL(e.getUnassignedPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(e.getUnassignedPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("F")) TEST_EQUAL(e.getUnassignedPeptideIdentifications()[1].getHits().size(), 2) TEST_EQUAL(e.getUnassignedPeptideIdentifications()[1].getHits()[0].getSequence(), AASequence::fromString("G")) TEST_EQUAL(e.getUnassignedPeptideIdentifications()[1].getHits()[1].getSequence(), AASequence::fromString("H")) // test meta values: TEST_EQUAL(e[0].getMetaValue("myIntList") == ListUtils::create<Int>("1,10,12"), true); TEST_EQUAL(e[0].getMetaValue("myDoubleList") == ListUtils::create<double>("1.111,10.999,12.45"), true); TEST_EQUAL(e[0].getMetaValue("myStringList") == ListUtils::create<String>("myABC1,Stuff,12"), true); TEST_EQUAL(e[1].getMetaValue("myDoubleList") == ListUtils::create<double>("6.442"), true); //test if loading a second file works (initialization) FeatureMap e2; dfmap_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML"), e2); std::string tmp_filename; NEW_TMP_FILE(tmp_filename); dfmap_file.store(tmp_filename, e2); TEST_FILE_SIMILAR(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML"), tmp_filename) //test of old file with mzData description (version 1.2) //here only the downward-compatibility of the new parser is tested //no exception should be thrown dfmap_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_3_old.featureXML"), e); TEST_EQUAL(e.size(), 1) //FeatureFileOptions tests dfmap_file.getOptions().setRTRange(makeRange(0, 10)); dfmap_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML"), e); TEST_EQUAL(e.size(), 1) TEST_REAL_SIMILAR(e[0].getRT(), 0) TEST_REAL_SIMILAR(e[0].getMZ(), 35) TEST_REAL_SIMILAR(e[0].getIntensity(), 500) dfmap_file.getOptions() = FeatureFileOptions(); dfmap_file.getOptions().setMZRange(makeRange(10, 50)); dfmap_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML"), e); TEST_EQUAL(e.size(), 1) TEST_REAL_SIMILAR(e[0].getRT(), 0) TEST_REAL_SIMILAR(e[0].getMZ(), 35) TEST_REAL_SIMILAR(e[0].getIntensity(), 500) dfmap_file.getOptions() = FeatureFileOptions(); dfmap_file.getOptions().setIntensityRange(makeRange(400, 600)); dfmap_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML"), e); TEST_EQUAL(e.size(), 1) TEST_REAL_SIMILAR(e[0].getRT(), 0) TEST_REAL_SIMILAR(e[0].getMZ(), 35) TEST_REAL_SIMILAR(e[0].getIntensity(), 500) { // convex hulls: dfmap_file.getOptions() = FeatureFileOptions(); FeatureMap e_full; dfmap_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), e_full); dfmap_file.getOptions().setLoadConvexHull(false); dfmap_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), e); // delete CH's manually std::vector<ConvexHull2D> empty_hull; for (Size ic = 0; ic < e_full.size(); ++ic) e_full[ic].setConvexHulls(empty_hull); e_full.updateRanges(); e.updateRanges(); TEST_EQUAL(e_full, e) } // subordinates: { dfmap_file.getOptions() = FeatureFileOptions(); FeatureMap e_full; dfmap_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), e_full); dfmap_file.getOptions().setLoadSubordinates(false); dfmap_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), e); // delete SO's manually std::vector<Feature> empty_f; for (Size ic = 0; ic < e_full.size(); ++ic) e_full[ic].setSubordinates(empty_f); TEST_EQUAL(e_full, e) } } END_SECTION START_SECTION((void store(const String &filename, const FeatureMap&feature_map))) { FeatureMap map; FeatureXMLFile f; f.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML"), map); std::string tmp_filename; NEW_TMP_FILE(tmp_filename); f.store(tmp_filename, map); WHITELIST("?xml-stylesheet") TEST_FILE_SIMILAR(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML"), tmp_filename) } END_SECTION START_SECTION((FeatureFileOptions & getOptions())) { FeatureXMLFile f; FeatureMap e; f.getOptions().setRTRange(makeRange(1.5, 4.5)); f.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), e); TEST_EQUAL(e.size(), 5) f.getOptions().setMZRange(makeRange(1025.0, 2000.0)); f.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), e); TEST_EQUAL(e.size(), 3) f.getOptions().setIntensityRange(makeRange(290.0, 310.0)); f.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), e); TEST_EQUAL(e.size(), 1) f.getOptions().setMetadataOnly(true); f.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), e); TEST_EQUAL(e.getIdentifier(), "lsid2") TEST_EQUAL(e.size(), 0) } END_SECTION START_SECTION([EXTRA] static bool isValid(const String& filename)) { FeatureXMLFile f; TEST_EQUAL(f.isValid(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML"), std::cerr), true); TEST_EQUAL(f.isValid(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), std::cerr), true); FeatureMap e; String filename; //test if empty file is valid NEW_TMP_FILE(filename) f.store(filename, e); TEST_EQUAL(f.isValid(filename, std::cerr), true); //test if full file is valid NEW_TMP_FILE(filename); f.load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML"), e); f.store(filename, e); TEST_EQUAL(f.isValid(filename, std::cerr), true); } END_SECTION START_SECTION((const FeatureFileOptions &getOptions() const)) { FeatureXMLFile f; f.getOptions().setRTRange(makeRange(1.5, 4.5)); f.getOptions().setIntensityRange(makeRange(290.0, 310.0)); const FeatureFileOptions pfo = f.getOptions(); TEST_EQUAL(pfo.getRTRange(), makeRange(1.5, 4.5)) TEST_EQUAL(pfo.getIntensityRange(), makeRange(290.0, 310.0)) } END_SECTION START_SECTION(( void setOptions(const FeatureFileOptions &) )) { FeatureXMLFile f; FeatureFileOptions pfo = f.getOptions(); pfo.setMetadataOnly(true); pfo.setLoadConvexHull(false); pfo.setRTRange(makeRange(1.5, 4.5)); pfo.setIntensityRange(makeRange(290.0, 310.0)); f.setOptions(pfo); TEST_EQUAL(pfo.getMetadataOnly(), f.getOptions().getMetadataOnly()) TEST_EQUAL(pfo.getLoadConvexHull(), f.getOptions().getLoadConvexHull()) TEST_EQUAL(pfo.getRTRange(), f.getOptions().getRTRange()) TEST_EQUAL(pfo.getIntensityRange(), f.getOptions().getIntensityRange()) } END_SECTION START_SECTION([EXTRA]) { Feature f1; f1.setRT(1001); f1.setMZ(1002); f1.setCharge(1003); Feature f1_cpy(f1); Feature f11; f11.setRT(1101); f11.setMZ(1102); Feature f12; f12.setRT(1201); f12.setMZ(1202); Feature f13; f13.setRT(1301); f13.setMZ(1302); TEST_EQUAL(f1.getSubordinates().empty(), true); f1.getSubordinates().push_back(f11); TEST_EQUAL(f1.getSubordinates().size(), 1); f1.getSubordinates().push_back(f12); TEST_EQUAL(f1.getSubordinates().size(), 2); f1.getSubordinates().push_back(f13); TEST_EQUAL(f1.getSubordinates().size(), 3); TEST_EQUAL(f1.getRT(), 1001); TEST_EQUAL(f1.getSubordinates()[0].getRT(), 1101); TEST_EQUAL(f1.getSubordinates()[1].getRT(), 1201); TEST_EQUAL(f1.getSubordinates()[2].getRT(), 1301); const Feature& f1_cref = f1; TEST_EQUAL(f1_cref.getMZ(), 1002); TEST_EQUAL(f1_cref.getSubordinates()[0].getMZ(), 1102); TEST_EQUAL(f1_cref.getSubordinates()[1].getMZ(), 1202); TEST_EQUAL(f1_cref.getSubordinates()[2].getMZ(), 1302); TEST_NOT_EQUAL(f1_cref, f1_cpy); Feature f1_cpy2(f1); TEST_EQUAL(f1_cpy2, f1); f1.getSubordinates().clear(); TEST_EQUAL(f1_cref, f1_cpy); Feature f2; f2.setRT(1001); f2.setMZ(1002); f2.setCharge(1003); TEST_NOT_EQUAL(f1_cpy2.getSubordinates().empty(), true); f2.setSubordinates(f1_cpy2.getSubordinates()); TEST_EQUAL(f2, f1_cpy2); String filename; NEW_TMP_FILE(filename); FeatureXMLFile f; FeatureMap e; e.push_back(f1); e.push_back(f2); // this will print the number of newly assigned unique ids STATUS(e.applyMemberFunction(&UniqueIdInterface::ensureUniqueId)); f.store(filename, e); FeatureMap e2; f.load(filename, e2); e.updateRanges(); TEST_TRUE(e == e2); String filename2; NEW_TMP_FILE(filename2); f.store(filename2, e2); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BaseGroupFinder_test.cpp
.cpp
1,487
60
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Clemens Groepl, Marc Sturm $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/BaseGroupFinder.h> /////////////////////////// using namespace OpenMS; using namespace std; class TestPairFinder : public BaseGroupFinder { public: TestPairFinder() : BaseGroupFinder() { check_defaults_ = false; } void run(const std::vector<ConsensusMap>&, ConsensusMap&) override { } }; START_TEST(BaseGroupFinder, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TestPairFinder* ptr = nullptr; TestPairFinder* nullPointer = nullptr; START_SECTION((BaseGroupFinder())) ptr = new TestPairFinder(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~BaseGroupFinder())) delete ptr; END_SECTION START_SECTION((virtual void run(const std::vector< ConsensusMap > &input, ConsensusMap &result)=0)) NOT_TESTABLE END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Tagger_test.cpp
.cpp
27,031
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/CHEMISTRY/Tagger.h> #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/KERNEL/MSSpectrum.h> using namespace OpenMS; START_TEST(Tagger, "$Id$") START_SECTION(void getTag(const MSSpectrum& spec, std::set<std::string>& tags)) TheoreticalSpectrumGenerator tsg; Param param = tsg.getParameters(); param.setValue("add_metainfo", "false"); param.setValue("add_first_prefix_ion", "true"); param.setValue("add_a_ions", "true"); param.setValue("add_losses", "true"); param.setValue("add_precursor_peaks", "true"); tsg.setParameters(param); // spectrum with charges +1 and +2 AASequence test_sequence = AASequence::fromString("PEPTIDETESTTHISTAGGER"); PeakSpectrum spec; tsg.getSpectrum(spec, test_sequence, 1, 2); TEST_EQUAL(spec.size(), 357); std::vector<std::string> tags; // tagger searching only for charge +1 Tagger tagger = Tagger(2, 10, 5, 1, 1); tagger.getTag(spec, tags); TEST_EQUAL(tags.size(), 890); // first aa in prefixes is not recognized yet, unless as false positive TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPT") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPTI") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "EPTID") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PTIDE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TIDET") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "IDETE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "DETES") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ETEST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TESTT") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ESTTH") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STTHI") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TTHIS") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "THIST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "HISTA") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ISTAG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STAGG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TAGGE") != tags.end(), true) // last aa in suffixes is not recognized yet, unless as false positive TEST_EQUAL(std::find(tags.begin(), tags.end(), "AGGER") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GGER") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GER") != tags.end(), false) // tagger searching only for charge +2 Tagger tagger2 = Tagger(2, 10, 5, 2, 2); tags.clear(); tagger2.getTag(spec, tags); TEST_EQUAL(tags.size(), 1006); TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPT") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPTI") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "EPTID") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PTIDE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TIDET") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "IDETE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "DETES") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ETEST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TESTT") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ESTTH") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STTHI") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TTHIS") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "THIST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "HISTA") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ISTAG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STAGG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TAGGE") != tags.end(), true) // these are found as false positives with charge +2, in a +1 and +2 spectrum TEST_EQUAL(std::find(tags.begin(), tags.end(), "AGGER") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GGER") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GER") != tags.end(), true) // tagger searching for charges +1 and +2 Tagger tagger3 = Tagger(2, 10, 5, 1, 2); tags.clear(); tagger3.getTag(spec, tags); TEST_EQUAL(tags.size(), 1094); TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPT") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPTI") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "EPTID") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PTIDE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TIDET") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "IDETE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "DETES") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ETEST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TESTT") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ESTTH") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STTHI") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TTHIS") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "THIST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "HISTA") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ISTAG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STAGG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TAGGE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "AGGER") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GGER") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GER") != tags.end(), true) // spectrum with charges +1 and +2 AASequence test_sequence2 = AASequence::fromString("PEPTID(Oxidation)ETESTTHISTAGGER"); PeakSpectrum spec2; tsg.getSpectrum(spec2, test_sequence2, 2, 2); TEST_EQUAL(spec2.size(), 180); tags.clear(); tagger3.getTag(spec2, tags); TEST_EQUAL(tags.size(), 545); TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPT") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPTI") != tags.end(), false) // not found due to modification TEST_EQUAL(std::find(tags.begin(), tags.end(), "EPTID") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PTIDE") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TIDET") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "IDETE") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "DETES") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ETEST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TESTT") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ESTTH") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STTHI") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TTHIS") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "THIST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "HISTA") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ISTAG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STAGG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TAGGE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "AGGER") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GGER") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GER") != tags.end(), true) // tagger searching for charge +2 with fixed modification Tagger tagger4 = Tagger(2, 10, 5, 2, 2, ListUtils::create<String>("Oxidation (D)")); tags.clear(); tagger4.getTag(spec2, tags); TEST_EQUAL(tags.size(), 667); TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPT") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPTI") != tags.end(), false) // modified residue found again TEST_EQUAL(std::find(tags.begin(), tags.end(), "EPTID") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PTIDE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TIDET") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "IDETE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "DETES") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ETEST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TESTT") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ESTTH") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STTHI") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TTHIS") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "THIST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "HISTA") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ISTAG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STAGG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TAGGE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "AGGER") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GGER") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GER") != tags.end(), true) // tagger searching for charge +2 with variable modification Tagger tagger5 = Tagger(2, 10, 5, 2, 2, StringList(), ListUtils::create<String>("Oxidation (D)")); tags.clear(); tagger5.getTag(spec2, tags); TEST_EQUAL(tags.size(), 739); TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPT") != tags.end(), false) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PEPTI") != tags.end(), false) // modified residue found again TEST_EQUAL(std::find(tags.begin(), tags.end(), "EPTID") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "PTIDE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TIDET") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "IDETE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "DETES") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ETEST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TESTT") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ESTTH") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STTHI") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TTHIS") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "THIST") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "HISTA") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "ISTAG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "STAGG") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "TAGGE") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "AGGER") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GGER") != tags.end(), true) TEST_EQUAL(std::find(tags.begin(), tags.end(), "GER") != tags.end(), true) // // runtime benchmark, research tags many times in the same spectrum // // takes currently about 90 sec // std::cout << std::endl; // for (int i = 0; i < 5000; i++) // { // tags.clear(); // tagger3.getTag(spec, tags); // } // // write out found tags if necessary // for (const std::string& tag : tags) // { // std::cout << "TEST TAG: " << tag << std::endl; // } END_SECTION START_SECTION(void getTag(const MSSpectrum& spec, std::set<std::string>& tags) Tolerance based on ppm vs absolute Da - comparison) // Test both tolerance modes: ppm-based (default/relative) and absolute Da-based (new feature) // This test demonstrates the difference between the two modes, especially important // for large fragment masses (e.g., nucleic acids, top-down proteomics) // Create a synthetic spectrum with large m/z values simulating large fragments // We add small mass errors (0.01 Da) that are within Da mode tolerance but outside ppm mode std::vector<double> mzs_large; // Simulate a sequence with large base m/z values (1000-2000 Da range) // Starting at 1000 Da and adding amino acid masses with deliberate mass errors double base_mz_ppm = 1000.0; double mass_error = 0.01; // 10 milliDa error - within Da mode (0.015 Da at 1500 Da), outside ppm mode (0.001 Da for ~100 Da AA) mzs_large.push_back(base_mz_ppm); // ~1000 Da mzs_large.push_back(base_mz_ppm + 97.0527 + mass_error); // +P ~1097 Da (with error) mzs_large.push_back(base_mz_ppm + 97.0527 + 129.0426 + mass_error); // +PE ~1226 Da (with error) mzs_large.push_back(base_mz_ppm + 97.0527 + 129.0426 + 97.0527 + mass_error); // +PEP ~1323 Da (with error) mzs_large.push_back(base_mz_ppm + 97.0527 + 129.0426 + 97.0527 + 101.0477 + mass_error); // +PEPT ~1424 Da (with error) mzs_large.push_back(base_mz_ppm + 97.0527 + 129.0426 + 97.0527 + 101.0477 + 103.0094 + mass_error); // +PEPTI ~1527 Da (with error) mzs_large.push_back(base_mz_ppm + 97.0527 + 129.0426 + 97.0527 + 101.0477 + 103.0094 + 115.0269 + mass_error); // +PEPTID ~1642 Da (with error) mzs_large.push_back(base_mz_ppm + 97.0527 + 129.0426 + 97.0527 + 101.0477 + 103.0094 + 115.0269 + 129.0426 + mass_error); // +PEPTIDE ~1771 Da (with error) std::vector<std::string> tags_ppm_vec; std::vector<std::string> tags_da_vec; // Test 1: Default ppm-based tolerance (tol_is_ppm = true, the default) // With ppm mode, tolerance is calculated relative to amino acid mass differences // For amino acid mass ~100 Da, 10 ppm = 0.001 Da - won't match our 0.01 Da error Tagger tagger_ppm = Tagger(2, 10, 7, 1, 1, StringList(), StringList(), true); // ppm mode (default) tagger_ppm.getTag(mzs_large, tags_ppm_vec); // Test 2: New absolute Da-based tolerance (tol_is_ppm = false) // With Da mode, tolerance is calculated relative to fragment m/z values // For fragment m/z ~1500 Da, 10 ppm = 0.015 Da - WILL match our 0.01 Da error // This gives much more tolerance for matching when fragment masses are large Tagger tagger_da = Tagger(2, 10, 7, 1, 1, StringList(), StringList(), false); // Da mode (new) tagger_da.getTag(mzs_large, tags_da_vec); // Convert to sets for easier comparison std::set<std::string> tags_ppm_mode(tags_ppm_vec.begin(), tags_ppm_vec.end()); std::set<std::string> tags_da_mode(tags_da_vec.begin(), tags_da_vec.end()); // Both modes should find some tags TEST_NOT_EQUAL(tags_ppm_mode.size(), 0) TEST_NOT_EQUAL(tags_da_mode.size(), 0) // Critical test: The two sets should NOT be equal (different tolerance behavior) // We test this by checking if they differ in size or content bool sets_are_equal = (tags_ppm_mode.size() == tags_da_mode.size() && std::equal(tags_ppm_mode.begin(), tags_ppm_mode.end(), tags_da_mode.begin())); TEST_EQUAL(sets_are_equal, false) // Sets should differ // Da mode should find at least as many tags as ppm mode (more lenient tolerance) TEST_EQUAL(tags_da_mode.size() >= tags_ppm_mode.size(), true) // Find at least one tag that is in Da mode but not in ppm mode // This proves Da mode's wider tolerance allows matches that ppm mode misses bool found_da_exclusive = false; std::string example_da_exclusive; for (const auto& tag : tags_da_mode) { if (tags_ppm_mode.find(tag) == tags_ppm_mode.end()) { found_da_exclusive = true; example_da_exclusive = tag; break; } } TEST_EQUAL(found_da_exclusive, true) // Prove Da mode finds tags ppm mode doesn't // Additionally verify that Da mode found significantly more tags (at least 10% more) // This demonstrates the practical benefit of the wider tolerance for large fragments double ratio = static_cast<double>(tags_da_mode.size()) / static_cast<double>(tags_ppm_mode.size()); TEST_EQUAL(ratio >= 1.1, true) // Da mode should find at least 10% more tags END_SECTION START_SECTION(void getTag(const MSSpectrum& spec, std::set<std::string>& tags) Tolerance mode with absolute Da values) // Test the new absolute Da tolerance mode with specific expected results // This validates both positive cases (within tolerance) and negative cases (outside tolerance) // Set up test data with known amino acid masses and deliberate errors // P = 97.0527 Da, E = 129.0426 Da, T = 101.0477 Da std::vector<double> mzs_with_errors; double base_mz_abs = 150.0; double within_tol_error = 0.015; // Within 0.02 Da tolerance double outside_tol_error = 0.025; // Outside 0.02 Da tolerance // Build spectrum with controlled errors: mzs_with_errors.push_back(base_mz_abs); // 150.000 mzs_with_errors.push_back(base_mz_abs + 97.0527 + within_tol_error); // +P with 0.015 Da error (WITHIN tolerance) mzs_with_errors.push_back(base_mz_abs + 97.0527 + 129.0426 + within_tol_error); // +PE with 0.015 Da error (WITHIN) mzs_with_errors.push_back(base_mz_abs + 97.0527 + 129.0426 + 97.0527 + outside_tol_error); // +PEP with 0.025 Da error (OUTSIDE) mzs_with_errors.push_back(base_mz_abs + 97.0527 + 129.0426 + 97.0527 + 101.0477); // +PEPT exact mass (WITHIN) // Test 1: With appropriate tolerance (0.02 Da), should match within-tolerance errors std::vector<std::string> tags_good_tol_vec; Tagger tagger_good_tol = Tagger(2, 0.02, 4, 1, 1, StringList(), StringList(), false); tagger_good_tol.getTag(mzs_with_errors, tags_good_tol_vec); std::set<std::string> tags_good_tol(tags_good_tol_vec.begin(), tags_good_tol_vec.end()); // Should find tags with errors within 0.02 Da TEST_EQUAL(tags_good_tol.find("PE") != tags_good_tol.end(), true) // 0.015 Da error - WITHIN tolerance // Should NOT find tags requiring the 0.025 Da error match (PEP chain broken by large error) // The tag "PEP" might not be found because the third P has 0.025 Da error (outside tolerance) // But we should still find tags from the good portion of the sequence TEST_NOT_EQUAL(tags_good_tol.size(), 0) // Should find some tags // Test 2: NEGATIVE CONTROL - With overly tight tolerance (0.001 Da), should miss the deliberate errors std::vector<std::string> tags_tight_tol_vec; Tagger tagger_tight_tol = Tagger(2, 0.001, 4, 1, 1, StringList(), StringList(), false); tagger_tight_tol.getTag(mzs_with_errors, tags_tight_tol_vec); std::set<std::string> tags_tight_tol(tags_tight_tol_vec.begin(), tags_tight_tol_vec.end()); // With 0.001 Da tolerance, should NOT match the 0.015 Da errors TEST_EQUAL(tags_tight_tol.find("PE") != tags_tight_tol.end(), false) // 0.015 Da error - OUTSIDE 0.001 Da tolerance // Should find fewer tags overall (or none) since most masses have errors TEST_EQUAL(tags_good_tol.size() > tags_tight_tol.size(), true) // Good tolerance finds more // Test 3: With exact masses (no errors), should match perfectly with any reasonable tolerance std::vector<double> mzs_exact; mzs_exact.push_back(150.0); mzs_exact.push_back(150.0 + 97.0527); // +P exact mzs_exact.push_back(150.0 + 97.0527 + 129.0426); // +PE exact mzs_exact.push_back(150.0 + 97.0527 + 129.0426 + 97.0527); // +PEP exact std::vector<std::string> tags_exact_vec; Tagger tagger_exact = Tagger(2, 0.02, 3, 1, 1, StringList(), StringList(), false); tagger_exact.getTag(mzs_exact, tags_exact_vec); std::set<std::string> tags_exact(tags_exact_vec.begin(), tags_exact_vec.end()); // With exact masses, should definitely find the expected tags // Note: Tagger generates linear sequence tags from consecutive peaks TEST_EQUAL(tags_exact.find("PE") != tags_exact.end(), true) TEST_EQUAL(tags_exact.find("EP") != tags_exact.end(), true) TEST_EQUAL(tags_exact.find("PEP") != tags_exact.end(), true) // Build expected minimum tag set for exact masses // Note: Only testing tags that Tagger actually generates (linear consecutive tags) std::set<std::string> expected_tags = {"PE", "EP", "PEP"}; // Check that all expected tags are present for (const auto& expected : expected_tags) { TEST_EQUAL(tags_exact.find(expected) != tags_exact.end(), true) } // Test 4: Verify tolerance boundary - mass difference clearly within tolerance std::vector<double> mzs_within; mzs_within.push_back(200.0); mzs_within.push_back(200.0 + 97.0527 + 0.015); // +P with 0.015 Da error mzs_within.push_back(200.0 + 97.0527 + 129.0426 + 0.015); // +PE with 0.015 Da error on each std::vector<std::string> tags_within_vec; Tagger tagger_within = Tagger(2, 0.02, 2, 1, 1, StringList(), StringList(), false); tagger_within.getTag(mzs_within, tags_within_vec); std::set<std::string> tags_within(tags_within_vec.begin(), tags_within_vec.end()); // With 0.015 Da error (< 0.02 Da tolerance), should find the tag TEST_NOT_EQUAL(tags_within.size(), 0) // Should match within tolerance TEST_EQUAL(tags_within.find("PE") != tags_within.end(), true) // Should find PE with errors within tolerance // Test 5: NEGATIVE - Verify mass difference outside tolerance is rejected std::vector<double> mzs_outside; mzs_outside.push_back(200.0); mzs_outside.push_back(200.0 + 97.0527 + 0.025); // +P with 0.025 Da error (outside 0.02 Da tolerance) mzs_outside.push_back(200.0 + 97.0527 + 129.0426 + 0.025); // +PE std::vector<std::string> tags_outside_vec; Tagger tagger_outside = Tagger(2, 0.02, 2, 1, 1, StringList(), StringList(), false); tagger_outside.getTag(mzs_outside, tags_outside_vec); std::set<std::string> tags_outside(tags_outside_vec.begin(), tags_outside_vec.end()); // With 0.025 Da error (> 0.02 Da tolerance), should NOT find the PE tag TEST_EQUAL(tags_outside.find("PE") != tags_outside.end(), false) // Should reject PE with errors outside tolerance END_SECTION START_SECTION(void getTag(const MSSpectrum& spec, std::set<std::string>& tags) Explicit test for absolute vs ppm tolerance modes with large fragments) // This test explicitly demonstrates the difference between ppm and absolute Da modes // For large fragment masses (e.g., top-down proteomics, nucleic acids) // At m/z 2000 Da: // - 100 ppm on AA mass (~100 Da) = 0.01 Da tolerance // - 100 ppm on fragment m/z (2000 Da) = 0.2 Da tolerance (20x larger!) std::vector<double> mzs_demo; double base = 2000.0; double aa_P = 97.0527; double aa_E = 129.0426; // Add some noise/shift to make this realistic (0.05 Da shift) mzs_demo.push_back(base); mzs_demo.push_back(base + aa_P + 0.05); // shifted by 0.05 Da mzs_demo.push_back(base + aa_P + aa_E + 0.05); mzs_demo.push_back(base + aa_P + aa_E + aa_P + 0.05); std::vector<std::string> tags_ppm_tight; std::vector<std::string> tags_da_wide; // Test 1: ppm mode with 100 ppm - applies tolerance to AA mass (~100 Da) // Tolerance: ~0.01 Da on AA mass - won't match 0.05 Da shift Tagger tagger_ppm_tight = Tagger(2, 100, 3, 1, 1, StringList(), StringList(), true); tagger_ppm_tight.getTag(mzs_demo, tags_ppm_tight); // Test 2: Da mode with 100 ppm - applies tolerance to fragment m/z (~2000 Da) // Tolerance: ~0.2 Da on fragment m/z - WILL match 0.05 Da shift Tagger tagger_da_wide = Tagger(2, 100, 3, 1, 1, StringList(), StringList(), false); tagger_da_wide.getTag(mzs_demo, tags_da_wide); // With the larger shift, ppm mode (tight on AA mass) should find fewer or no tags // Da mode (wide on fragment m/z) should find tags despite the shift // The exact counts depend on matching, but Da mode should be >= ppm mode TEST_EQUAL(tags_da_wide.size() >= tags_ppm_tight.size(), true) END_SECTION START_SECTION(void getTag(const MSSpectrum& spec, std::set<std::string>& tags) Backward compatibility - default is ppm mode) // Verify that the default behavior (ppm mode) is preserved for backward compatibility std::vector<double> mzs_compat; mzs_compat.push_back(200.0); mzs_compat.push_back(297.0527); // +P mzs_compat.push_back(426.0953); // +PE std::vector<std::string> tags_default; std::vector<std::string> tags_explicit_ppm; // Constructor without tol_is_ppm parameter (uses default = true) Tagger tagger_default = Tagger(2, 20, 2, 1, 1); tagger_default.getTag(mzs_compat, tags_default); // Constructor with explicit tol_is_ppm = true Tagger tagger_explicit = Tagger(2, 20, 2, 1, 1, StringList(), StringList(), true); tagger_explicit.getTag(mzs_compat, tags_explicit_ppm); // Both should produce identical results (backward compatibility) TEST_EQUAL(tags_default.size(), tags_explicit_ppm.size()) END_SECTION START_SECTION(void getTag(const MSSpectrum& spec, std::set<std::string>& tags) Test absolute Da mode with realistic tolerances) // Test absolute Da mode with tolerances typical for high-resolution MS std::vector<double> mzs_hires; double base_mz_hires = 1500.0; // Add realistic mass measurement errors (~5-10 ppm at high resolution) mzs_hires.push_back(base_mz_hires); mzs_hires.push_back(base_mz_hires + 97.0527 + 0.001); // 1 milliDa shift mzs_hires.push_back(base_mz_hires + 97.0527 * 2 + 0.002); // 2 milliDa shift mzs_hires.push_back(base_mz_hires + 97.0527 * 3 + 0.001); // 1 milliDa shift std::vector<std::string> tags_hires; // Use 10 ppm in absolute Da mode // At 1500 Da: 10 ppm = 0.015 Da = 15 milliDa (covers our 1-2 milliDa shifts) Tagger tagger_hires = Tagger(2, 10, 3, 1, 1, StringList(), StringList(), false); tagger_hires.getTag(mzs_hires, tags_hires); // Should find tags with realistic high-resolution mass errors TEST_NOT_EQUAL(tags_hires.size(), 0) END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FeatureFinderAlgorithmPickedHelperStructs_test.cpp
.cpp
10,905
368
// 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 <OpenMS/FEATUREFINDER/FeatureFinderAlgorithmPickedHelperStructs.h> /////////////////////////// #include <OpenMS/KERNEL/Peak1D.h> using namespace OpenMS; using namespace std; START_TEST(FeatureFinderAlgorithmPickedHelperStructs, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::IsotopePattern] IsotopePattern(Size size))) { const Size expected_size = 10; FeatureFinderAlgorithmPickedHelperStructs::IsotopePattern pattern(expected_size); TEST_EQUAL(pattern.intensity.size(), expected_size) TEST_EQUAL(pattern.mz_score.size(), expected_size) TEST_EQUAL(pattern.peak.size(), expected_size) TEST_EQUAL(pattern.spectrum.size(), expected_size) TEST_EQUAL(pattern.theoretical_mz.size(), expected_size) } END_SECTION // MassTrace for testing FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt1; mt1.theoretical_int = 0.8; ///////////////////////////////////////////////////////////// Peak1D p1_1; p1_1.setIntensity(1.08268226589f); p1_1.setMZ(1000); mt1.peaks.push_back(std::make_pair(677.1 , &p1_1)); Peak1D p1_2; p1_2.setIntensity(1.58318959267f); p1_2.setMZ(1000); mt1.peaks.push_back(std::make_pair(677.4 , &p1_2)); Peak1D p1_3; p1_3.setIntensity(2.22429840363f); p1_3.setMZ(1000); mt1.peaks.push_back(std::make_pair(677.7 , &p1_3)); Peak1D p1_4; p1_4.setIntensity(3.00248879081f); p1_4.setMZ(1000); mt1.peaks.push_back(std::make_pair(678 , &p1_4)); Peak1D p1_5; p1_5.setIntensity(3.89401804768f); p1_5.setMZ(1000); mt1.peaks.push_back(std::make_pair(678.3 , &p1_5)); Peak1D p1_6; p1_6.setIntensity(4.8522452777f); p1_6.setMZ(1000); mt1.peaks.push_back(std::make_pair(678.6 , &p1_6)); Peak1D p1_7; p1_7.setIntensity(5.80919229659f); p1_7.setMZ(1000); mt1.peaks.push_back(std::make_pair(678.9 , &p1_7)); Peak1D p1_8; p1_8.setIntensity(6.68216169129f); p1_8.setMZ(1000); mt1.peaks.push_back(std::make_pair(679.2 , &p1_8)); Peak1D p1_9; p1_9.setIntensity(7.38493077109f); p1_9.setMZ(1000); mt1.peaks.push_back(std::make_pair(679.5 , &p1_9)); Peak1D p1_10; p1_10.setIntensity(7.84158938645f); p1_10.setMZ(1000); mt1.peaks.push_back(std::make_pair(679.8 , &p1_10)); START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTrace] ConvexHull2D getConvexhull() const )) { ConvexHull2D ch = mt1.getConvexhull(); DPosition<2> point; point[0] = 679.8; point[1] = p1_10.getMZ(); TEST_EQUAL(ch.encloses(point),true); point[1] = p1_10.getMZ() + 1.0; TEST_EQUAL(ch.encloses(point),false); point[1] = p1_10.getMZ(); point[0] = 679.9; TEST_EQUAL(ch.encloses(point),false); } END_SECTION START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTrace] void updateMaximum())) { mt1.updateMaximum(); TEST_EQUAL(mt1.max_peak, &p1_10) TEST_EQUAL(mt1.max_rt, 679.8) } END_SECTION START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTrace] double getAvgMZ() const )) { // getAvgMZ computes intensity weighted avg of the mass trace TEST_EQUAL(mt1.getAvgMZ(), 1000) FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt_avg; Peak1D pAvg1; pAvg1.setMZ(10.5); pAvg1.setIntensity(1000); mt_avg.peaks.push_back(std::make_pair(100.0, &pAvg1)); Peak1D pAvg2; pAvg2.setMZ(10.0); pAvg2.setIntensity(100); mt_avg.peaks.push_back(std::make_pair(100.0, &pAvg2)); Peak1D pAvg3; pAvg3.setMZ(9.5); pAvg3.setIntensity(10); mt_avg.peaks.push_back(std::make_pair(100.0, &pAvg3)); TEST_REAL_SIMILAR(mt_avg.getAvgMZ(), 10.4459) } END_SECTION START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTrace] bool isValid() const )) { TEST_EQUAL(mt1.isValid(), true) FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt_non_valid; mt_non_valid.peaks.push_back(std::make_pair(679.8 , &p1_10)); TEST_EQUAL(mt_non_valid.isValid(), false) mt_non_valid.peaks.push_back(std::make_pair(679.5 , &p1_9)); TEST_EQUAL(mt_non_valid.isValid(), false) mt_non_valid.peaks.push_back(std::make_pair(679.2 , &p1_8)); TEST_EQUAL(mt_non_valid.isValid(), true) } END_SECTION // testing mass trace FeatureFinderAlgorithmPickedHelperStructs::MassTraces mt; FeatureFinderAlgorithmPickedHelperStructs::MassTraces empty_traces; // add a mass trace mt.push_back(mt1); START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTraces] MassTraces())) { TEST_EQUAL(mt.max_trace, 0) } END_SECTION START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTraces] Size getPeakCount() const )) { TEST_EQUAL(mt.getPeakCount(), 10) TEST_EQUAL(empty_traces.getPeakCount(), 0) } END_SECTION FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt2; mt2.theoretical_int = 0.2; Peak1D p2_4; p2_4.setIntensity(0.750622197703f); p2_4.setMZ(1001); mt2.peaks.push_back(std::make_pair(678, &p2_4)); Peak1D p2_5; p2_5.setIntensity(0.97350451192f); p2_5.setMZ(1001); mt2.peaks.push_back(std::make_pair(678.3, &p2_5)); Peak1D p2_6; p2_6.setIntensity(1.21306131943f); p2_6.setMZ(1001); mt2.peaks.push_back(std::make_pair(678.6, &p2_6)); mt.push_back(mt2); START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTraces] bool isValid(double seed_mz, double trace_tolerance))) { // isValid checks if if we have enough traces FeatureFinderAlgorithmPickedHelperStructs::MassTraces invalid_traces; invalid_traces.push_back(mt1); TEST_EQUAL(invalid_traces.isValid(600.0, 0.03), false) // contains only one mass trace // and if the given seed is inside one of the mass traces TEST_EQUAL(mt.isValid(1000.0, 0.00), true) TEST_EQUAL(mt.isValid(1001.003, 0.03), true) TEST_EQUAL(mt.isValid(1002, 0.003), false) } END_SECTION START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTraces] Size getTheoreticalmaxPosition() const )) { TEST_EXCEPTION(Exception::Precondition, empty_traces.getTheoreticalmaxPosition()) TEST_EQUAL(mt.getTheoreticalmaxPosition(), 0) } END_SECTION START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTraces] void updateBaseline())) { empty_traces.updateBaseline(); TEST_EQUAL(empty_traces.baseline, 0.0) mt.updateBaseline(); TEST_EQUAL(mt.baseline, p2_4.getIntensity()) } END_SECTION START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTraces] std::pair<double,double> getRTBounds() const )) { TEST_EXCEPTION(Exception::Precondition, empty_traces.getRTBounds()) std::pair<double, double> bounds = mt.getRTBounds(); TEST_EQUAL(bounds.first, 677.1) TEST_EQUAL(bounds.second, 679.8) } END_SECTION // add some border cases to the traces that should be checked in computeIntensityProfile() // add a leading peak to the second trace Peak1D p2_0; p2_0.setIntensity(0.286529652f); p2_0.setMZ(1001); mt[1].peaks.insert(mt[1].peaks.begin(), std::make_pair(676.8, &p2_0)); // .. add a peak after a gap Peak1D p2_7; p2_7.setIntensity(0.72952935f); p2_7.setMZ(1001); mt[1].peaks.push_back(std::make_pair(679.2, &p2_7)); // .. and a trailing peak Peak1D p2_8; p2_8.setIntensity(0.672624672f); p2_8.setMZ(1001); mt[1].peaks.push_back(std::make_pair(680.1, &p2_8)); START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::MassTraces] void computeIntensityProfile(std::list< std::pair<double, double> > intensity_profile) const)) { std::list< std::pair<double, double> > intensity_profile; mt.computeIntensityProfile(intensity_profile); TEST_EQUAL(intensity_profile.size(), 12) ABORT_IF(intensity_profile.size() != 12) std::list< std::pair<double, double> >::iterator profile = intensity_profile.begin(); // the leading peak // 676.8 -> 0.286529652f TEST_REAL_SIMILAR(profile->first, 676.8) TEST_REAL_SIMILAR(profile->second, 0.286529652f) ++profile; // 677.1 -> 1.08268226589f TEST_REAL_SIMILAR(profile->first, 677.1) TEST_REAL_SIMILAR(profile->second, 1.08268226589f) ++profile; // 677.4 -> 1.58318959267f TEST_REAL_SIMILAR(profile->first, 677.4) TEST_REAL_SIMILAR(profile->second, 1.58318959267f) ++profile; // 677.7 -> 2.22429840363f TEST_REAL_SIMILAR(profile->first, 677.7) TEST_REAL_SIMILAR(profile->second, 2.22429840363f) ++profile; // 678.0 -> 3.00248879081f + 0.750622197703f TEST_REAL_SIMILAR(profile->first, 678.0) TEST_REAL_SIMILAR(profile->second, (3.00248879081f + 0.750622197703f)) ++profile; // 678.3 -> 3.89401804768f + 0.97350451192f TEST_REAL_SIMILAR(profile->first, 678.3) TEST_REAL_SIMILAR(profile->second, (3.89401804768f + 0.97350451192f)) ++profile; // 678.6 -> 4.8522452777f + 1.21306131943f TEST_REAL_SIMILAR(profile->first, 678.6) TEST_REAL_SIMILAR(profile->second, (4.8522452777f + 1.21306131943f)) ++profile; // 678.9 -> 5.80919229659f TEST_REAL_SIMILAR(profile->first, 678.9) TEST_REAL_SIMILAR(profile->second, 5.80919229659f) ++profile; // 679.2 -> 6.68216169129f + 0.72952935f TEST_REAL_SIMILAR(profile->first, 679.2) TEST_REAL_SIMILAR(profile->second, (6.68216169129f + 0.72952935f)) ++profile; // 679.5 -> 7.38493077109f TEST_REAL_SIMILAR(profile->first, 679.5) TEST_REAL_SIMILAR(profile->second, 7.38493077109f) ++profile; // 679.8 -> 7.84158938645f TEST_REAL_SIMILAR(profile->first, 679.8) TEST_REAL_SIMILAR(profile->second, 7.84158938645f) ++profile; // 680.1 -> 0.672624672f TEST_REAL_SIMILAR(profile->first, 680.1) TEST_REAL_SIMILAR(profile->second, 0.672624672f) ++profile; TEST_EQUAL(profile == intensity_profile.end(), true) } END_SECTION START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::Seed] bool operator<(const Seed &rhs) const )) { FeatureFinderAlgorithmPickedHelperStructs::Seed s1,s2,s3; s1.intensity = 100.0; s2.intensity = 200.0; s3.intensity = 300.0; TEST_EQUAL(s1.operator <(s2), true) TEST_EQUAL(s1.operator <(s3), true) TEST_EQUAL(s2.operator <(s3), true) TEST_EQUAL(s2.operator <(s1), false) TEST_EQUAL(s3.operator <(s1), false) TEST_EQUAL(s3.operator <(s2), false) } END_SECTION START_SECTION(([FeatureFinderAlgorithmPickedHelperStructs::TheoreticalIsotopePattern] Size size() const )) { FeatureFinderAlgorithmPickedHelperStructs::TheoreticalIsotopePattern theo_pattern; TEST_EQUAL(theo_pattern.size(), 0) theo_pattern.intensity.push_back(0.7); theo_pattern.intensity.push_back(0.2); theo_pattern.intensity.push_back(0.1); TEST_EQUAL(theo_pattern.size(), 3) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/NucleicAcidSpectrumGenerator_test.cpp
.cpp
12,570
365
// 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 <iostream> #include <OpenMS/CHEMISTRY/NucleicAcidSpectrumGenerator.h> #include <OpenMS/CONCEPT/Constants.h> /////////////////////////// START_TEST(NucleicAcidSpectrumGenerator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; NucleicAcidSpectrumGenerator* ptr = nullptr; NucleicAcidSpectrumGenerator* null_ptr = nullptr; START_SECTION(NucleicAcidSpectrumGenerator()) ptr = new NucleicAcidSpectrumGenerator(); TEST_NOT_EQUAL(ptr, null_ptr) END_SECTION START_SECTION(NucleicAcidSpectrumGenerator(const NucleicAcidSpectrumGenerator& source)) NucleicAcidSpectrumGenerator copy(*ptr); TEST_EQUAL(copy.getParameters(), ptr->getParameters()) END_SECTION START_SECTION(NucleicAcidSpectrumGenerator& operator=(const TheoreticalSpectrumGenerator& source)) NucleicAcidSpectrumGenerator copy; copy = *ptr; TEST_EQUAL(copy.getParameters(), ptr->getParameters()) END_SECTION START_SECTION(~NucleicAcidSpectrumGenerator()) delete ptr; END_SECTION ptr = new NucleicAcidSpectrumGenerator(); START_SECTION((void getSpectrum(MSSpectrum& spectrum, const NASequence& oligo, Int min_charge, Int max_charge) const)) { // fragment ion data from Ariadne (ariadne.riken.jp): NASequence seq = NASequence::fromString("[m1A]UCCACAGp"); ABORT_IF(abs(seq.getMonoWeight() - 2585.3800) > 0.01); vector<double> aminusB_ions = {113.0244, 456.0926, 762.1179, 1067.1592, 1372.2005, 1701.2530, 2006.2943, 2335.3468}; vector<double> a_ions = {262.0946, 568.1199, 873.1612, 1178.2024, 1507.2550, 1812.2962, 2141.3488, 2486.3962}; vector<double> b_ions = {280.1051, 586.1304, 891.1717, 1196.2130, 1525.2655, 1830.3068, 2159.3593, 2504.4068}; vector<double> c_ions = {342.0609, 648.0862, 953.1275, 1258.1688, 1587.2213, 1892.2626, 2221.3151}; vector<double> d_ions = {360.0715, 666.0968, 971.1380, 1276.1793, 1605.2319, 1910.2731, 2239.3257}; vector<double> w_ions = {442.0171, 771.0696, 1076.1109, 1405.1634, 1710.2047, 2015.2460, 2321.2713}; vector<double> x_ions = {424.0065, 753.0590, 1058.1003, 1387.1528, 1692.1941, 1997.2354, 2303.2607}; vector<double> y_ions = {362.0507, 691.1032, 996.1445, 1325.1970, 1630.2383, 1935.2796, 2241.3049}; vector<double> z_ions = {344.0402, 673.0927, 978.1340, 1307.1865, 1612.2278, 1917.2691, 2223.2944}; Param param = ptr->getDefaults(); param.setValue("add_metainfo", "true"); param.setValue("add_first_prefix_ion", "true"); param.setValue("add_b_ions", "false"); param.setValue("add_y_ions", "false"); MSSpectrum spectrum; param.setValue("add_a-B_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), aminusB_ions.size() - 1); // last one is missing for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), aminusB_ions[i]); } spectrum.clear(true); param.setValue("add_a-B_ions", "false"); param.setValue("add_a_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), a_ions.size() - 1); // last one is missing for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), a_ions[i]); } spectrum.clear(true); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), b_ions.size() - 1); // last one is missing for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), b_ions[i]); } spectrum.clear(true); param.setValue("add_b_ions", "false"); param.setValue("add_c_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), c_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), c_ions[i]); } spectrum.clear(true); param.setValue("add_c_ions", "false"); param.setValue("add_d_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), d_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), d_ions[i]); } spectrum.clear(true); param.setValue("add_d_ions", "false"); param.setValue("add_w_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), w_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), w_ions[i]); } spectrum.clear(true); param.setValue("add_w_ions", "false"); param.setValue("add_x_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), x_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), x_ions[i]); } spectrum.clear(true); param.setValue("add_x_ions", "false"); param.setValue("add_y_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), y_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), y_ions[i]); } spectrum.clear(true); param.setValue("add_y_ions", "false"); param.setValue("add_z_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), z_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), z_ions[i]); } seq = NASequence::fromString("[m1A]UCCACA[G*]p"); //Terminal thiol replacement shouldn't change any masses TEST_REAL_SIMILAR(seq.getMonoWeight(), 2585.3800); //repeat the above with internal Thiols seq = NASequence::fromString("[m1A]UC[C*]AC[A*]Gp"); //Terminal thiol replacement shouldn't change any masses ABORT_IF(abs(seq.getMonoWeight() - 2617.334342) > 0.01); aminusB_ions = {113.0244, 456.0926, 762.1179, 1067.1592, 1388.1777, 1717.2302, 2022.27147, 2367.3011}; a_ions = {262.0946, 568.1199, 873.1612, 1178.2024, 1523.2321, 1828.2733, 2157.3259, 2518.3505}; b_ions = {280.1051, 586.1304, 891.1717, 1196.2130, 1541.2426, 1846.2839, 2175.3365, 2536.3611}; c_ions = {342.0609, 648.0862, 953.1275, 1274.1458, 1603.1984, 1908.2397, 2253.2694}; d_ions = {360.0715, 666.0968, 971.1380, 1292.1564, 1621.2090, 1926.2502, 2271.2800}; w_ions = {457.9942, 787.0468, 1092.0881, 1437.1178, 1742.1591, 2047.2003, 2353.2256}; x_ions = {439.9837, 769.0362, 1074.0775, 1419.1072, 1724.1485, 2029.1898, 2335.2150}; y_ions = {362.0507, 707.0805, 1012.1217, 1341.1743, 1662.1927, 1967.2340, 2273.2593}; z_ions = {344.0402, 689.0699, 994.1112, 1323.1637, 1644.1822, 1949.2234, 2255.2487}; param = ptr->getDefaults(); param.setValue("add_metainfo", "true"); param.setValue("add_first_prefix_ion", "true"); param.setValue("add_b_ions", "false"); param.setValue("add_y_ions", "false"); spectrum.clear(true); param.setValue("add_a-B_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), aminusB_ions.size() - 1); // last one is missing for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), aminusB_ions[i]); } spectrum.clear(true); param.setValue("add_a-B_ions", "false"); param.setValue("add_a_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), a_ions.size() - 1); // last one is missing for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), a_ions[i]); } spectrum.clear(true); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), b_ions.size() - 1); // last one is missing for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), b_ions[i]); } spectrum.clear(true); param.setValue("add_b_ions", "false"); param.setValue("add_c_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), c_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), c_ions[i]); } spectrum.clear(true); param.setValue("add_c_ions", "false"); param.setValue("add_d_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), d_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), d_ions[i]); } spectrum.clear(true); param.setValue("add_d_ions", "false"); param.setValue("add_w_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), w_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), w_ions[i]); } spectrum.clear(true); param.setValue("add_w_ions", "false"); param.setValue("add_x_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), x_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), x_ions[i]); } spectrum.clear(true); param.setValue("add_x_ions", "false"); param.setValue("add_y_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), y_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), y_ions[i]); } spectrum.clear(true); param.setValue("add_y_ions", "false"); param.setValue("add_z_ions", "true"); ptr->setParameters(param); ptr->getSpectrum(spectrum, seq, -1, -1); TEST_EQUAL(spectrum.size(), z_ions.size()); for (Size i = 0; i < spectrum.size(); ++i) { TEST_REAL_SIMILAR(spectrum[i].getMZ(), z_ions[i]); } } END_SECTION START_SECTION((void getMultipleSpectra(std::map<Int, MSSpectrum>& spectra, const NASequence& oligo, const std::set<Int>& charges, Int base_charge = 1) const)) { NucleicAcidSpectrumGenerator gen; Param param = gen.getParameters(); param.setValue("add_first_prefix_ion", "true"); param.setValue("add_metainfo", "true"); // param.setValue("add_precursor_peaks", "true"); // yes or no? param.setValue("add_a_ions", "true"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "true"); param.setValue("add_d_ions", "true"); param.setValue("add_w_ions", "true"); param.setValue("add_x_ions", "true"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "true"); param.setValue("add_a-B_ions", "true"); NASequence seq = NASequence::fromString("[m1A]UCCACAGp"); set<Int> charges = {-1, -3, -5}; // get spectra individually: vector<MSSpectrum> compare(charges.size()); Size index = 0; for (Int charge : charges) { gen.getSpectrum(compare[index], seq, -1, charge); index++; } // now all together: map<Int, MSSpectrum> spectra; gen.getMultipleSpectra(spectra, seq, charges, -1); // compare: TEST_EQUAL(compare.size(), spectra.size()); index = 0; for (const auto& pair : spectra) { TEST_EQUAL(compare[index] == pair.second, true); index++; } } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MRMScoring_test.cpp
.cpp
35,920
871
// 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/ANALYSIS/OPENSWATH/MRMScoring.h" #include "OpenMS/DATASTRUCTURES/MatrixEigen.h" #include "OpenMS/OPENSWATHALGO/DATAACCESS/MockObjects.h" #include "OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h" #include "OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.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 <OpenMS/CONCEPT/ClassTest.h> #define BOOST_AUTO_TEST_CASE START_SECTION using namespace OpenMS; #endif using namespace std; using namespace OpenSwath; void fill_mock_objects(MockMRMFeature * imrmfeature, std::vector<std::string>& native_ids) { native_ids.push_back("group1"); native_ids.push_back("group2"); std::vector<double> intensity1 {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> intensity2 {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> ms1intensity {0.0, 110.0, 200.0, 270.0, 320.0, 350.0, 360.0, 350.0, 320.0, 270.0, 200.0}; std::shared_ptr<MockFeature> f1_ptr = std::shared_ptr<MockFeature>(new MockFeature()); std::shared_ptr<MockFeature> f2_ptr = std::shared_ptr<MockFeature>(new MockFeature()); std::shared_ptr<MockFeature> ms1_ptr = std::shared_ptr<MockFeature>(new MockFeature()); f1_ptr->m_intensity_vec = intensity1; f2_ptr->m_intensity_vec = intensity2; ms1_ptr->m_intensity_vec = ms1intensity; std::map<std::string, std::shared_ptr<MockFeature> > features; features["group1"] = f1_ptr; features["group2"] = f2_ptr; imrmfeature->m_features = features; // add features std::map<std::string, std::shared_ptr<MockFeature> > ms1_features; ms1_features["ms1trace"] = ms1_ptr; imrmfeature->m_precursor_features = ms1_features; // add ms1 feature } void fill_mock_objects2(MockMRMFeature * imrmfeature, std::vector<std::string>& precursor_ids, std::vector<std::string>& native_ids) { precursor_ids.push_back("ms1trace1"); precursor_ids.push_back("ms1trace2"); precursor_ids.push_back("ms1trace3"); native_ids.push_back("group1"); native_ids.push_back("group2"); std::vector<double> intensity1 {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> intensity2 {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> ms1intensity1 {0.0, 110.0, 200.0, 270.0, 320.0, 350.0, 360.0, 350.0, 320.0, 270.0, 200.0}; std::vector<double> ms1intensity2 {10.0, 115.0, 180.0, 280.0, 330.0, 340.0, 390.0, 320.0, 300.0, 250.0, 100.0}; std::vector<double> ms1intensity3 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; std::shared_ptr<MockFeature> f1_ptr = std::shared_ptr<MockFeature>(new MockFeature()); std::shared_ptr<MockFeature> f2_ptr = std::shared_ptr<MockFeature>(new MockFeature()); std::shared_ptr<MockFeature> ms1_f1_ptr = std::shared_ptr<MockFeature>(new MockFeature()); std::shared_ptr<MockFeature> ms1_f2_ptr = std::shared_ptr<MockFeature>(new MockFeature()); std::shared_ptr<MockFeature> ms1_f3_ptr = std::shared_ptr<MockFeature>(new MockFeature()); f1_ptr->m_intensity_vec = intensity1; f2_ptr->m_intensity_vec = intensity2; ms1_f1_ptr->m_intensity_vec = ms1intensity1; ms1_f2_ptr->m_intensity_vec = ms1intensity2; ms1_f3_ptr->m_intensity_vec = ms1intensity3; std::map<std::string, std::shared_ptr<MockFeature> > features; features["group1"] = f1_ptr; features["group2"] = f2_ptr; imrmfeature->m_features = features; // add features std::map<std::string, std::shared_ptr<MockFeature> > ms1_features; ms1_features["ms1trace1"] = ms1_f1_ptr; ms1_features["ms1trace2"] = ms1_f2_ptr; ms1_features["ms1trace3"] = ms1_f3_ptr; imrmfeature->m_precursor_features = ms1_features; // add ms1 feature } /////////////////////////// START_TEST(MRMScoring, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// #ifndef USE_BOOST_UNIT_TEST { MRMScoring* ptr = nullptr; MRMScoring* nullPointer = nullptr; START_SECTION(MRMScoring()) { ptr = new MRMScoring(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~MRMScoring()) { delete ptr; } END_SECTION } #endif /* * Validation of the cross-correlation in Python * from numpy import * data1 = [5.97543668746948, 4.2749171257019, 3.3301842212677, 4.08597040176392, 5.50307035446167, 5.24326848983765, 8.40812492370605, 2.83419919013977, 6.94378805160522, 7.69957494735718, 4.08597040176392] data2 = [15.8951349258423, 41.5446395874023, 76.0746307373047, 109.069435119629, 111.90364074707, 169.79216003418, 121.043930053711, 63.0136985778809, 44.6150207519531, 21.4926776885986, 7.93575811386108] ms1data = [0.0, 110.0, 200.0, 270.0, 320.0, 350.0, 360.0, 350.0, 320.0, 270.0, 200.0] data1 = (data1 - mean(data1) ) / std(data1) data2 = (data2 - mean(data2) ) / std(data2) ms1data = (ms1data - mean(ms1data) ) / std(ms1data) xcorrmatrix_0_0 = correlate(data1, data1, "same") / len(data1) xcorrmatrix_0_1 = correlate(data1, data2, "same") / len(data1) max_el0 = max(enumerate(xcorrmatrix_0_0), key= lambda x: x[1]) max_el1 = max(enumerate(xcorrmatrix_0_1), key= lambda x: x[1]) xcorr_deltas = [0, abs(max_el0[0] - max_el1[0]), 0] xcorr_max = [1, max_el1[1], 1] mean(xcorr_deltas) + std(xcorr_deltas, ddof=1) # coelution score # 2.7320508075688772 mean(xcorr_max) # shape score # 0.13232774079239637 # MS1 level xcorrvector_1 = correlate(ms1data, data1, "same") / len(data1) xcorrvector_2 = correlate(ms1data, data2, "same") / len(data2) max_el0 = max(enumerate(xcorrvector_1), key= lambda x: x[1]) max_el1 = max(enumerate(xcorrvector_2), key= lambda x: x[1]) xcorr_deltas = [0, abs(max_el0[0] - max_el1[0])] xcorr_max = [max_el0[1], max_el1[1]] mean(xcorr_deltas) + std(xcorr_deltas, ddof=1) # coelution score # 1.8213672050459184 mean(xcorr_max) # shape score # 0.54120799790227003 * */ //START_SECTION((void initializeXCorrMatrix(MRMFeature& mrmfeature, MRMTransitionGroup< SpectrumType, PeakType >& transition_group, bool normalize))) BOOST_AUTO_TEST_CASE(initializeXCorrMatrix) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); //initialize the XCorr Matrix mrmscore.initializeXCorrMatrix(imrmfeature, native_ids); delete imrmfeature; TEST_EQUAL(mrmscore.getXCorrMatrix().rows(), 2) TEST_EQUAL(mrmscore.getXCorrMatrix().cols(), 2) TEST_EQUAL(mrmscore.getXCorrMatrix()(0, 0).data.size(), 23) // test auto-correlation = xcorrmatrix_0_0 const OpenSwath::Scoring::XCorrArrayType auto_correlation = mrmscore.getXCorrMatrix()(0, 0); TEST_EQUAL(auto_correlation.data[11].first, 0) TEST_EQUAL(auto_correlation.data[12].first, 1) TEST_EQUAL(auto_correlation.data[10].first, -1) TEST_EQUAL(auto_correlation.data[13].first, 2) TEST_EQUAL(auto_correlation.data[ 9].first, -2) TEST_REAL_SIMILAR(auto_correlation.data[11].second , 1) // find(0)->second, TEST_REAL_SIMILAR(auto_correlation.data[12].second , -0.227352707759245) // find(1)->second, TEST_REAL_SIMILAR(auto_correlation.data[10].second , -0.227352707759245) // find(-1)->second, TEST_REAL_SIMILAR(auto_correlation.data[13].second , -0.07501116) // find(2)->second, TEST_REAL_SIMILAR(auto_correlation.data[ 9].second , -0.07501116) // find(-2)->second, // test cross-correlation = xcorrmatrix_0_1 const OpenSwath::Scoring::XCorrArrayType cross_correlation = mrmscore.getXCorrMatrix()(0, 1); TEST_REAL_SIMILAR(cross_correlation.data[13].second, -0.31165141) // find(2)->second, TEST_REAL_SIMILAR(cross_correlation.data[12].second, -0.35036919) // find(1)->second, TEST_REAL_SIMILAR(cross_correlation.data[11].second, 0.03129565) // find(0)->second, TEST_REAL_SIMILAR(cross_correlation.data[10].second, 0.30204049) // find(-1)->second, TEST_REAL_SIMILAR(cross_correlation.data[ 9].second, 0.13012441) // find(-2)->second, TEST_REAL_SIMILAR(cross_correlation.data[ 8].second, 0.39698322) // find(-3)->second, TEST_REAL_SIMILAR(cross_correlation.data[ 7].second, 0.16608774) // find(-4)->second, } END_SECTION BOOST_AUTO_TEST_CASE(initializeXCorrPrecursorContrastMatrix) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; std::vector<std::string> native_ids; fill_mock_objects2(imrmfeature, precursor_ids, native_ids); //initialize the XCorr vector mrmscore.initializeXCorrPrecursorContrastMatrix(imrmfeature, precursor_ids, native_ids); delete imrmfeature; TEST_EQUAL(mrmscore.getXCorrPrecursorContrastMatrix().rows(), 3) TEST_EQUAL(mrmscore.getXCorrPrecursorContrastMatrix().cols(), 2) std::vector<double> sum_matrix; const auto& cm = mrmscore.getXCorrPrecursorContrastMatrix(); // Note: the original code depens on col vs. row order and // the old code: for (auto e : mrmscore.getXCorrPrecursorContrastMatrix()) fails with different data for (Size r = 0; r != cm.rows(); ++r) for (Size c = 0; c != cm.cols(); ++c) { double sum{0}; for (size_t i = 0; i < cm(r,c).data.size(); ++i) { sum += abs(cm(r,c).data[i].second); } sum_matrix.push_back(sum); } /* for (auto e : mrmscore.getXCorrPrecursorContrastMatrix()) { } */ TEST_REAL_SIMILAR(sum_matrix[0], 3.40949220) TEST_REAL_SIMILAR(sum_matrix[1], 6.19794611) TEST_REAL_SIMILAR(sum_matrix[2], 3.68912454) TEST_REAL_SIMILAR(sum_matrix[3], 6.60757921) TEST_REAL_SIMILAR(sum_matrix[4], 0) TEST_REAL_SIMILAR(sum_matrix[5], 0) } END_SECTION BOOST_AUTO_TEST_CASE(initializeXCorrPrecursorCombinedMatrix) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; std::vector<std::string> native_ids; fill_mock_objects2(imrmfeature, precursor_ids, native_ids); //initialize the XCorr vector mrmscore.initializeXCorrPrecursorCombinedMatrix(imrmfeature, precursor_ids, native_ids); delete imrmfeature; TEST_EQUAL(mrmscore.getXCorrPrecursorCombinedMatrix().rows(), 5) TEST_EQUAL(mrmscore.getXCorrPrecursorCombinedMatrix().cols(), 5) std::vector<double> sum_matrix; const auto& cm = mrmscore.getXCorrPrecursorCombinedMatrix(); // Note: the original code depens on col vs. row order and // the old code: for (auto e : mrmscore.getXCorrPrecursorCombinedMatrix()) fails with different data for (Size r = 0; r != cm.rows(); ++r) for (Size c = 0; c != cm.cols(); ++c) { double sum{0}; for (size_t i = 0; i < cm(r,c).data.size(); ++i) { sum += abs(cm(r,c).data[i].second); } sum_matrix.push_back(sum); } // Check upper triangular matrix TEST_REAL_SIMILAR(sum_matrix[0], 5.86440677) TEST_REAL_SIMILAR(sum_matrix[1], 6.05410398) TEST_REAL_SIMILAR(sum_matrix[2], 0) TEST_REAL_SIMILAR(sum_matrix[3], 3.40949220) TEST_REAL_SIMILAR(sum_matrix[4], 6.19794611) TEST_REAL_SIMILAR(sum_matrix[6], 6.30751744) TEST_REAL_SIMILAR(sum_matrix[7], 0) TEST_REAL_SIMILAR(sum_matrix[8], 3.68912454) TEST_REAL_SIMILAR(sum_matrix[9], 6.60757921) TEST_REAL_SIMILAR(sum_matrix[12], 0) TEST_REAL_SIMILAR(sum_matrix[13], 0) TEST_REAL_SIMILAR(sum_matrix[14], 0) TEST_REAL_SIMILAR(sum_matrix[18], 3.13711983) TEST_REAL_SIMILAR(sum_matrix[19], 3.57832717) TEST_REAL_SIMILAR(sum_matrix[24], 6.78303987) } END_SECTION /*BOOST_AUTO_TEST_CASE(initializeXCorrPrecursorMatrix) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; fill_mock_objects(imrmfeature, precursor_ids); //initialize the XCorr vector mrmscore.initializeXCorrPrecursorMatrix(imrmfeature, precursor_ids); delete imrmfeature; TEST_EQUAL(mrmscore.getXCorrPrecursorMatrix().rows(), 3) TEST_EQUAL(mrmscore.getXCorrPrecurso().cols(), 2) } END_SECTION*/ BOOST_AUTO_TEST_CASE(initializeXCorrContrastMatrix) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); //initialize the XCorr Matrix mrmscore.initializeXCorrContrastMatrix(imrmfeature, native_ids, native_ids); delete imrmfeature; TEST_EQUAL(mrmscore.getXCorrContrastMatrix().rows(), 2) TEST_EQUAL(mrmscore.getXCorrContrastMatrix().cols(), 2) TEST_EQUAL(mrmscore.getXCorrContrastMatrix()(0, 0).data.size(), 23) // test auto-correlation = xcorrmatrix_0_0 const OpenSwath::Scoring::XCorrArrayType auto_correlation = mrmscore.getXCorrContrastMatrix()(0, 0); TEST_REAL_SIMILAR(auto_correlation.data[11].second, 1) // find(0)->second, TEST_REAL_SIMILAR(auto_correlation.data[12].second, -0.227352707759245) // find(1)->second, TEST_REAL_SIMILAR(auto_correlation.data[10].second, -0.227352707759245) // find(-1)->second, TEST_REAL_SIMILAR(auto_correlation.data[13].second, -0.07501116) // find(2)->second, TEST_REAL_SIMILAR(auto_correlation.data[ 9].second, -0.07501116) // find(-2)->second, // // test cross-correlation = xcorrmatrix_0_1 const OpenSwath::Scoring::XCorrArrayType cross_correlation = mrmscore.getXCorrContrastMatrix()(0, 1); TEST_REAL_SIMILAR(cross_correlation.data[13].second, -0.31165141) // find(2)->second, TEST_REAL_SIMILAR(cross_correlation.data[12].second, -0.35036919) // find(1)->second, TEST_REAL_SIMILAR(cross_correlation.data[11].second, 0.03129565) // find(0)->second, TEST_REAL_SIMILAR(cross_correlation.data[10].second, 0.30204049) // find(-1)->second, TEST_REAL_SIMILAR(cross_correlation.data[ 9].second, 0.13012441) // find(-2)->second, TEST_REAL_SIMILAR(cross_correlation.data[ 8].second, 0.39698322) // find(-3)->second, TEST_REAL_SIMILAR(cross_correlation.data[ 7].second, 0.16608774) // find(-4)->second, } END_SECTION BOOST_AUTO_TEST_CASE(test_calcXcorrCoelutionScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); mrmscore.initializeXCorrMatrix(imrmfeature, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcXcorrCoelutionScore(), 1 + std::sqrt(3.0)) // mean + std deviation } END_SECTION BOOST_AUTO_TEST_CASE(test_calcSeparateXcorrContrastCoelutionScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); mrmscore.initializeXCorrContrastMatrix(imrmfeature, native_ids, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcSeparateXcorrContrastCoelutionScore()[0], 1.5) TEST_REAL_SIMILAR(mrmscore.calcSeparateXcorrContrastCoelutionScore()[1], 1.5) } END_SECTION BOOST_AUTO_TEST_CASE(test_calcXcorrCoelutionWeightedScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; static const double weights_[] = { 0.5, 0.5 }; std::vector<double> weights (weights_, weights_ + sizeof(weights_) / sizeof(weights_[0]) ); std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); mrmscore.initializeXCorrMatrix(imrmfeature, native_ids); delete imrmfeature; // xcorr_deltas = [0, 3, 0] * array([0.25, 2*0.5*0.5,0.25]) // sum(xcorr_deltas) TEST_REAL_SIMILAR(mrmscore.calcXcorrCoelutionWeightedScore(weights), 1.5) } END_SECTION BOOST_AUTO_TEST_CASE(test_calcXcorrShapeScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); mrmscore.initializeXCorrMatrix(imrmfeature, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcXcorrShapeScore(), (1.0 + 0.3969832 + 1.0)/3.0) // mean + std deviation } END_SECTION BOOST_AUTO_TEST_CASE(test_calcSeparateXcorrContrastShapeScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); mrmscore.initializeXCorrContrastMatrix(imrmfeature, native_ids, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcSeparateXcorrContrastShapeScore()[0], 0.698492) TEST_REAL_SIMILAR(mrmscore.calcSeparateXcorrContrastShapeScore()[1], 0.698492) } END_SECTION BOOST_AUTO_TEST_CASE(test_calcXcorrShapeWeightedScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); static const double weights_[] = { 0.5, 0.5 }; std::vector<double> weights (weights_, weights_ + sizeof(weights_) / sizeof(weights_[0]) ); mrmscore.initializeXCorrMatrix(imrmfeature, native_ids); delete imrmfeature; // xcorr_deltas = [1, 0.3969832, 1] * array([0.25, 2*0.5*0.5,0.25]) // sum(xcorr_deltas) TEST_REAL_SIMILAR(mrmscore.calcXcorrShapeWeightedScore(weights), 0.6984916) } END_SECTION BOOST_AUTO_TEST_CASE(calcXcorrPrecursorContrastCoelutionScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; std::vector<std::string> native_ids; fill_mock_objects2(imrmfeature, precursor_ids, native_ids); //initialize the XCorr vector mrmscore.initializeXCorrPrecursorContrastMatrix(imrmfeature, precursor_ids, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcXcorrPrecursorContrastCoelutionScore(), 9.5741984 ) } END_SECTION BOOST_AUTO_TEST_CASE(calcXcorrPrecursorCombinedCoelutionScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; std::vector<std::string> native_ids; fill_mock_objects2(imrmfeature, precursor_ids, native_ids); //initialize the XCorr vector mrmscore.initializeXCorrPrecursorCombinedMatrix(imrmfeature, precursor_ids, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcXcorrPrecursorCombinedCoelutionScore(), 9.2444789 ) } END_SECTION BOOST_AUTO_TEST_CASE(calcXcorrPrecursorContrastShapeScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; std::vector<std::string> native_ids; fill_mock_objects2(imrmfeature, precursor_ids, native_ids); //initialize the XCorr vector mrmscore.initializeXCorrPrecursorContrastMatrix(imrmfeature, precursor_ids, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcXcorrPrecursorContrastShapeScore(), 0.3772868 ) } END_SECTION BOOST_AUTO_TEST_CASE(calcXcorrPrecursorCombinedShapeScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; std::vector<std::string> native_ids; fill_mock_objects2(imrmfeature, precursor_ids, native_ids); //initialize the XCorr vector mrmscore.initializeXCorrPrecursorCombinedMatrix(imrmfeature, precursor_ids, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcXcorrPrecursorCombinedShapeScore(), 0.5079334 ) } END_SECTION //START_SECTION((virtual void test_calcLibraryScore())) BOOST_AUTO_TEST_CASE(test_Library_score) { /* * Validation in Python of the different library correlation scores * from numpy import * data1 = array([1,10000,2000]) data2 = array([782.380737304688, 58.3845062255859, 58.3845062255859]) ndata1 = (data1 / (sum(data1) *1.0) ) ndata2 = (data2 / (sum(data2) *1.0) ) dotprod = sum([ (a*b) for (a,b) in zip(ndata1, ndata2) ]) lenx = sqrt(sum([ (a*a) for (a,b) in zip(ndata1, ndata2) ])) leny = sqrt(sum([ (b*b) for (a,b) in zip(ndata1, ndata2) ])) math.acos(dotprod/(lenx*leny)) # 1.483262002242929 res = [ (a-b)*(a-b) for (a,b) in zip(ndata1, ndata2) ] sqrt(sum(res)/len(data1)) # 0.67272266738875497 import scipy.stats.stats scipy.stats.stats.pearsonr(ndata1, ndata2) # (-0.65459131605877441, 0.54568145960752545) deltas = [ abs(a-b) for (a,b) in zip(ndata1, ndata2) ] sum(deltas) / len(data1) #0.5800337593857342 sqrtdata1 = sqrt(data1) sqrtdata2 = sqrt(data2) norm1 = sqrtdata1 / sqrt( sum([s*s for s in sqrtdata1]) ) norm2 = sqrtdata2 / sqrt( sum([s*s for s in sqrtdata2]) ) sum([ (a*b) for (a,b) in zip(norm1, norm2) ]) # 0.34514800971521764 ndata1 = (data1 / (sum(data1) *1.0) ) ndata2 = (data2 / (sum(data2) *1.0) ) nsqrtdata1 = (sqrtdata1 / (sum(sqrtdata1) *1.0) ) nsqrtdata2 = (sqrtsdata2 / (sum(sqrtdata2) *1.0) ) sum([ abs(a-b) for (a,b) in zip(nsqrtdata1, nsqrtdata2) ]) # 1.2796447146892949 */ MockMRMFeature * imrmfeature = new MockMRMFeature(); // create mrmfeature, add "experimental" intensities std::shared_ptr<MockFeature> f1_ptr = std::shared_ptr<MockFeature>(new MockFeature()); std::shared_ptr<MockFeature> f2_ptr = std::shared_ptr<MockFeature>(new MockFeature()); std::shared_ptr<MockFeature> f3_ptr = std::shared_ptr<MockFeature>(new MockFeature()); f1_ptr->m_intensity = (float)782.38073; f2_ptr->m_intensity = (float)58.384506; f3_ptr->m_intensity = (float)58.384506; std::map<std::string, std::shared_ptr<MockFeature> > features; features["group1"] = f1_ptr; features["group2"] = f2_ptr; features["group3"] = f2_ptr; imrmfeature->m_features = features; // create transitions, e.g. library intensity std::vector<OpenSwath::LightTransition> transitions; { OpenSwath::LightTransition t; t.library_intensity = 1; t.transition_name = "group1"; transitions.push_back(t); } { OpenSwath::LightTransition t; t.library_intensity = 10000; t.transition_name = "group2"; transitions.push_back(t); } { OpenSwath::LightTransition t; t.library_intensity = 2000; t.transition_name = "group3"; transitions.push_back(t); } MRMScoring mrmscore; double manhatten, dotproduct; double spectral_angle, rmsd; double library_corr, library_rmsd; mrmscore.calcLibraryScore(imrmfeature, transitions, library_corr, library_rmsd, manhatten, dotproduct, spectral_angle, rmsd); TEST_REAL_SIMILAR(library_corr, -0.654591316) TEST_REAL_SIMILAR(library_rmsd, 0.5800337593) TEST_REAL_SIMILAR(manhatten, 1.279644714) TEST_REAL_SIMILAR(dotproduct, 0.34514801) TEST_REAL_SIMILAR(spectral_angle, 1.483262) TEST_REAL_SIMILAR(rmsd, 0.6727226674) delete imrmfeature; } END_SECTION BOOST_AUTO_TEST_CASE(test_RT_score) { MRMScoring mrmscore; OpenSwath::LightCompound pep; pep.rt = 100; TEST_REAL_SIMILAR(mrmscore.calcRTScore(pep, 100), 0) TEST_REAL_SIMILAR(mrmscore.calcRTScore(pep, 0), 100) } END_SECTION BOOST_AUTO_TEST_CASE(test_SN_score) { MRMScoring mrmscore; std::vector<OpenSwath::ISignalToNoisePtr> sn_estimators; std::shared_ptr<MockSignalToNoise> sn1 = std::shared_ptr<MockSignalToNoise>(new MockSignalToNoise()); sn1->m_sn_value = 500; std::shared_ptr<MockSignalToNoise> sn2 = std::shared_ptr<MockSignalToNoise>(new MockSignalToNoise()); sn2->m_sn_value = 1500; sn_estimators.push_back(sn1); sn_estimators.push_back(sn2); MockMRMFeature imrmfeature; std::shared_ptr<MockFeature> f1_ptr = std::shared_ptr<MockFeature>(new MockFeature()); std::shared_ptr<MockFeature> f2_ptr = std::shared_ptr<MockFeature>(new MockFeature()); f1_ptr->m_rt = 1200; f2_ptr->m_rt = 1200; std::map<std::string, std::shared_ptr<MockFeature> > features; features["group1"] = f1_ptr; features["group2"] = f2_ptr; imrmfeature.m_features = features; TEST_REAL_SIMILAR(mrmscore.calcSNScore(&imrmfeature, sn_estimators), 1000.0) TEST_REAL_SIMILAR(mrmscore.calcSeparateSNScore(&imrmfeature, sn_estimators)[0], 6.21461) TEST_REAL_SIMILAR(mrmscore.calcSeparateSNScore(&imrmfeature, sn_estimators)[1], 7.31322) } END_SECTION BOOST_AUTO_TEST_CASE(initializeMIMatrix) { /* * 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); % test_calcMIScore matrices m1 = [mi(x_ranking,y_ranking) mi(y_ranking,y_ranking) mi(x_ranking,x_ranking)] mean(m1) % test_calcSeparateMIContrastScore m2 = zeros(2,2) m2(1,1) = mi(x_ranking,y_ranking) m2(2,1) = mi(y_ranking,y_ranking) m2(1,2) = mi(x_ranking,x_ranking) m2(2,2) = mi(y_ranking,x_ranking) mean(m2) % test_calcMIWeightedScore m3 = [mi(x_ranking,y_ranking)*0.5*0.5 mi(y_ranking,y_ranking)*0.5*0.5*2 mi(x_ranking,x_ranking)*0.5*0.5] sum(m3) % test_calcMIPrecursorContrastScore ms1 = [0.0 110.0 200.0 270.0 320.0 350.0 360.0 350.0 320.0 270.0 200.0]' [~, ~, ms1_ranking] = unique(ms1); m4 = [mi(x_ranking,ms1_ranking) mi(y_ranking,ms1_ranking)] mean(m4) */ MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); //initialize the MI Matrix mrmscore.initializeMIMatrix(imrmfeature, native_ids); delete imrmfeature; TEST_EQUAL(mrmscore.getMIMatrix().rows(), 2) TEST_EQUAL(mrmscore.getMIMatrix().cols(), 2) TEST_REAL_SIMILAR(mrmscore.getMIMatrix()(0, 0), 3.2776) TEST_REAL_SIMILAR(mrmscore.getMIMatrix()(0, 1), 3.2776) TEST_REAL_SIMILAR(mrmscore.getMIMatrix()(1, 1), 3.4594) TEST_REAL_SIMILAR(mrmscore.getMIMatrix()(1, 0), 0) // value not initialized for lower diagonal half of matrix } END_SECTION BOOST_AUTO_TEST_CASE(initializeMIPrecursorContrastMatrix) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; std::vector<std::string> native_ids; fill_mock_objects2(imrmfeature, precursor_ids, native_ids); //initialize the XCorr vector mrmscore.initializeMIPrecursorContrastMatrix(imrmfeature, precursor_ids, native_ids); delete imrmfeature; TEST_EQUAL(mrmscore.getMIPrecursorContrastMatrix().rows(), 3) TEST_EQUAL(mrmscore.getMIPrecursorContrastMatrix().cols(), 2) double sum = OpenMS::eigenView(mrmscore.getMIPrecursorContrastMatrix()).sum(); TEST_REAL_SIMILAR(sum, 12.01954465) } END_SECTION BOOST_AUTO_TEST_CASE(initializeMIPrecursorCombinedMatrix) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; std::vector<std::string> native_ids; fill_mock_objects2(imrmfeature, precursor_ids, native_ids); //initialize the XCorr vector mrmscore.initializeMIPrecursorCombinedMatrix(imrmfeature, precursor_ids, native_ids); delete imrmfeature; TEST_EQUAL(mrmscore.getMIPrecursorCombinedMatrix().rows(), 5) TEST_EQUAL(mrmscore.getMIPrecursorCombinedMatrix().cols(), 5) double sum = OpenMS::eigenView(mrmscore.getMIPrecursorCombinedMatrix()).sum(); TEST_REAL_SIMILAR(sum, 48.98726953) } END_SECTION BOOST_AUTO_TEST_CASE(initializeMIContrastMatrix) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids1, native_ids2; fill_mock_objects(imrmfeature, native_ids1); for (int i=native_ids1.size()-1; i>=0; i--) { native_ids2.push_back(native_ids1[i]); } //initialize the XCorr Matrix mrmscore.initializeMIContrastMatrix(imrmfeature, native_ids1, native_ids2); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.getMIContrastMatrix()(0, 0), 3.2776) TEST_REAL_SIMILAR(mrmscore.getMIContrastMatrix()(0, 1), 3.2776) TEST_REAL_SIMILAR(mrmscore.getMIContrastMatrix()(1, 1), 3.2776) TEST_REAL_SIMILAR(mrmscore.getMIContrastMatrix()(1, 0), 3.4594) } END_SECTION BOOST_AUTO_TEST_CASE(test_calcMIScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); mrmscore.initializeMIMatrix(imrmfeature, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcMIScore(), 3.3382) // mean + std deviation } END_SECTION BOOST_AUTO_TEST_CASE(test_calcSeparateMIContrastScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids1, native_ids2; fill_mock_objects(imrmfeature, native_ids1); for (int i=native_ids1.size()-1; i>=0; i--) { native_ids2.push_back(native_ids1[i]); } mrmscore.initializeMIContrastMatrix(imrmfeature, native_ids1, native_ids2); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcSeparateMIContrastScore()[0], 3.27761) TEST_REAL_SIMILAR(mrmscore.calcSeparateMIContrastScore()[1], 3.36852) } END_SECTION BOOST_AUTO_TEST_CASE(test_calcMIWeightedScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> native_ids; fill_mock_objects(imrmfeature, native_ids); static const double weights_[] = { 0.5, 0.5 }; std::vector<double> weights (weights_, weights_ + sizeof(weights_) / sizeof(weights_[0]) ); mrmscore.initializeMIMatrix(imrmfeature, native_ids); delete imrmfeature; // xcorr_deltas = [1, 0.3969832, 1] * array([0.25, 2*0.5*0.5,0.25]) // sum(xcorr_deltas) TEST_REAL_SIMILAR(mrmscore.calcMIWeightedScore(weights), 3.3231) } END_SECTION BOOST_AUTO_TEST_CASE(test_calcMIPrecursorContrastScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; std::vector<std::string> native_ids; fill_mock_objects2(imrmfeature, precursor_ids, native_ids); //initialize the XCorr vector mrmscore.initializeMIPrecursorContrastMatrix(imrmfeature, precursor_ids, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcMIPrecursorContrastScore(), 2.003257 ) } END_SECTION BOOST_AUTO_TEST_CASE(test_calcMIPrecursorCombinedScore) { MockMRMFeature * imrmfeature = new MockMRMFeature(); MRMScoring mrmscore; std::vector<std::string> precursor_ids; std::vector<std::string> native_ids; fill_mock_objects2(imrmfeature, precursor_ids, native_ids); //initialize the XCorr vector mrmscore.initializeMIPrecursorCombinedMatrix(imrmfeature, precursor_ids, native_ids); delete imrmfeature; TEST_REAL_SIMILAR(mrmscore.calcMIPrecursorCombinedScore(), 1.959490 ) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MzTabMFile_test.cpp
.cpp
1,720
60
// 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/MzTabMFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/FORMAT/OMSFile.h> #include <OpenMS/FORMAT/TextFile.h> #include <OpenMS/METADATA/ID/IdentificationDataConverter.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MzTabMFile, "$Id$") ///////////////////////////////////////////////////////////// MzTabMFile* ptr = nullptr; MzTabMFile* null_ptr = nullptr; START_SECTION(MzTabMFile()) { ptr = new MzTabMFile(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~MzTabFile()) { delete ptr; } END_SECTION START_SECTION(void store(const String& filename, MzTabM& mztab_m)) { FeatureMap feature_map; MzTabM mztabm; OMSFile().load(OPENMS_GET_TEST_DATA_PATH("MzTabMFile_input_1.oms"), feature_map); mztabm = MzTabM::exportFeatureMapToMzTabM(feature_map); String mztabm_tmpfile; NEW_TMP_FILE(mztabm_tmpfile); MzTabMFile().store(mztabm_tmpfile, mztabm); TEST_FILE_SIMILAR(mztabm_tmpfile.c_str(), OPENMS_GET_TEST_DATA_PATH("MzTabMFile_output_1.mztab")); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AASequence_test.cpp
.cpp
81,721
1,640
// 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 <map> #include <OpenMS/test_config.h> /////////////////////////// #ifdef _OPENMP #include <omp.h> #endif #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/CHEMISTRY/ResidueDB.h> #include <OpenMS/CHEMISTRY/ModificationsDB.h> #include <OpenMS/CONCEPT/Constants.h> #include <OpenMS/CONCEPT/LogStream.h> #include <iostream> #include <unordered_set> #include <functional> #include <OpenMS/SYSTEM/StopWatch.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(AASequence, "$Id$") ///////////////////////////////////////////////////////////// // AASequence seq = AASequence::fromString("PEPTM(Met->Hse)IDE"); // cout << seq.size() << endl; // cout << ModificationsDB::getInstance()->getModification("Acetyl", "", ResidueModification::N_TERM).getOrigin() << endl; AASequence* ptr = nullptr; AASequence* nullPointer = nullptr; START_SECTION(AASequence()) ptr = new AASequence(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~AASequence()) delete ptr; END_SECTION START_SECTION(AASequence(const AASequence& rhs)) AASequence seq; seq = AASequence::fromString("AAA"); AASequence seq2(seq); TEST_EQUAL(seq, seq2) END_SECTION START_SECTION(AASequence fromString(const String& s, bool permissive = true)) { AASequence seq = AASequence::fromString("CNARCKNCNCNARCDRE"); TEST_EQUAL(seq.isModified(), false) TEST_EQUAL(seq.hasNTerminalModification(), false); TEST_EQUAL(seq.hasCTerminalModification(), false); TEST_EQUAL(seq.getResidue(4).getModification(), 0); AASequence seq2; seq2 = AASequence::fromString("CNARCKNCNCNARCDRE"); TEST_EQUAL(seq, seq2); // test complex term-mods { AASequence seq3 = AASequence::fromString("VPQVSTPTLVEVSRSLGK(Label:18O(2))"); TEST_EQUAL(seq3.isModified(), true) TEST_EQUAL(seq3.hasNTerminalModification(), false); TEST_EQUAL(seq3.hasCTerminalModification(), true); TEST_EQUAL(seq3.getResidue(4).getModification(), 0); TEST_EQUAL(seq3.getCTerminalModificationName(), "Label:18O(2)"); AASequence seq4 = AASequence::fromString("VPQVSTPTLVEVSRSLGK(Label:18O(2))"); TEST_EQUAL(seq3, seq4); AASequence seq5 = AASequence::fromString("(ICPL:2H(4))CNARCNCNCN"); TEST_EQUAL(seq5.hasNTerminalModification(), true); TEST_EQUAL(seq5.isModified(), true); TEST_EQUAL(seq5.getNTerminalModificationName(), "ICPL:2H(4)"); AASequence seq6 = AASequence::fromString("CNARCK(Label:13C(6)15N(2))NCNCN"); TEST_EQUAL(seq6.hasNTerminalModification(), false); TEST_EQUAL(seq6.hasCTerminalModification(), false); TEST_EQUAL(seq6.isModified(), true); TEST_EQUAL(seq6.getResidue(5).getModificationName(), "Label:13C(6)15N(2)"); TEST_EQUAL(seq6.getResidue(4).getModificationName(), ""); AASequence seq7 = AASequence::fromString("CNARCKNCNCNARCDRE(Amidated)"); TEST_EQUAL(seq7.hasNTerminalModification(), false); TEST_EQUAL(seq7.hasCTerminalModification(), true); TEST_EQUAL(seq7.isModified(), true); TEST_EQUAL(seq7.getCTerminalModificationName(), "Amidated"); } // Test UniMod { AASequence seq3 = AASequence::fromString("PEPTIDEM(UniMod:10)"); TEST_EQUAL(seq3.hasNTerminalModification(), false); TEST_EQUAL(seq3.hasCTerminalModification(), true); TEST_EQUAL(seq3.isModified(), true); TEST_STRING_EQUAL(seq3.getCTerminalModification()->getFullId(), "Met->Hse (C-term M)"); // Also test lower-case unimod and equivalence // AASequence seq4 = AASequence::fromString("PEPTIDEM(unimod:10)"); TEST_EQUAL(seq4.hasNTerminalModification(), false); TEST_EQUAL(seq4.hasCTerminalModification(), true); TEST_EQUAL(seq4.isModified(), true); TEST_STRING_EQUAL(seq4.getCTerminalModification()->getFullId(), "Met->Hse (C-term M)"); TEST_EQUAL( AASequence::fromString(".(UniMod:1)PEPC(UniMod:4)PEPM(UniMod:35)PEPR.(UniMod:2)"), AASequence::fromString(".(unimod:1)PEPC(unimod:4)PEPM(unimod:35)PEPR.(unimod:2)") ) } // test square bracket modifications { AASequence seq8 = AASequence::fromString("PEPTIDEK[136]"); TEST_EQUAL(seq8.hasNTerminalModification(), false); TEST_EQUAL(seq8.hasCTerminalModification(), false); TEST_EQUAL(seq8.isModified(), true); TEST_STRING_EQUAL(seq8[7].getModificationName(), "Label:13C(6)15N(2)"); AASequence seq9 = AASequence::fromString("PEPS[167]TIDEK"); TEST_EQUAL(seq9.isModified(), true); TEST_STRING_EQUAL(seq9[3].getModificationName(), "Phospho"); AASequence seq10 = AASequence::fromString("PEPC[160]TIDEK"); TEST_EQUAL(seq10.isModified(), true); TEST_STRING_EQUAL(seq10[3].getModificationName(), "Carbamidomethyl"); AASequence seq11 = AASequence::fromString("PEPM[147]TIDEK"); TEST_EQUAL(seq11.isModified(), true); TEST_STRING_EQUAL(seq11[3].getModificationName(), "Oxidation"); AASequence seq12 = AASequence::fromString("PEPT[181]TIDEK"); TEST_EQUAL(seq12.isModified(), true); TEST_STRING_EQUAL(seq12[3].getModificationName(), "Phospho"); AASequence seq13 = AASequence::fromString("PEPY[243]TIDEK"); TEST_EQUAL(seq13.isModified(), true); TEST_STRING_EQUAL(seq13[3].getModificationName(), "Phospho"); AASequence seq14 = AASequence::fromString("PEPR[166]TIDEK"); TEST_EQUAL(seq14.isModified(), true); TEST_STRING_EQUAL(seq14[3].getModificationName(), "Label:13C(6)15N(4)"); // Test modifications of amino acids that can *only occur* N terminally // test case: "Pyro-carbamidomethyl" is only defined as N-terminal AASequence seq15 = AASequence::fromString("C[143]PEPTIDEK"); TEST_EQUAL(seq15.isModified(), true); TEST_EQUAL(seq15.hasNTerminalModification(), true) TEST_EQUAL(seq15.hasCTerminalModification(), false) TEST_EQUAL(seq15.getNTerminalModification() == nullptr, false); TEST_STRING_EQUAL(seq15.getNTerminalModification()->getId(), "Pyro-carbamidomethyl"); TEST_STRING_EQUAL(seq15.getNTerminalModification()->getFullId(), "Pyro-carbamidomethyl (N-term C)"); TEST_STRING_EQUAL(seq15.getNTerminalModificationName(), "Pyro-carbamidomethyl"); // test case: "Gln->pyro-Glu" is only defined as N-terminal AASequence seq16 = AASequence::fromString("Q[111]PEPTIDEK"); TEST_EQUAL(seq16.isModified(), true); TEST_EQUAL(seq16.hasNTerminalModification(), true) TEST_EQUAL(seq16.hasCTerminalModification(), false) TEST_EQUAL(seq16.getNTerminalModification() == nullptr, false); TEST_STRING_EQUAL(seq16.getNTerminalModification()->getId(), "Gln->pyro-Glu"); TEST_STRING_EQUAL(seq16.getNTerminalModification()->getFullId(), "Gln->pyro-Glu (N-term Q)"); TEST_STRING_EQUAL(seq16.getNTerminalModificationName(), "Gln->pyro-Glu"); AASequence seq17 = AASequence::fromString("[+42].MVLVQDLLHPTAASEAR"); TEST_EQUAL(seq17.hasNTerminalModification(), true) TEST_STRING_EQUAL(seq17.getNTerminalModification()->getId(), "Acetyl"); TEST_STRING_EQUAL(seq17.getNTerminalModification()->getFullId(), "Acetyl (N-term)"); TEST_STRING_EQUAL(seq17.getNTerminalModificationName(), "Acetyl"); AASequence seq18 = AASequence::fromString("[+304.207].ETC[+57.0215]RQLGLGTNIYNAER"); TEST_EQUAL(seq18.hasNTerminalModification(), true) TEST_STRING_EQUAL(seq18.getNTerminalModification()->getId(), "TMTpro"); TEST_STRING_EQUAL(seq18.getNTerminalModification()->getFullId(), "TMTpro (N-term)"); TEST_STRING_EQUAL(seq18.getNTerminalModificationName(), "TMTpro"); } // invalid test case: "Pyro-carbamidomethyl" is only defined as N-terminal // AASequence seq15 = AASequence::fromString("PEPC[143]TIDEK"); // TEST_EQUAL(seq15.isModified(), true); // TEST_STRING_EQUAL(seq15[3].getModificationName(), "Pyro-carbamidomethyl"); // invalid test case: "Gln->pyro-Glu" is only defined as N-terminal // AASequence seq16 = AASequence::fromString("PEPQ[111]TIDEK"); // TEST_EQUAL(seq16.isModified(), true); // TEST_STRING_EQUAL(seq16[3].getModificationName(), "Gln->pyro-Glu"); // invalid test case: "Glu->pyro-Glu" is only defined as N-terminal // AASequence seq17 = AASequence::fromString("PEPE[111]TIDEK"); // TEST_EQUAL(seq17.isModified(), true); // TEST_STRING_EQUAL(seq17[3].getModificationName(), "Glu->pyro-Glu"); TEST_EXCEPTION(Exception::ParseError, AASequence::fromString("blDABCDEF")); TEST_EXCEPTION(Exception::ParseError, AASequence::fromString("a")); // test "permissive" option: AASequence seq18 = AASequence::fromString("PEP T*I#D+E", true); TEST_EQUAL(seq18.size(), 10); TEST_EQUAL(seq18.toString(), "PEPTXIXDXE"); TEST_EXCEPTION(Exception::ParseError, AASequence::fromString("PEP T*I#D+E", false)); // invalid test case: N/C terminal mods need to be at the termini TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString("PEPTIDEM(UniMod:10)K")); TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString("PQ(UniMod:28)EPTIDEK")); TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString("PC(UniMod:26)EPTIDEK")); // prefer residue mod. over C-term mod.: AASequence seq19 = AASequence::fromString("PEPM(Oxidation)"); TEST_EQUAL(seq19.hasCTerminalModification(), false); TEST_EQUAL(seq19[3].isModified(), true); TEST_STRING_EQUAL(seq19[3].getModificationName(), "Oxidation"); // test peptide N-terminal and peptide C-terminal modifications { // peptide N-terminal AASequence seq1 = AASequence::fromString("(UniMod:28)QPEPTIDEK"); TEST_EQUAL(seq1.isModified(), true); TEST_EQUAL(seq1.hasNTerminalModification(), true) TEST_EQUAL(seq1.hasCTerminalModification(), false) TEST_EQUAL(seq1.getNTerminalModification() == nullptr, false); TEST_STRING_EQUAL(seq1.getNTerminalModification()->getFullId(), "Gln->pyro-Glu (N-term Q)"); // peptide C-terminal AASequence seq2 = AASequence::fromString("PEPTIDEM.(UniMod:10)"); TEST_EQUAL(seq2.hasNTerminalModification(), false); TEST_EQUAL(seq2.hasCTerminalModification(), true); TEST_EQUAL(seq2.getCTerminalModification() == nullptr, false); TEST_EQUAL(seq2.isModified(), true); TEST_STRING_EQUAL(seq2.getCTerminalModification()->getFullId(), "Met->Hse (C-term M)"); // no terminal dot seq2 = AASequence::fromString("PEPTIDEM(UniMod:10)"); TEST_STRING_EQUAL(seq2.getCTerminalModification()->getFullId(), "Met->Hse (C-term M)"); // test protein N-term modification AASequence seq3 = AASequence::fromString("(UniMod:51)CPEPTIDE"); // <umod:mod title="Tripalmitate" full_name="N-acyl diglyceride cysteine" TEST_REAL_SIMILAR(seq3.getMonoWeight(), double(902.3691545801998 + 788.725777)); TEST_EQUAL(seq3.getNTerminalModification() == nullptr, false); TEST_EQUAL(seq3.hasNTerminalModification(), true); TEST_EQUAL(seq3.hasCTerminalModification(), false); TEST_EQUAL(seq3.isModified(), true); TEST_STRING_EQUAL(seq3.getNTerminalModification()->getFullId(), "Tripalmitate (Protein N-term C)"); // test Skyline protein N-terminal modification AASequence seq_skyline = AASequence::fromString("M(unimod:1)FENITAAPADPILGLADLFR"); TEST_EQUAL(seq_skyline.getNTerminalModification() == nullptr, false); TEST_EQUAL(seq_skyline.hasNTerminalModification(), true); TEST_EQUAL(seq_skyline.hasCTerminalModification(), false); TEST_EQUAL(seq_skyline.isModified(), true); TEST_STRING_EQUAL(seq_skyline.getNTerminalModification()->getFullId(), "Acetyl (N-term)"); // test protein C-term modification AASequence seq4 = AASequence::fromString("PEPTIDEK.(UniMod:313)"); // <umod:mod title="Lys-loss" full_name="Loss of C-terminal K from Heavy Chain of MAb" TEST_REAL_SIMILAR(seq4.getMonoWeight(), double(927.4549330734999 - 128.094963)); TEST_EQUAL(seq4.getCTerminalModification() == nullptr, false); TEST_EQUAL(seq4.hasCTerminalModification(), true); TEST_EQUAL(seq4.hasNTerminalModification(), false); TEST_EQUAL(seq4.isModified(), true); TEST_STRING_EQUAL(seq4.getCTerminalModification()->getFullId(), "Lys-loss (Protein C-term K)"); // no terminal dot seq4 = AASequence::fromString("PEPTIDEK(UniMod:313)"); TEST_EQUAL(seq4[7].isModified(), true); TEST_STRING_EQUAL(seq4[7].getModificationName(), "Lys-loss"); TEST_STRING_EQUAL(seq4.getResidue(7).getModification()->getFullId(), "Lys-loss (K)"); } // test with Selenocysteine { AASequence seq = AASequence::fromString("PEPTIDESEKUEM(Oxidation)CER"); TEST_EQUAL(seq.toUniModString(), "PEPTIDESEKUEM(UniMod:35)CER") TEST_EQUAL(seq.getFormula(), EmpiricalFormula("C75H122N20O32S2Se1")) TEST_REAL_SIMILAR(EmpiricalFormula("C75H122N20O32S2").getMonoWeight(), 1878.7975553518002) // note that the monoisotopic weight of Selenium is 80 and not 74 TEST_REAL_SIMILAR(EmpiricalFormula("C75H122N20O32S2Se1").getAverageWeight(), 1958.981404189803) TEST_REAL_SIMILAR(EmpiricalFormula("C75H122N20O32S2Se1").getMonoWeight(), 1958.7140766518) TEST_REAL_SIMILAR(seq.getMonoWeight(), 1958.7140766518) TEST_REAL_SIMILAR(seq.getAverageWeight(), 1958.981404189803) } } END_SECTION START_SECTION(AASequence& operator=(const AASequence& rhs)) AASequence seq = AASequence::fromString("AAA"); AASequence seq2 = AASequence::fromString("AAA"); TEST_EQUAL(seq, seq2) END_SECTION START_SECTION(([EXTRA]Test modifications with brackets)) AASequence seq1 = AASequence::fromString("ANLVFK(Label:13C(6)15N(2))EIEK(Label:2H(4))"); TEST_EQUAL(seq1.hasNTerminalModification(), false) TEST_EQUAL(seq1.hasCTerminalModification(), false) TEST_EQUAL(seq1.isModified(), true) AASequence seq2 = AASequence::fromString("ANLVFK(Label:13C(6)15N(2))EIEK(Label:2H(4))(Amidated)"); TEST_EQUAL(seq2.hasNTerminalModification(), false) TEST_EQUAL(seq2.hasCTerminalModification(), true) TEST_EQUAL(seq2.isModified(), true) END_SECTION START_SECTION(bool operator==(const AASequence& rhs) const) AASequence seq1 = AASequence::fromString("(Acetyl)DFPIANGER"); AASequence seq2 = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq2 == AASequence::fromString("DFPIANGER"), true) TEST_EQUAL(seq1 == AASequence::fromString("(Acetyl)DFPIANGER"), true) AASequence seq3 = AASequence::fromString("DFPIANGER(ADP-Ribosyl)"); AASequence seq4 = AASequence::fromString("DFPIANGER(Amidated)"); TEST_EQUAL(seq3 == AASequence::fromString("DFPIANGER"), false) TEST_EQUAL(seq3 == AASequence::fromString("DFPIANGER(ADP-Ribosyl)"), true) TEST_EQUAL(seq4 == AASequence::fromString("DFPIANGER(Amidated)"), true) TEST_EQUAL(seq4 == AASequence::fromString("DFPIANGER"), false) AASequence seq5 = AASequence::fromString("DFBIANGER"); TEST_EQUAL(seq5 == AASequence::fromString("DFPIANGER"), false) TEST_EQUAL(seq5 == AASequence::fromString("DFBIANGER"), true) END_SECTION START_SECTION(const Residue& getResidue(Size index) const) AASequence seq = AASequence::fromString("ACDEF"); Size unsignedint(2); TEST_EQUAL(seq.getResidue(unsignedint).getOneLetterCode(), "D") TEST_EXCEPTION(Exception::IndexOverflow, seq.getResidue((Size)1000)) END_SECTION START_SECTION((EmpiricalFormula getFormula(Residue::ResidueType type = Residue::Full, Int charge=0) const)) AASequence seq = AASequence::fromString("ACDEF"); TEST_EQUAL(seq.getFormula(), EmpiricalFormula("O10SH33N5C24")) TEST_EQUAL(seq.getFormula(Residue::Full, 1), EmpiricalFormula("O10SH33N5C24+")) TEST_EQUAL(seq.getFormula(Residue::BIon, 0), EmpiricalFormula("O9SH31N5C24")) END_SECTION START_SECTION((double getAverageWeight(Residue::ResidueType type = Residue::Full, Int charge=0) const)) AASequence seq = AASequence::fromString("DFPIANGER"); TOLERANCE_ABSOLUTE(0.01) TEST_REAL_SIMILAR(seq.getAverageWeight(), double(1018.08088)) TEST_REAL_SIMILAR(seq.getAverageWeight(Residue::YIon, 1), double(1019.09)) END_SECTION START_SECTION((double getMonoWeight(Residue::ResidueType type = Residue::Full, Int charge=0) const)) { TOLERANCE_ABSOLUTE(1e-6) TOLERANCE_RELATIVE(1.0 + 1e-6) // test if fragments of charged single amino acid sequences match the charged residue weight of the fragment ions EmpiricalFormula ala_res = EmpiricalFormula("C3H5NO"); TEST_REAL_SIMILAR(AASequence::fromString("A").getMonoWeight(Residue::Internal, 0), ala_res.getMonoWeight()); EmpiricalFormula ala_full = ala_res + EmpiricalFormula("H2O"); TEST_REAL_SIMILAR(AASequence::fromString("A").getMonoWeight(Residue::Full, 0), ala_full.getMonoWeight()); EmpiricalFormula ala_a_neutral = EmpiricalFormula("H")+ala_res-EmpiricalFormula("CHO"); TEST_REAL_SIMILAR(AASequence::fromString("A").getMonoWeight(Residue::AIon, 1), ala_a_neutral.getMonoWeight()+Constants::PROTON_MASS_U); //44.04947 EmpiricalFormula ala_b_neutral = EmpiricalFormula("H")+ala_res-EmpiricalFormula("H"); TEST_REAL_SIMILAR(AASequence::fromString("A").getMonoWeight(Residue::BIon, 1), ala_b_neutral.getMonoWeight()+Constants::PROTON_MASS_U); //72.04439 EmpiricalFormula ala_y_neutral = EmpiricalFormula("OH")+ala_res+EmpiricalFormula("H"); TEST_REAL_SIMILAR(AASequence::fromString("A").getMonoWeight(Residue::YIon, 1), ala_y_neutral.getMonoWeight()+Constants::PROTON_MASS_U); //90.05496 EmpiricalFormula ala_z_neutral = EmpiricalFormula("OH")+ala_res-EmpiricalFormula("NH2"); TEST_REAL_SIMILAR(AASequence::fromString("A").getMonoWeight(Residue::ZIon, 1), ala_z_neutral.getMonoWeight()+Constants::PROTON_MASS_U); //73.02900 TEST_REAL_SIMILAR(AASequence::fromString("DFPIANGER").getMonoWeight(), double(1017.48796)) // test if direct calculation and calculation via empirical formula yield the same result TEST_REAL_SIMILAR(AASequence::fromString("DFPIANGER").getMonoWeight(Residue::YIon, 1), AASequence::fromString("DFPIANGER").getFormula(Residue::YIon, 1).getMonoWeight()) TEST_REAL_SIMILAR(AASequence::fromString("DFPIANGER").getMonoWeight(Residue::YIon, 1), double(1018.4952)) // test N-term modification AASequence seq2 = AASequence::fromString("(NIC)DFPIANGER"); TEST_REAL_SIMILAR(seq2.getMonoWeight(), double(1122.51)); // test protein N-term modification AASequence seq2b = AASequence::fromString("(UniMod:51)CPEPTIDE"); // <umod:mod title="Tripalmitate" full_name="N-acyl diglyceride cysteine" TEST_REAL_SIMILAR(seq2b.getMonoWeight(), double(902.3691545801998 + 788.725777)); // test old OpenMS NIC definition AASequence seq2a = AASequence::fromString("(MOD:09998)DFPIANGER"); TEST_TRUE(seq2 == seq2a) // test heavy modification AASequence seq3 = AASequence::fromString("(dNIC)DFPIANGER"); TEST_REAL_SIMILAR(seq3.getMonoWeight(), double(1017.48796) + double(109.048119)); // test old OpenMS dNIC definition AASequence seq3a = AASequence::fromString("(MOD:09999)DFPIANGER"); TEST_TRUE(seq3 == seq3a) TEST_REAL_SIMILAR(AASequence::fromString("TYQYS(Phospho)").getFormula().getMonoWeight(), AASequence::fromString("TYQYS(Phospho)").getMonoWeight()); TEST_REAL_SIMILAR(AASequence::fromString("TYQYS(Phospho)").getFormula().getMonoWeight(), AASequence::fromString("TYQYS(Phospho)").getMonoWeight()); } END_SECTION START_SECTION((double getMZ(Int charge, Residue::ResidueType type = Residue::Full) const)) { TOLERANCE_ABSOLUTE(1e-6) TOLERANCE_RELATIVE(1.0 + 1e-6) // uses getMonoWeight and is thus thoroughly tested TEST_REAL_SIMILAR(AASequence::fromString("DFPIANGER").getMZ(1, Residue::YIon), double(1018.4952)) TEST_REAL_SIMILAR(AASequence::fromString("DFPIANGER").getMZ(2, Residue::YIon), double((1018.4952 + Constants::PROTON_MASS_U) / 2.0)) TEST_EXCEPTION(OpenMS::Exception::InvalidValue, AASequence::fromString("DFPIANGER").getMZ(0)); } END_SECTION START_SECTION(const Residue& operator[](Size index) const) AASequence seq = AASequence::fromString("DFPIANGER"); Size index = 0; TEST_EQUAL(seq[index].getOneLetterCode(), "D") index = 20; TEST_EXCEPTION(Exception::IndexOverflow, seq[index]) END_SECTION START_SECTION(AASequence operator+(const AASequence& peptide) const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("DFP"); AASequence seq3 = AASequence::fromString("IANGER"); TEST_EQUAL(seq1, seq2 + seq3); END_SECTION START_SECTION(AASequence operator+(const Residue* residue) const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("DFPIANGE"); TEST_EQUAL(seq1, seq2 + ResidueDB::getInstance()->getResidue("R")) END_SECTION START_SECTION(AASequence& operator+=(const AASequence&)) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("DFP"); AASequence seq3 = AASequence::fromString("IANGER"); seq2 += seq3; TEST_EQUAL(seq1, seq2) END_SECTION START_SECTION(AASequence& operator+=(const Residue* residue)) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("DFPIANGE"); seq2 += ResidueDB::getInstance()->getResidue("R"); TEST_EQUAL(seq1, seq2) END_SECTION START_SECTION(Size size() const) AASequence seq1 = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq1.size(), 9) END_SECTION START_SECTION(AASequence getPrefix(Size index) const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("DFP"); AASequence seq3 = AASequence::fromString("DFPIANGER"); AASequence seq4 = AASequence::fromString("(TMT6plex)DFPIANGER"); AASequence seq5 = AASequence::fromString("DFPIANGER(Label:18O(2))"); AASequence seq6 = AASequence::fromString("DFPIANGERR(Label:18O(2))"); TEST_EQUAL(seq2, seq1.getPrefix(3)); TEST_EQUAL(seq3, seq1.getPrefix(9)); TEST_NOT_EQUAL(seq4.getPrefix(3), seq1.getPrefix(3)) TEST_NOT_EQUAL(seq5.getPrefix(9), seq1.getPrefix(9)) TEST_EQUAL(seq6.getPrefix(9), seq1.getPrefix(9)) TEST_EXCEPTION(Exception::IndexOverflow, seq1.getPrefix(10)) END_SECTION START_SECTION(AASequence getSuffix(Size index) const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("GER"); AASequence seq3 = AASequence::fromString("DFPIANGER"); AASequence seq4 = AASequence::fromString("DFPIANGER(Label:18O(2))"); AASequence seq5 = AASequence::fromString("(TMT6plex)DFPIANGER"); AASequence seq6 = AASequence::fromString("(TMT6plex)DDFPIANGER"); TEST_EQUAL(seq2, seq1.getSuffix(3)); TEST_EQUAL(seq3, seq1.getSuffix(9)); TEST_NOT_EQUAL(seq4.getSuffix(3), seq1.getSuffix(3)) TEST_NOT_EQUAL(seq5.getSuffix(9), seq1.getSuffix(9)) TEST_EQUAL(seq6.getSuffix(9), seq1.getSuffix(9)) TEST_EXCEPTION(Exception::IndexOverflow, seq1.getSuffix(10)) END_SECTION START_SECTION(AASequence getSubsequence(Size index, UInt number) const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("IAN"); AASequence seq3 = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq2, seq1.getSubsequence(3, 3)) TEST_EQUAL(seq3, seq1.getSubsequence(0, 9)) TEST_EXCEPTION(Exception::IndexOverflow, seq1.getSubsequence(0, 10)) END_SECTION START_SECTION(bool has(const Residue& residue) const) AASequence seq = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq.has(seq[(Size)0]), true) Residue res; TEST_NOT_EQUAL(seq.has(res), true) END_SECTION START_SECTION(bool hasSubsequence(const AASequence& peptide) const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("IANG"); AASequence seq3 = AASequence::fromString("DFPP"); TEST_EQUAL(seq1.hasSubsequence(seq2), true) TEST_EQUAL(seq1.hasSubsequence(seq3), false) END_SECTION START_SECTION(bool hasPrefix(const AASequence& peptide) const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("DFP"); AASequence seq3 = AASequence::fromString("AIN"); AASequence seq4 = AASequence::fromString("(TMT6plex)DFP"); AASequence seq5 = AASequence::fromString("DFPIANGER(Label:18O(2))"); AASequence seq6 = AASequence::fromString("DFP(Label:18O(2))"); TEST_EQUAL(seq1.hasPrefix(seq2), true) TEST_EQUAL(seq1.hasPrefix(seq3), false) TEST_EQUAL(seq1.hasPrefix(seq4), false) TEST_EQUAL(seq1.hasPrefix(seq5), false) TEST_EQUAL(seq1.hasPrefix(seq6), true) END_SECTION START_SECTION(bool hasSuffix(const AASequence& peptide) const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("GER"); AASequence seq3 = AASequence::fromString("AIN"); AASequence seq4 = AASequence::fromString("GER(Label:18O(2))"); AASequence seq5 = AASequence::fromString("(TMT6plex)DFPIANGER"); AASequence seq6 = AASequence::fromString("(TMT6plex)GER"); TEST_EQUAL(seq1.hasSuffix(seq2), true) TEST_EQUAL(seq1.hasSuffix(seq3), false) TEST_EQUAL(seq1.hasSuffix(seq4), false) TEST_EQUAL(seq1.hasSuffix(seq5), false) TEST_EQUAL(seq1.hasSuffix(seq6), true) END_SECTION START_SECTION(ConstIterator begin() const) String result[] = { "D", "F", "P", "I", "A", "N", "G", "E", "R" }; AASequence seq = AASequence::fromString("DFPIANGER"); Size i = 0; for (AASequence::ConstIterator it = seq.begin(); it != seq.end(); ++it, ++i) { TEST_EQUAL((*it).getOneLetterCode(), result[i]) } END_SECTION START_SECTION(ConstIterator end() const) NOT_TESTABLE END_SECTION START_SECTION(Iterator begin()) String result[] = { "D", "F", "P", "I", "A", "N", "G", "E", "R" }; AASequence seq = AASequence::fromString("DFPIANGER"); Size i = 0; for (AASequence::ConstIterator it = seq.begin(); it != seq.end(); ++it, ++i) { TEST_EQUAL((*it).getOneLetterCode(), result[i]) } END_SECTION START_SECTION(Iterator end()) NOT_TESTABLE END_SECTION //START_SECTION(friend std::ostream& operator << (std::ostream& os, const AASequence& peptide)) // // TODO //END_SECTION //START_SECTION(friend std::istream& operator > (std::istream& is, const AASequence& peptide)) // // TODO //END_SECTION START_SECTION(String toString() const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("(MOD:00051)DFPIANGER"); AASequence seq3 = AASequence::fromString("DFPIAN(Deamidated)GER"); TEST_STRING_EQUAL(seq1.toString(), "DFPIANGER") TEST_STRING_EQUAL(seq2.toString(), ".(MOD:00051)DFPIANGER") TEST_STRING_EQUAL(seq3.toString(), "DFPIAN(Deamidated)GER") END_SECTION START_SECTION(String toUnmodifiedString() const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("(MOD:00051)DFPIANGER"); AASequence seq3 = AASequence::fromString("DFPIAN(Deamidated)GER"); TEST_STRING_EQUAL(seq1.toUnmodifiedString(), "DFPIANGER") TEST_STRING_EQUAL(seq2.toUnmodifiedString(), "DFPIANGER") TEST_STRING_EQUAL(seq3.toUnmodifiedString(), "DFPIANGER") END_SECTION START_SECTION(String toUniModString() const) AASequence s = AASequence::fromString("PEPC(Carbamidomethyl)PEPM(Oxidation)PEPR"); TEST_STRING_EQUAL(s.toUniModString(), "PEPC(UniMod:4)PEPM(UniMod:35)PEPR"); s.setNTerminalModification("Acetyl (N-term)"); s.setCTerminalModification("Amidated (C-term)"); TEST_STRING_EQUAL(s.toUniModString(), ".(UniMod:1)PEPC(UniMod:4)PEPM(UniMod:35)PEPR.(UniMod:2)"); END_SECTION START_SECTION(String toBracketString(const std::vector<String> & fixed_modifications = std::vector<String>()) const) AASequence s = AASequence::fromString("PEPC(Carbamidomethyl)PEPM(Oxidation)PEPR"); TEST_STRING_EQUAL(s.toBracketString(), "PEPC[160]PEPM[147]PEPR"); vector<String> fixed_mods; fixed_mods.push_back("Carbamidomethyl (C)"); TEST_STRING_EQUAL(s.toBracketString(true, false, fixed_mods), "PEPCPEPM[147]PEPR"); TEST_STRING_SIMILAR(s.toBracketString(false, false, fixed_mods), "PEPCPEPM[147.0354000171]PEPR"); TEST_STRING_EQUAL(s.toBracketString(true, true, fixed_mods), "PEPCPEPM[+16]PEPR"); s.setNTerminalModification("Acetyl (N-term)"); s.setCTerminalModification("Amidated (C-term)"); TEST_STRING_EQUAL(s.toBracketString(true, false, fixed_mods), "n[43]PEPCPEPM[147]PEPRc[16]"); TEST_STRING_SIMILAR(s.toBracketString(false, false, fixed_mods), "n[43.0183900319]PEPCPEPM[147.0354000171]PEPRc[16.0187240319]"); TEST_STRING_EQUAL(s.toBracketString(true, true, fixed_mods), "n[+42]PEPCPEPM[+16]PEPRc[-1]"); fixed_mods.push_back("Acetyl (N-term)"); fixed_mods.push_back("Amidated (C-term)"); TEST_STRING_EQUAL(s.toBracketString(true, false, fixed_mods), "PEPCPEPM[147]PEPR"); TEST_STRING_SIMILAR(s.toBracketString(false, false, fixed_mods), "PEPCPEPM[147.0354000171]PEPR"); TEST_STRING_EQUAL(s.toBracketString(true, true, fixed_mods), "PEPCPEPM[+16]PEPR"); END_SECTION START_SECTION(void setModification(Size index, const String &modification)) AASequence seq1 = AASequence::fromString("ACDEFNEK"); seq1.setModification(5, "Deamidated"); TEST_STRING_EQUAL(seq1[5].getModificationName(), "Deamidated"); // remove modification seq1.setModification(5, ""); TEST_STRING_EQUAL(seq1.toString(), "ACDEFNEK") seq1.setModificationByDiffMonoMass(5, 0.984); TEST_STRING_EQUAL(seq1.toString(), "ACDEFN(Deamidated)EK") seq1.setModificationByDiffMonoMass(3, -1.234); TEST_STRING_EQUAL(seq1.toString(), "ACDE[-1.234]FN(Deamidated)EK") TEST_PRECONDITION_VIOLATED(seq1.setModification(1, seq1[3].getModification())) seq1.setModificationByDiffMonoMass(1, seq1[3].getModification()->getDiffMonoMass()); TEST_STRING_EQUAL(seq1.toString(), "AC[-1.234]DE[-1.234]FN(Deamidated)EK") seq1.setModification(6, seq1[3].getModification()); // now the AA origin fits TEST_STRING_EQUAL(seq1.toString(), "AC[-1.234]DE[-1.234]FN(Deamidated)E[-1.234]K") END_SECTION START_SECTION(void setNTerminalModification(const String &modification)) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("(MOD:00051)DFPIANGER"); TEST_EQUAL(seq1 == seq2, false) seq1.setNTerminalModification("MOD:00051"); TEST_TRUE(seq1 == seq2) AASequence seq3 = AASequence::fromString("DABCDEF"); AASequence seq4 = AASequence::fromString("(MOD:00051)DABCDEF"); TEST_EQUAL(seq3 == seq4, false) seq3.setNTerminalModification("MOD:00051"); TEST_EQUAL(seq3.isModified(), true) TEST_EQUAL(seq4.isModified(), true) TEST_TRUE(seq3 == seq4) AASequence seq5 = AASequence::fromString("DABCDEF"); AASequence seq6 = seq5; AASequence seq7 = seq5; AASequence seq8 = seq5; seq5.setNTerminalModification("Met-loss (Protein N-term M)"); TEST_EQUAL(seq5.isModified(), true) seq6.setNTerminalModification("Acetyl (N-term)"); TEST_EQUAL(seq6.isModified(), true) seq7.setCTerminalModification("Amidated (C-term)"); TEST_EQUAL(seq7.isModified(), true) TEST_EXCEPTION(OpenMS::Exception::InvalidValue, seq8.setCTerminalModification("T")); TEST_EXCEPTION(OpenMS::Exception::InvalidValue, seq8.setCTerminalModification("T)")); TEST_EXCEPTION(OpenMS::Exception::InvalidValue, seq8.setCTerminalModification("(T)")); TEST_EXCEPTION(OpenMS::Exception::InvalidValue, seq8.setCTerminalModification("foobar")); END_SECTION START_SECTION(const String& getNTerminalModificationName() const) AASequence seq1 = AASequence::fromString("(MOD:00051)DFPIANGER"); TEST_EQUAL(seq1.getNTerminalModificationName(), "MOD:00051"); AASequence seq2 = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq2.getNTerminalModificationName(), ""); END_SECTION START_SECTION(const ResidueModification* getNTerminalModification() const) AASequence seq1 = AASequence::fromString("(Formyl)DFPIANGER"); TEST_EQUAL(seq1.getNTerminalModification()->getId(), "Formyl"); TEST_EQUAL(seq1.getNTerminalModification()->getFullId(), "Formyl (N-term)"); AASequence seq2 = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq2.getNTerminalModification(), 0); END_SECTION START_SECTION(const ResidueModification* getCTerminalModification() const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("DFPIANGER(Amidated)"); TEST_EQUAL(seq2.getCTerminalModification()->getId(), "Amidated"); TEST_EQUAL(seq2.getCTerminalModification()->getFullId(), "Amidated (C-term)"); TEST_EQUAL(seq1.getCTerminalModification(), 0); END_SECTION START_SECTION(void setCTerminalModification(const String& modification)) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("DFPIANGER(Amidated)"); TEST_EQUAL(seq1 == seq2, false) seq1.setCTerminalModification("Amidated"); TEST_TRUE(seq1 == seq2) AASequence seq3 = AASequence::fromString("DABCDER"); AASequence seq4 = AASequence::fromString("DABCDER(Amidated)"); TEST_EQUAL(seq3 == seq4, false) seq3.setCTerminalModification("Amidated"); TEST_EQUAL(seq3.isModified(), true) TEST_EQUAL(seq4.isModified(), true) TEST_TRUE(seq3 == seq4) AASequence seq5 = AASequence::fromString("DABCDER(MOD:00177)"); AASequence seq6 = AASequence::fromString("DABCDER(MOD:00177)(Amidated)"); TEST_EQUAL(seq5.isModified(), true) TEST_EQUAL(seq6.isModified(), true) seq5.setCTerminalModification("Amidated"); TEST_TRUE(seq5 == seq6) AASequence seq7 = AASequence::fromString("DFPIANGER(MOD:00177)"); AASequence seq8 = AASequence::fromString("DFPIANGER(MOD:00177)(Amidated)"); TEST_EQUAL(seq7.isModified(), true) TEST_EQUAL(seq8.isModified(), true) seq7.setCTerminalModification("Amidated"); TEST_TRUE(seq5 == seq6) END_SECTION START_SECTION(const String& getCTerminalModificationName() const) AASequence seq1 = AASequence::fromString("DFPIANGER(Amidated)"); TEST_EQUAL(seq1.getCTerminalModificationName(), "Amidated"); AASequence seq2 = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq2.getCTerminalModificationName(), ""); END_SECTION START_SECTION(bool hasNTerminalModification() const) AASequence seq1 = AASequence::fromString("(MOD:00051)DABCDEF"); AASequence seq2 = AASequence::fromString("DABCDEF"); TEST_EQUAL(seq1.hasNTerminalModification(), true) TEST_EQUAL(seq2.hasNTerminalModification(), false) AASequence seq3 = AASequence::fromString("(MOD:00051)DFPIANGER"); AASequence seq4 = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq3.hasNTerminalModification(), true) TEST_EQUAL(seq4.hasNTerminalModification(), false) END_SECTION START_SECTION(bool hasCTerminalModification() const) AASequence seq1 = AASequence::fromString("DFPIANGER(Amidated)"); AASequence seq2 = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq1.hasCTerminalModification(), true) TEST_EQUAL(seq2.hasCTerminalModification(), false) seq1.setCTerminalModification(""); TEST_EQUAL(seq1.hasCTerminalModification(), false) END_SECTION START_SECTION(bool isModified() const) AASequence seq1 = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq1.isModified(), false); AASequence seq2(seq1); seq2.setNTerminalModification("MOD:09999"); TEST_EQUAL(seq2.isModified(), true) AASequence seq3(seq1); seq3.setCTerminalModification("Amidated"); TEST_EQUAL(seq3.isModified(), true); AASequence seq4 = AASequence::fromString("DFPIANGER(MOD:00177)"); TEST_EQUAL(seq4.isModified(), true); END_SECTION START_SECTION(bool operator<(const AASequence &rhs) const) AASequence seq1 = AASequence::fromString("DFPIANGER"); AASequence seq2 = AASequence::fromString("DFBIANGER"); TEST_EQUAL(seq2 < seq1, true) TEST_EQUAL(seq1 < seq2, false) AASequence seq3 = AASequence::fromString("DFPIANGFR"); TEST_EQUAL(seq3 < seq1, false) // shorter residue sequence is smaller than longer one TEST_EQUAL(AASequence::fromString("PPP") < AASequence::fromString("AAAA"), true) TEST_EQUAL(AASequence::fromString("PM(Oxidation)P") < AASequence::fromString("AAAA"), true) // modified is larger than unmodified TEST_EQUAL(AASequence::fromString("MMM") < AASequence::fromString("MM(Oxidation)M"), true) TEST_EQUAL(AASequence::fromString("ARRR") < AASequence::fromString("ARRR(Label:13C(6))"), true) TEST_EQUAL(AASequence::fromString("CNR") < AASequence::fromString("(ICPL:2H(4))CNR"), true) TEST_EQUAL(AASequence::fromString("(ICPL:2H(4))CNAR") < AASequence::fromString("(ICPL:13C(6))YCYCY"), true) // alphabetic order TEST_EQUAL(AASequence::fromString("AAA") < AASequence::fromString("AAM"), true) TEST_EQUAL(AASequence::fromString("AAM") < AASequence::fromString("AMA"), true) TEST_EQUAL(AASequence::fromString("AMA") < AASequence::fromString("MAA"), true) // if N-terminal mods. are the same, check the sequence TEST_EQUAL(AASequence::fromString("(ICPL:2H(4))AMA") < AASequence::fromString("(ICPL:2H(4))MAA"), true) TEST_EQUAL(AASequence::fromString("(ICPL:2H(4))MAA") < AASequence::fromString("(ICPL:2H(4))AMA"), false) // if everything else is the same, check the C-terminal mods. TEST_EQUAL(AASequence::fromString("(ICPL:2H(4))AMA(Amidated)") < AASequence::fromString("(ICPL:2H(4))AMA(Label:18O(2))"), true) TEST_EQUAL(AASequence::fromString("(ICPL:2H(4))AMA(Label:18O(2))") < AASequence::fromString("(ICPL:2H(4))AMA(Amidated)"), false) END_SECTION START_SECTION(bool operator!=(const AASequence& rhs) const) AASequence seq1 = AASequence::fromString("(MOD:00051)DFPIANGER"); AASequence seq2 = AASequence::fromString("DFPIANGER"); TEST_EQUAL(seq2 != AASequence::fromString("DFPIANGER"), false) TEST_EQUAL(seq1 != AASequence::fromString("(MOD:00051)DFPIANGER"), false) // test C-terminal mods AASequence seq3 = AASequence::fromString("DFPIANGER(MOD:00177)"); AASequence seq4 = AASequence::fromString("DFPIANGER(Amidated)"); TEST_EQUAL(seq3 != AASequence::fromString("DFPIANGER"), true) TEST_EQUAL(seq3 != AASequence::fromString("DFPIANGER(MOD:00177)"), false) TEST_EQUAL(seq4 != AASequence::fromString("DFPIANGER(Amidated)"), false) TEST_EQUAL(seq4 != AASequence::fromString("DFPIANGER"), true) // test inner mods TEST_EQUAL(AASequence::fromString("DFPMIANGER") != AASequence::fromString("DFPM(Oxidation)IANGER"), true) TEST_EQUAL(AASequence::fromString("DFPM(Oxidation)IANGER") == AASequence::fromString("DFPM(Oxidation)IANGER"), true) AASequence seq5 = AASequence::fromString("DFBIANGER"); TEST_EQUAL(seq5 != AASequence::fromString("DFPIANGER"), true) TEST_EQUAL(seq5 != AASequence::fromString("DFBIANGER"), false) END_SECTION START_SECTION(void getAAFrequencies(Map<String, Size>& frequency_table) const) AASequence a = AASequence::fromString("THREEAAAWITHYYY"); std::map<String, Size> table; a.getAAFrequencies(table); TEST_EQUAL(table["T"]==2, true); TEST_EQUAL(table["H"]==2, true); TEST_EQUAL(table["R"]==1, true); TEST_EQUAL(table["E"]==2, true); TEST_EQUAL(table["A"]==3, true); TEST_EQUAL(table["W"]==1, true); TEST_EQUAL(table["I"]==1, true); TEST_EQUAL(table["Y"]==3, true); TEST_EQUAL(table.size()==8, true); END_SECTION START_SECTION([EXTRA] Tag in peptides) { AASequence aa1 = AASequence::fromString("PEPTC[+57.02]IDE"); // 57.021464 AASequence aa2 = AASequence::fromString("PEPTC(Carbamidomethyl)IDE"); AASequence aa3 = AASequence::fromString("PEPTC(UniMod:4)IDE"); AASequence aa4 = AASequence::fromString("PEPTC(Iodoacetamide derivative)IDE"); AASequence aa5 = AASequence::fromString("PEPTC[160.030654]IDE"); AASequence aa6 = AASequence::fromString("PEPTX[160.030654]IDE"); TEST_REAL_SIMILAR(aa1.getMonoWeight(), 959.39066) TEST_REAL_SIMILAR(aa2.getMonoWeight(), 959.39066) TEST_REAL_SIMILAR(aa3.getMonoWeight(), 959.39066) TEST_REAL_SIMILAR(aa4.getMonoWeight(), 959.39066) TEST_REAL_SIMILAR(aa5.getMonoWeight(), 959.39066) TEST_REAL_SIMILAR(aa6.getMonoWeight(), 959.39066) TEST_EQUAL(aa1.size(), 8) TEST_EQUAL(aa2.size(), 8) TEST_EQUAL(aa3.size(), 8) TEST_EQUAL(aa4.size(), 8) TEST_EQUAL(aa5.size(), 8) TEST_EQUAL(aa6.size(), 8) TEST_EQUAL(aa1.isModified(), true) TEST_EQUAL(aa2.isModified(), true) TEST_EQUAL(aa3.isModified(), true) TEST_EQUAL(aa4.isModified(), true) TEST_EQUAL(aa5.isModified(), true) TEST_EQUAL(aa6.isModified(), true) // Test negative mods / losses // test without loss TEST_REAL_SIMILAR(AASequence::fromString("PEPTMIDE").getMonoWeight(), 930.4004) // test with losses // known loss from unimod: Homoserine (should actually only happen at c-term but we allow it) TEST_REAL_SIMILAR(AASequence::fromString("PEPTM[-30]IDE").getMonoWeight(), 930.4004 - 29.992806) // new loss from unimod: Homoserine (should actually only happen at c-term but we allow it) TEST_REAL_SIMILAR(AASequence::fromString("PEPTM[-30.4004]IDE").getMonoWeight(), 900.0) TEST_EQUAL(AASequence::fromString("PEPTM[-30]IDE").size(), 8) TEST_EQUAL(AASequence::fromString("PEPTM[-30]IDE").isModified(), true) } END_SECTION START_SECTION([EXTRA] Arbitrary tag in peptides using square brackets) { // test arbitrary modification AASequence aa_original = AASequence::fromString("PEPTIDE"); TEST_REAL_SIMILAR(aa_original.getMonoWeight(), 799.36001) AASequence aa_half = AASequence::fromString("IDE"); TEST_REAL_SIMILAR(aa_half.getMonoWeight(), 375.1641677975) AASequence aa = AASequence::fromString("PEPTX[999]IDE"); TEST_REAL_SIMILAR(aa.getMonoWeight(), 799.36001 + 999.0) TEST_REAL_SIMILAR(aa.getMonoWeight(), aa_original.getMonoWeight() + 999.0) { AASequence aa = AASequence::fromString("PEPTX[999.0]IDE"); TEST_REAL_SIMILAR(aa.getMonoWeight(), 799.36001 + 999.0) TEST_REAL_SIMILAR(aa.getMonoWeight(), aa_original.getMonoWeight() + 999.0) } // test arbitrary differences (e.g. it should be possible to encode arbitrary masses and still get the correct weight) { AASequence test1 = AASequence::fromString("PEPTX[160.030654]IDE"); TEST_REAL_SIMILAR(test1.getMonoWeight(), aa_original.getMonoWeight() + 160.030654) AASequence test2 = AASequence::fromString("PEPTX[160.040654]IDE"); TEST_REAL_SIMILAR(test2.getMonoWeight(), aa_original.getMonoWeight() + 160.040654) AASequence test3 = AASequence::fromString("PEPTX[160.050654]IDE"); TEST_REAL_SIMILAR(test3.getMonoWeight(), aa_original.getMonoWeight() + 160.050654) AASequence test4 = AASequence::fromString("PEPTX[160.130654]IDE"); TEST_REAL_SIMILAR(test4.getMonoWeight(), aa_original.getMonoWeight() + 160.130654) AASequence test5 = AASequence::fromString("PEPTX[160.230654]IDE"); TEST_REAL_SIMILAR(test5.getMonoWeight(), aa_original.getMonoWeight() + 160.230654) } // test arbitrary differences (e.g. it should be possible to encode arbitrary masses and still get the correct weight) { AASequence test1 = AASequence::fromString("PEPTN[160.030654]IDE"); TEST_REAL_SIMILAR(test1.getMonoWeight(), aa_original.getMonoWeight() + 160.030654) AASequence test2 = AASequence::fromString("PEPTN[160.040654]IDE"); TEST_REAL_SIMILAR(test2.getMonoWeight(), aa_original.getMonoWeight() + 160.040654) AASequence test3 = AASequence::fromString("PEPTN[160.050654]IDE"); TEST_REAL_SIMILAR(test3.getMonoWeight(), aa_original.getMonoWeight() + 160.050654) AASequence test4 = AASequence::fromString("PEPTN[160.130654]IDE"); TEST_REAL_SIMILAR(test4.getMonoWeight(), aa_original.getMonoWeight() + 160.130654) AASequence test5 = AASequence::fromString("PEPTN[160.230654]IDE"); TEST_REAL_SIMILAR(test5.getMonoWeight(), aa_original.getMonoWeight() + 160.230654) } // test arbitrary differences (e.g. it should be possible to encode arbitrary masses and still get the correct weight) { AASequence test1 = AASequence::fromString("PEPT[+160.030654]IDE"); TEST_REAL_SIMILAR(test1.getMonoWeight(), aa_original.getMonoWeight() + 160.030654) TEST_REAL_SIMILAR(test1[0].getMonoWeight(), 115.0633292871) TEST_EQUAL(test1[3].isModified(), true) TEST_REAL_SIMILAR(test1[3].getMonoWeight(), 160.030654 + 119.0582442871) // the weight at this position is the mod + residue itself AASequence test2 = AASequence::fromString("PEPT[+160.040654]IDE"); TEST_REAL_SIMILAR(test2.getMonoWeight(), aa_original.getMonoWeight() + 160.040654) AASequence test3 = AASequence::fromString("PEPT[+160.050654]IDE"); TEST_REAL_SIMILAR(test3.getMonoWeight(), aa_original.getMonoWeight() + 160.050654) AASequence test4 = AASequence::fromString("PEPT[+160.130654]IDE"); TEST_REAL_SIMILAR(test4.getMonoWeight(), aa_original.getMonoWeight() + 160.130654) AASequence test5 = AASequence::fromString("PEPT[+160.230654]IDE"); TEST_REAL_SIMILAR(test5.getMonoWeight(), aa_original.getMonoWeight() + 160.230654) } // test arbitrary differences when writing them out AASequence test6 = AASequence::fromString("PEPTX[1600.230654]IDE"); TEST_EQUAL(test6.size(), 8) TEST_EQUAL(test6.toString(), "PEPTX[1600.230654]IDE") TEST_STRING_SIMILAR(test6.toUniModString(), "PEPTX[1600.230654]IDE") TEST_EQUAL(test6.toBracketString(), "PEPTX[1600]IDE") TEST_STRING_SIMILAR(test6.toBracketString(false), "PEPTX[1600.230654]IDE") TEST_EQUAL(test6.toUnmodifiedString(), "PEPTXIDE") TEST_EQUAL(test6[4].isModified(), true) TEST_REAL_SIMILAR(test6[4].getModification()->getMonoMass(), 1600.230654 + 18.0105650638) // because of the H2O loss TEST_REAL_SIMILAR(test6[4].getMonoWeight(), 1600.230654 + 18.0105650638) // computed as full (not internal) -> H2O loss TEST_REAL_SIMILAR(test6[4].getMonoWeight(Residue::Internal), 1600.230654) // this is the actual computed mass of the AA in the peptide bond: as expected 1600.23 TEST_REAL_SIMILAR(test6.getMonoWeight(), aa_original.getMonoWeight() + 1600.230654) // most importantly, the total mass is correct AASequence test7 = AASequence::fromString(test6.toString()); TEST_EQUAL(test7.size(), 8) TEST_EQUAL(test7.toString(), "PEPTX[1600.230654]IDE") TEST_STRING_SIMILAR(test7.toUniModString(), "PEPTX[1600.230654]IDE") TEST_EQUAL(test7.toBracketString(), "PEPTX[1600]IDE") TEST_STRING_SIMILAR(test7.toBracketString(false), "PEPTX[1600.230654]IDE") TEST_EQUAL(test7.toUnmodifiedString(), "PEPTXIDE") TEST_EQUAL(test6, test7) // the peptides should be equal // test arbitrary modification on N { AASequence aa_withn = AASequence::fromString("PEPTNIDE"); AASequence test_seq = AASequence::fromString("PEPTN[1600.230654]IDE"); TEST_EQUAL(test_seq.size(), 8) TEST_EQUAL(test_seq.toString(), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_seq.toUniModString(), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_seq.toBracketString(false, false), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_seq.toBracketString(false, true), "PEPTN[+1486.1877258086]IDE") TEST_EQUAL(test_seq.toUnmodifiedString(), "PEPTNIDE") TEST_REAL_SIMILAR(test_seq.getMonoWeight(), aa_original.getMonoWeight() + 1600.230654) TEST_REAL_SIMILAR(test_seq.getMonoWeight(), aa_withn.getMonoWeight() + 1486.1877258086) // test that we can re-read the string AASequence test_other = AASequence::fromString(test_seq.toString()); TEST_EQUAL(test_other.size(), 8) TEST_EQUAL(test_other.toString(), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_other.toUniModString(), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_other.toBracketString(false, false), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_other.toBracketString(false, true), "PEPTN[+1486.1877258086]IDE") TEST_EQUAL(test_other.toUnmodifiedString(), "PEPTNIDE") TEST_REAL_SIMILAR(test_other.getMonoWeight(), aa_original.getMonoWeight() + 1600.230654) TEST_REAL_SIMILAR(test_other.getMonoWeight(), aa_withn.getMonoWeight() + 1486.1877258086) TEST_EQUAL(test_other, test_seq) // the peptides should be equal // test that we can re-read the string from BracketString test_other = AASequence::fromString(test_seq.toBracketString(false)); TEST_EQUAL(test_other.size(), 8) TEST_STRING_SIMILAR(test_other.toString(), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_other.toUniModString(), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_other.toBracketString(false, false), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_other.toBracketString(false, true), "PEPTN[+1486.1877258086]IDE") TEST_EQUAL(test_other.toUnmodifiedString(), "PEPTNIDE") TEST_REAL_SIMILAR(test_other.getMonoWeight(), aa_original.getMonoWeight() + 1600.230654) TEST_REAL_SIMILAR(test_other.getMonoWeight(), aa_withn.getMonoWeight() + 1486.1877258086) TEST_EQUAL(test_other, test_seq) // the peptides should be equal // test that we can re-read the string from BracketString test_other = AASequence::fromString(test_seq.toBracketString(false, true)); TEST_EQUAL(test_other.size(), 8) // TEST_STRING_SIMILAR(test_other.toString(), "PEPTN[+1486.1877258086]IDE") TEST_STRING_SIMILAR(test_other.toUniModString(), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_other.toBracketString(false, false), "PEPTN[1600.230654]IDE") TEST_STRING_SIMILAR(test_other.toBracketString(false, true), "PEPTN[+1486.1877258086]IDE") TEST_EQUAL(test_other.toUnmodifiedString(), "PEPTNIDE") TEST_REAL_SIMILAR(test_other.getMonoWeight(), aa_original.getMonoWeight() + 1600.230654) TEST_REAL_SIMILAR(test_other.getMonoWeight(), aa_withn.getMonoWeight() + 1486.1877258086) // TEST_STRING_SIMILAR(test_other.toString(), test_seq.toString()) // the peptides should be equal } // test N-terminal modification { AASequence test_seq = AASequence::fromString(".[1601.2384790319]IDE"); TEST_EQUAL(test_seq.size(), 3) TEST_STRING_SIMILAR(test_seq.toString(), ".[1601.2384790319]IDE") TEST_STRING_SIMILAR(test_seq.toUniModString(), ".[1601.2384790319]IDE") TEST_STRING_SIMILAR(test_seq.toBracketString(false, false), "n[1601.2384790319]IDE") // an extra H for the N-terminus TEST_STRING_SIMILAR(test_seq.toBracketString(false, true), "n[+1600.230654]IDE") TEST_EQUAL(test_seq.toUnmodifiedString(), "IDE") TEST_REAL_SIMILAR(test_seq.getMonoWeight(), aa_half.getMonoWeight() + 1600.230654) // test that we can re-read the string AASequence test_other = AASequence::fromString(test_seq.toString()); TEST_EQUAL(test_other.size(), 3) TEST_STRING_SIMILAR(test_other.toString(), ".[1601.2384790319]IDE") TEST_EQUAL(test_seq, test_other) // the peptides should be equal // test that we can re-read the string from UniModString test_other = AASequence::fromString(test_seq.toUniModString()); TEST_EQUAL(test_other.size(), 3) TEST_STRING_SIMILAR(test_other.toString(), ".[1601.2384790319]IDE") TEST_STRING_SIMILAR(test_seq.toString(), test_other.toString()) // the peptides should be equal // test that we can re-read the string from BracketString test_other = AASequence::fromString(test_seq.toBracketString(false, true)); TEST_EQUAL(test_other.size(), 3) TEST_STRING_SIMILAR(test_other.toString(), ".[1600.230654]IDE") test_other = AASequence::fromString(test_seq.toBracketString(false, false)); TEST_EQUAL(test_other.size(), 3) // TEST_EQUAL(test_seq, test_other) // the peptides should be equal TEST_STRING_SIMILAR(test_seq.toString(), test_other.toString()) // the peptides should be equal // read from delta string { AASequence test_seq = AASequence::fromString("n[+1600.230654]IDE"); TEST_EQUAL(test_seq.size(), 3) TEST_STRING_SIMILAR(test_seq.toString(), ".[+1600.230654]IDE") TEST_STRING_SIMILAR(test_seq.toUniModString(), ".[1601.2384790319]IDE") TEST_STRING_SIMILAR(test_seq.toBracketString(false, false), "n[1601.2384790319]IDE") // an extra H for the N-terminus TEST_STRING_SIMILAR(test_seq.toBracketString(false, true), "n[+1600.230654]IDE") TEST_EQUAL(test_seq.toUnmodifiedString(), "IDE") TEST_REAL_SIMILAR(test_seq.getMonoWeight(), aa_half.getMonoWeight() + 1600.230654) } } // test C-terminal modification { const AASequence test_seq = AASequence::fromString("IDE.[1617.2333940319]"); TEST_EQUAL(test_seq.size(), 3) TEST_STRING_SIMILAR(test_seq.toString(), "IDE.[1617.2333940319]") TEST_STRING_SIMILAR(test_seq.toUniModString(), "IDE.[1617.2333940319]") TEST_STRING_SIMILAR(test_seq.toBracketString(false, false), "IDEc[1617.2333940319]") // an extra OH for C-terminus TEST_STRING_SIMILAR(test_seq.toBracketString(false, true), "IDEc[+1600.230654]") TEST_EQUAL(test_seq.toUnmodifiedString(), "IDE") TEST_REAL_SIMILAR(test_seq.getMonoWeight(), aa_half.getMonoWeight() + 1600.230654) // test that we can re-read the string AASequence test_other = AASequence::fromString(test_seq.toString()); TEST_EQUAL(test_other.size(), 3) TEST_EQUAL(test_other.toString(), "IDE.[1617.2333940319]") TEST_EQUAL(test_seq, test_other) // the peptides should be equal // test that we can re-read the UniModString test_other = AASequence::fromString(test_seq.toUniModString()); TEST_EQUAL(test_other.size(), 3) TEST_EQUAL(test_other.toString().hasPrefix("IDE.[1617.23339"), true) // TEST_STRING_SIMILAR is dangerous, because it skips over '+' etc TEST_STRING_SIMILAR(test_seq.toString(), test_other.toString()) // the peptides should be equal // test that we can re-read the string from BracketString auto bs = test_seq.toBracketString(false, true); test_other = AASequence::fromString(bs); TEST_EQUAL(test_other.size(), 3) TEST_EQUAL(test_other.toString().hasPrefix("IDE.[+1600.2306539"), true) // TEST_STRING_SIMILAR is dangerous, because it skips over '+' etc test_other = AASequence::fromString(test_seq.toBracketString(false, false)); TEST_EQUAL(test_other.size(), 3) // TEST_EQUAL(test_seq, test_other) // the peptides should be equal TEST_STRING_SIMILAR(test_seq.toString(), test_other.toString()) // the peptides should be equal // read from delta string { AASequence test_seq = AASequence::fromString("IDEc[+1600.230654]"); TEST_EQUAL(test_seq.size(), 3) TEST_STRING_SIMILAR(test_seq.toString(), "IDE.[+1600.230654]") TEST_STRING_SIMILAR(test_seq.toUniModString(), "IDE.[1617.2333940319]") TEST_STRING_SIMILAR(test_seq.toBracketString(false, false), "IDEc[1617.2333940319]") // an extra OH for C-terminus TEST_STRING_SIMILAR(test_seq.toBracketString(false, true), "IDEc[+1600.230654]") TEST_EQUAL(test_seq.toUnmodifiedString(), "IDE") TEST_REAL_SIMILAR(test_seq.getMonoWeight(), aa_half.getMonoWeight() + 1600.230654) } } // test from #2320 { AASequence aa_original = AASequence::fromString("DFPANGER"); TEST_REAL_SIMILAR(aa_original.getMonoWeight(), 904.4038997864) AASequence aa_withX_original = AASequence::fromString("DFPANGERX"); // TEST_REAL_SIMILAR(aa_withX_original.getMonoWeight(), 904.4038997864) // cannot call weight on AASequence with X AASequence test_seq = AASequence::fromString("DFPANGERX[113.0840643509]"); TEST_EQUAL(test_seq.size(), 9) TEST_EQUAL(test_seq.toString(), "DFPANGERX[113.0840643509]") TEST_STRING_SIMILAR(test_seq.toUniModString(), "DFPANGERX[113.0840643509]") TEST_STRING_EQUAL(test_seq.toBracketString(true, false), "DFPANGERX[113]") TEST_STRING_EQUAL(test_seq.toBracketString(true, true), "DFPANGERX[113]") // even when specifying delta masses, X cannot produce a delta mass TEST_STRING_SIMILAR(test_seq.toBracketString(false, false), "DFPANGERX[113.0840643509]") TEST_EQUAL(test_seq.toUnmodifiedString(), "DFPANGERX") TEST_EQUAL(test_seq.hasNTerminalModification(), false) TEST_EQUAL(test_seq.hasCTerminalModification(), false) TEST_REAL_SIMILAR(test_seq.getMonoWeight(), aa_original.getMonoWeight() + 113.0840643509) AASequence test_internal_seq = AASequence::fromString("DFPANGEX[113.0840643509]R"); TEST_REAL_SIMILAR(test_internal_seq.getMonoWeight(), aa_original.getMonoWeight() + 113.0840643509) TEST_EQUAL(test_seq[8].isModified(), true) TEST_REAL_SIMILAR(test_seq[8].getMonoWeight(), 113.0840643509 + 18.0105650638) // computed as full (not internal) -> H2O loss TEST_REAL_SIMILAR(test_seq[8].getMonoWeight(Residue::Internal), 113.0840643509) // test that we can re-read the string AASequence test_other = AASequence::fromString(test_seq.toString()); TEST_EQUAL(test_seq.size(), 9) TEST_EQUAL(test_seq.toString(), "DFPANGERX[113.0840643509]") TEST_EQUAL(test_seq, test_other) // the peptides should be equal } // Faulty / nonsense calculations ... AASequence test; TEST_EXCEPTION(Exception::ParseError, test = AASequence::fromString("PEPTX[+160.230654]IDE")); AASequence seq11 = AASequence::fromString("PEPM[147.035405]TIDEK"); TEST_EQUAL(seq11.isModified(), true); TEST_STRING_EQUAL(seq11[3].getModificationName(), "Oxidation"); } END_SECTION START_SECTION([EXTRA] Test integer vs float tags) { /// Test absolute masses // Test a few modifications with the "correct" accurate mass { AASequence seq11 = AASequence::fromString("PEPM[147.035405]TIDEK"); // UniMod oxMet is 147.035405 TEST_EQUAL(seq11.isModified(), true); TEST_STRING_EQUAL(seq11[3].getModificationName(), "Oxidation"); TEST_EQUAL(seq11[3].getModification()->getUniModRecordId(), 35) TEST_EQUAL(seq11[3].getModification()->getUniModAccession(), "UniMod:35") AASequence seq12 = AASequence::fromString("PEPT[181.014]TIDEK"); TEST_EQUAL(seq12.isModified(), true); TEST_STRING_EQUAL(seq12[3].getModificationName(), "Phospho"); TEST_EQUAL(seq12[3].getModification()->getUniModRecordId(), 21) TEST_EQUAL(seq12[3].getModification()->getUniModAccession(), "UniMod:21") AASequence seq13 = AASequence::fromString("PEPY[243.03]TIDEK"); TEST_EQUAL(seq13.isModified(), true); TEST_STRING_EQUAL(seq13[3].getModificationName(), "Phospho"); TEST_EQUAL(seq13[3].getModification()->getUniModRecordId(), 21) TEST_EQUAL(seq13[3].getModification()->getUniModAccession(), "UniMod:21") AASequence seq15 = AASequence::fromString("PEPC[160.0306]TIDE"); TEST_EQUAL(seq15.isModified(), true); TEST_STRING_EQUAL(seq15[3].getModificationName(), "Carbamidomethyl"); TEST_EQUAL(seq15[3].getModification()->getUniModRecordId(), 4) TEST_EQUAL(seq15[3].getModification()->getUniModAccession(), "UniMod:4") } // Test a few modifications with the accurate mass slightly off to match some other modification { AASequence seq11 = AASequence::fromString("PEPM[147.01]TIDEK"); TEST_EQUAL(seq11.isModified(), true); TEST_STRING_EQUAL(seq11[3].getModificationName(), "Oxidation") TEST_EQUAL(seq11[3].getModification()->getUniModRecordId(), 35) AASequence seq12 = AASequence::fromString("PEPT[181.004]TIDEK"); TEST_EQUAL(seq12.isModified(), true); TEST_STRING_EQUAL(seq12[3].getModificationName(), "Sulfo"); TEST_EQUAL(seq12[3].getModification()->getUniModRecordId(), 40) AASequence seq13 = AASequence::fromString("PEPY[243.02]TIDEK"); TEST_EQUAL(seq13.isModified(), true); TEST_STRING_EQUAL(seq13[3].getModificationName(), "Sulfo"); TEST_EQUAL(seq13[3].getModification()->getUniModRecordId(), 40) AASequence seq14 = AASequence::fromString("PEPTC[159.035405]IDE"); TEST_EQUAL(seq14.isModified(), true); TEST_STRING_EQUAL(seq14[4].getModificationName(), "Delta:H(4)C(3)O(1)"); TEST_EQUAL(seq14[4].getModification()->getUniModRecordId(), 206) } /// Test delta masses // Test a few modifications with the "correct" accurate mass { AASequence seq11 = AASequence::fromString("PEPM[+15.994915]TIDEK"); // UniMod oxMet is 15.994915 TEST_EQUAL(seq11.isModified(), true); TEST_STRING_EQUAL(seq11[3].getModificationName(), "Oxidation"); AASequence seq12 = AASequence::fromString("PEPT[+79.96632]TIDEK"); TEST_EQUAL(seq12.isModified(), true); TEST_STRING_EQUAL(seq12[3].getModificationName(), "Phospho"); AASequence seq13 = AASequence::fromString("PEPY[+79.966331]TIDEK"); TEST_EQUAL(seq13.isModified(), true); TEST_STRING_EQUAL(seq13[3].getModificationName(), "Phospho"); AASequence seq14 = AASequence::fromString("PEPC[+57.02]TIDE"); TEST_EQUAL(seq14.isModified(), true); TEST_STRING_EQUAL(seq14[3].getModificationName(), "Carbamidomethyl"); } // Test a few modifications with the accurate mass slightly off to match some other modification { // this does not work any more since there is no difference in the oxygen atom // AASequence seq11("PEPM[+15.994909]TIDEK"); // PSI-MOD oxMet is 15.994909 // TEST_EQUAL(seq11.isModified(),true); // TEST_STRING_EQUAL(seq11[3].getModification(), "MOD:00719") AASequence seq12 = AASequence::fromString("PEPT[+79.957]TIDEK"); TEST_EQUAL(seq12.isModified(), true); TEST_STRING_EQUAL(seq12[3].getModificationName(), "Sulfo") AASequence seqUnk = AASequence::fromString("PEPTTIDEK[+79957.0]"); TEST_EQUAL(seqUnk.isModified(), true); TEST_STRING_EQUAL(seqUnk[8].getModificationName(), ""); //this is how "user-defined" mods are defined TEST_EQUAL(seqUnk[8].getModification()->isUserDefined(), true); TEST_STRING_EQUAL(seqUnk[8].getModification()->getFullName(), "[+79957.0]"); TEST_STRING_EQUAL(seqUnk[8].getModification()->getFullId(), "K[+79957.0]"); AASequence seq13 = AASequence::fromString("PEPY[+79.9568]TIDEK"); TEST_EQUAL(seq13.isModified(), true); TEST_STRING_EQUAL(seq13[3].getModificationName(), "Sulfo") AASequence seq14 = AASequence::fromString("PEPTC[+56.026215]IDE"); TEST_EQUAL(seq14.isModified(), true); TEST_STRING_EQUAL(seq14[4].getModificationName(), "Delta:H(4)C(3)O(1)"); } } END_SECTION START_SECTION([EXTRA] Peptide equivalence) { // Test float mass tag leading to internal Acetylation TEST_EQUAL(AASequence::fromString("PEPTC(Acetyl)IDE"), AASequence::fromString("PEPTC[+42.011]IDE")) // Test mass tag leading to a "Dimethyl:2H(4)13C(2)" at the N-term (pepXML format) TEST_EQUAL(AASequence::fromString("(Dimethyl:2H(4)13C(2))TGSESSQTGTSTTSSR"), AASequence::fromString("n[+34]TGSESSQTGTSTTSSR")) // Test absolute mass (34 + 1H) leading to a "Dimethyl:2H(4)13C(2)" at the N-term (pepXML format) TEST_EQUAL(AASequence::fromString("(Dimethyl:2H(4)13C(2))TGSESSQTGTSTTSSR"), AASequence::fromString("n[35]TGSESSQTGTSTTSSR")) // Test absolute integer mass at the N-term, internal residue and C-terminus (mixing pepXML bracket format and OpenMS round brackets) TEST_EQUAL(AASequence::fromString("n(Acetyl)PEPC(Carbamidomethyl)PEPM(Oxidation)PEPRc(Amidated)"), AASequence::fromString("n[43]PEPC(Carbamidomethyl)PEPM[147]PEPRc[16]")); // Test float mass tag leading to N-terminal Acetylation TEST_EQUAL(AASequence::fromString("(Acetyl)PEPTCIDE"), AASequence::fromString("[+42.011]PEPTCIDE")) // Test integer mass tag leading to N-terminal Acetylation TEST_EQUAL(AASequence::fromString("(Acetyl)PEPTCIDE"), AASequence::fromString("[+42]PEPTCIDE")) // Test Carbamidomethyl TEST_EQUAL(AASequence::fromString("PEPTC(UniMod:4)IDE"), AASequence::fromString("PEPTC(Carbamidomethyl)IDE")) TEST_EQUAL(AASequence::fromString("PEPTC(UniMod:4)IDE"), AASequence::fromString("PEPTC(Iodoacetamide derivative)IDE")) TEST_EQUAL(AASequence::fromString("PEPTC(UniMod:4)IDE"), AASequence::fromString("PEPTC[160.030654]IDE")) // 103.00919 + 57.02 TEST_EQUAL(AASequence::fromString("PEPTC(UniMod:4)IDE"), AASequence::fromString("PEPTC[+57.02]IDE")) TEST_EQUAL(AASequence::fromString("PEPTC(UniMod:4)IDE"), AASequence::fromString("PEPTC[160]IDE")) // 103.00919 + 57.02 TEST_EQUAL(AASequence::fromString("PEPTC(UniMod:4)IDE"), AASequence::fromString("PEPTC[+57]IDE")) // Test Oxidation TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString("DFPIAM[+16]GER")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString("DFPIAM[147]GER")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString("DFPIAM[+15.99]GER")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString("DFPIAM[147.035405]GER")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString("DFPIAM(Oxidation)GER")) // Test Oxidation TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString(".DFPIAM[+16]GER")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString(".DFPIAM[147]GER")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString(".DFPIAM[+15.99]GER")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString(".DFPIAM[147.035405]GER")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString(".DFPIAM(Oxidation)GER")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString(".DFPIAM[+16]GER.")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString(".DFPIAM[147]GER.")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString(".DFPIAM[+15.99]GER.")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString(".DFPIAM[147.035405]GER.")) TEST_EQUAL(AASequence::fromString("DFPIAM(UniMod:35)GER"), AASequence::fromString(".DFPIAM(Oxidation)GER.")) // Test Phosphorylation TEST_EQUAL(AASequence::fromString("PEPT(UniMod:21)TIDEK"), AASequence::fromString("PEPT(Phospho)TIDEK")) TEST_EQUAL(AASequence::fromString("PEPT(UniMod:21)TIDEK"), AASequence::fromString("PEPT[181]TIDEK")) TEST_EQUAL(AASequence::fromString("PEPT(UniMod:21)TIDEK"), AASequence::fromString("PEPT[+80]TIDEK")) TEST_EQUAL(AASequence::fromString("PEPY(UniMod:21)TIDEK"), AASequence::fromString("PEPY(Phospho)TIDEK")) TEST_EQUAL(AASequence::fromString("PEPY(UniMod:21)TIDEK"), AASequence::fromString("PEPY[243]TIDEK")) TEST_EQUAL(AASequence::fromString("PEPY(UniMod:21)TIDEK"), AASequence::fromString("PEPY[+80]TIDEK")) TEST_EQUAL(AASequence::fromString("PEPS(UniMod:21)TIDEK"), AASequence::fromString("PEPS(Phospho)TIDEK")) TEST_EQUAL(AASequence::fromString("PEPS(UniMod:21)TIDEK"), AASequence::fromString("PEPS[167]TIDEK")) TEST_EQUAL(AASequence::fromString("PEPS(UniMod:21)TIDEK"), AASequence::fromString("PEPS[+80]TIDEK")) // Test N-terminal modification TEST_EQUAL(AASequence::fromString("C[143]PEPTIDEK"), AASequence::fromString("(UniMod:26)CPEPTIDEK")) TEST_EQUAL(AASequence::fromString("C[+40]PEPTIDEK"), AASequence::fromString("(UniMod:26)CPEPTIDEK")) TEST_EQUAL(AASequence::fromString("Q[111]PEPTIDEK"), AASequence::fromString("(UniMod:28)QPEPTIDEK")) TEST_EQUAL(AASequence::fromString("Q[-17]PEPTIDEK"), AASequence::fromString("(UniMod:28)QPEPTIDEK")) TEST_EQUAL(AASequence::fromString("Q[-17.0265]PEPTIDEK"), AASequence::fromString("(UniMod:28)QPEPTIDEK")) TEST_EQUAL(AASequence::fromString("C[+39.994915]PEPTIDEK"), AASequence::fromString("(UniMod:26)CPEPTIDEK")) // Test C-terminal modification TEST_EQUAL(AASequence::fromString("PEPTIDEM[-29.992806]"), AASequence::fromString("PEPTIDEM(UniMod:610)")); TEST_EQUAL(AASequence::fromString("PEPTIDEM[-30]"), AASequence::fromString("PEPTIDEM(UniMod:610)")); TEST_EQUAL(AASequence::fromString("PEPTIDEM[101]"), AASequence::fromString("PEPTIDEM(UniMod:610)")); // // TEST_EQUAL(AASequence::fromString("[143]CPEPTIDEK"), AASequence::fromString("(UniMod:26)CPEPTIDEK")) // TEST_EQUAL(AASequence::fromString("n[143]CPEPTIDEK"), AASequence::fromString("(UniMod:26)CPEPTIDEK")) // Test loss TEST_EQUAL(AASequence::fromString("PEPTIDEM(UniMod:10)"), AASequence::fromString("PEPTIDEM(Met->Hse)")) TEST_EQUAL(AASequence::fromString("PEPTM(Met->Thr)IDE"), AASequence::fromString("PEPTM[-30]IDE")) TEST_EQUAL(AASequence::fromString("PEPTM(Met->Thr)IDE"), AASequence::fromString("PEPTM[101]IDE")) } END_SECTION START_SECTION([EXTRA] Tag in peptides) { String I_weight = String(ResidueDB::getInstance()->getResidue("I")->getMonoWeight(Residue::Internal)); AASequence aa1 = AASequence::fromString("DFPIANGER"); AASequence aa2 = AASequence::fromString("DPFX[" + I_weight + "]ANGER"); AASequence aa3 = AASequence::fromString("X[" + I_weight + "]DFPANGER"); AASequence aa4 = AASequence::fromString("DFPANGERX[" + I_weight + "]"); TEST_REAL_SIMILAR(aa1.getMonoWeight(), 1017.487958568) TEST_EQUAL(aa2.isModified(), true) TEST_EQUAL(aa3.hasNTerminalModification(), false) TEST_EQUAL(aa4.hasCTerminalModification(), false) TEST_REAL_SIMILAR(aa2.getMonoWeight(), 1017.487958568) TEST_REAL_SIMILAR(aa3.getMonoWeight(), 1017.487958568) TEST_REAL_SIMILAR(aa4.getMonoWeight(), 1017.487958568) } END_SECTION START_SECTION([EXTRA] testing terminal modifications) { AASequence aaNoMod = AASequence::fromString(".DFPIANGER."); AASequence aaNtermMod = AASequence::fromString(".(Dimethyl)DFPIANGER"); AASequence aaCtermMod = AASequence::fromString("DFPIANGER.(Label:18O(2))"); TEST_EQUAL(aaNoMod.isModified(), false) TEST_EQUAL(aaNtermMod.isModified(), true) TEST_EQUAL(aaCtermMod.isModified(), true) TEST_EQUAL(aaNoMod.getNTerminalModificationName(), "") TEST_EQUAL(aaNtermMod.getNTerminalModificationName(), "Dimethyl") TEST_EQUAL(aaCtermMod.getNTerminalModificationName(), "") TEST_EQUAL(aaNoMod.getCTerminalModificationName(), "") TEST_EQUAL(aaNtermMod.getCTerminalModificationName(), "") TEST_EQUAL(aaCtermMod.getCTerminalModificationName(), "Label:18O(2)") // Carbamylation vector<String> fixed_mods; TEST_STRING_EQUAL(aaNoMod.toBracketString(true, false, fixed_mods), "DFPIANGER"); TEST_STRING_EQUAL(aaNoMod.toBracketString(false, false, fixed_mods), "DFPIANGER"); TEST_STRING_EQUAL(aaNtermMod.toBracketString(true, false, fixed_mods), "n[29]DFPIANGER"); TEST_STRING_SIMILAR(aaNtermMod.toBracketString(false, false, fixed_mods), "n[29.0391250319]DFPIANGER"); TEST_STRING_EQUAL(aaCtermMod.toBracketString(true, false, fixed_mods), "DFPIANGERc[21]"); TEST_STRING_SIMILAR(aaCtermMod.toBracketString(false, false, fixed_mods), "DFPIANGERc[21.0112310319]"); TEST_STRING_EQUAL(aaNoMod.toUniModString(), "DFPIANGER"); TEST_STRING_EQUAL(aaNtermMod.toUniModString(), ".(UniMod:36)DFPIANGER"); TEST_STRING_EQUAL(aaCtermMod.toUniModString(), "DFPIANGER.(UniMod:193)"); // Test equivalence TEST_EQUAL(AASequence::fromString(".(UniMod:36)DFPIANGER"), AASequence::fromString(".(UniMod:36)DFPIANGER.")) TEST_EQUAL(AASequence::fromString(".(UniMod:36)DFPIANGER"), AASequence::fromString(".(Dimethyl)DFPIANGER.")) TEST_EQUAL(AASequence::fromString(".(UniMod:36)DFPIANGER"), AASequence::fromString("n[29]DFPIANGER")) TEST_EQUAL(AASequence::fromString(".(UniMod:36)DFPIANGER"), AASequence::fromString("n[29.0391250319]DFPIANGER")) TEST_EQUAL(AASequence::fromString(".(UniMod:36)DFPIANGER"), AASequence::fromString(".[29]DFPIANGER.")) TEST_EQUAL(AASequence::fromString(".(UniMod:36)DFPIANGER"), AASequence::fromString(".[29.0391250319]DFPIANGER.")) TEST_EQUAL(AASequence::fromString("DFPIANGER.(UniMod:193)"), AASequence::fromString(".DFPIANGER.(UniMod:193)")) TEST_EQUAL(AASequence::fromString("DFPIANGER.(UniMod:193)"), AASequence::fromString(".DFPIANGER.(Label:18O(2))")) TEST_EQUAL(AASequence::fromString("DFPIANGER.(UniMod:193)"), AASequence::fromString(".DFPIANGERc[21]")) TEST_EQUAL(AASequence::fromString("DFPIANGER.(UniMod:193)"), AASequence::fromString(".DFPIANGERc[21.0112310319]")) TEST_EQUAL(AASequence::fromString("DFPIANGER.(UniMod:193)"), AASequence::fromString(".DFPIANGER.[21]")) TEST_EQUAL(AASequence::fromString("DFPIANGER.(UniMod:193)"), AASequence::fromString(".DFPIANGER.[21.0112310319]")) // Test "forbidden combinations" on the N/C terminal end // UniMod 10 can only occur on C-terminal peptide on an M TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString("DFPIANGER.(UniMod:10)")) // not just any C-term is allowed TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString("DFPIANGEM(UniMod:10)R.")) // not just any M is allowed TEST_EQUAL( AASequence::fromString(".DFPIANGEM.(UniMod:10)"), AASequence::fromString(".DFPIANGEM.(UniMod:10)") ) TEST_EQUAL( AASequence::fromString(".DFPIANGEM(UniMod:10)"), AASequence::fromString(".DFPIANGEM.(UniMod:10)") ) TEST_EQUAL( AASequence::fromString(".DFPIANGEM.c[-30]"), AASequence::fromString(".DFPIANGEM.(UniMod:10)") ) TEST_EQUAL( AASequence::fromString(".DFPIANGEM.c[-29.99]"), AASequence::fromString(".DFPIANGEM.(UniMod:10)") ) // TO FIX: this is an ambiguous case, toBracketString produces the "absolute" // mass of the n terminal "AA" but its mass is negative, therefore when // parsing it would be interpreted as a delta mass and its off by one! TEST_EQUAL( AASequence::fromString(".DFPIANGEM(UniMod:10)").toBracketString(true), "DFPIANGEMc[-13]") // absolute TEST_STRING_SIMILAR( AASequence::fromString(".DFPIANGEM(UniMod:10)").toBracketString(false), "DFPIANGEMc[-12.9900659681]") // absolute TEST_EQUAL( AASequence::fromString(".DFPIANGEM(UniMod:10)").toBracketString(true, true), "DFPIANGEMc[-30]") // relative // UniMod 385 can only occur on N-terminal peptide on an C TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString("(UniMod:385).DFPIANGER.")) // not just any N-term is allowed TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString("(UniMod:385)DFPIANGER.")) // not just any N-term is allowed TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString(".DC(UniMod:385)CFPIANGER.")) // not just any C is allowed TEST_EQUAL(AASequence::fromString(".DN(UniMod:385)CFPIANGER."), AASequence::fromString(".DN(UniMod:385)CFPIANGER.")) // any N is allowed TEST_EQUAL(AASequence::fromString("(UniMod:385).CFPIANGER."), AASequence::fromString("(UniMod:385).CFPIANGER.")) TEST_EQUAL(AASequence::fromString("(UniMod:385)CFPIANGER."), AASequence::fromString("(UniMod:385).CFPIANGER.")) TEST_EQUAL(AASequence::fromString("n[-17].CFPIANGER."), AASequence::fromString("(UniMod:385).CFPIANGER.")) TEST_EQUAL(AASequence::fromString("n[-17.026].CFPIANGER."), AASequence::fromString("(UniMod:385).CFPIANGER.")) // TO FIX: this is an ambiguous case, toBracketString produces the "absolute" // mass of the n terminal "AA" but its mass is negative, therefore when // parsing it would be interpreted as a delta mass and its off by one! TEST_EQUAL(AASequence::fromString("(UniMod:385)CFPIANGER.").toBracketString(true), "n[-16]CFPIANGER") // absolute TEST_EQUAL(AASequence::fromString("(UniMod:385)CFPIANGER.").toBracketString(true, true), "n[-17]CFPIANGER") // relative // UniMod 26 can only occur on N-terminal peptide on an C TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString("(UniMod:26).DFPIANGER.")) // not just any N-term is allowed TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString("(UniMod:26)DFPIANGER.")) // not just any N-term is allowed TEST_EXCEPTION(Exception::InvalidValue, AASequence::fromString(".DC(UniMod:1419)CFPIANGER.")) // not just any C is allowed TEST_EQUAL(AASequence::fromString("(UniMod:26).CFPIANGER."), AASequence::fromString("(UniMod:26).CFPIANGER.")) TEST_EQUAL(AASequence::fromString("(UniMod:26)CFPIANGER."), AASequence::fromString("(UniMod:26).CFPIANGER.")) // This case is non-ambiguous since we have absolute mass (41.0027400319) and relative mass (+39.994915) TEST_EQUAL(AASequence::fromString("n[41].CFPIANGER."), AASequence::fromString("(UniMod:26).CFPIANGER.")) TEST_EQUAL(AASequence::fromString("n[41.0027400319].CFPIANGER."), AASequence::fromString("(UniMod:26).CFPIANGER.")) TEST_EQUAL(AASequence::fromString("n[+39.994915].CFPIANGER."), AASequence::fromString("(UniMod:26).CFPIANGER.")) TEST_EQUAL(AASequence::fromString("(UniMod:1009)CFPIANGER.").toBracketString(true), "n[13]CFPIANGER") // absolute TEST_EQUAL(AASequence::fromString("(UniMod:1009)CFPIANGER.").toBracketString(true, true), "n[+12]CFPIANGER") // relative // The example given in the documentation AASequence test = AASequence::fromString(".[43]PEPC(UniMod:4)PEPM[147]PEPR.[16]"); TEST_EQUAL(test.toString(), ".(Acetyl)PEPC(Carbamidomethyl)PEPM(Oxidation)PEPR.(Amidated)") TEST_EQUAL(test.toUniModString(), ".(UniMod:1)PEPC(UniMod:4)PEPM(UniMod:35)PEPR.(UniMod:2)") TEST_EQUAL(test.toBracketString(), "n[43]PEPC[160]PEPM[147]PEPRc[16]") TEST_STRING_SIMILAR(test.toBracketString(false, false), "n[43.0183900319]PEPC[160.0306489852]PEPM[147.0354000171]PEPRc[16.0187240319]") TEST_EQUAL(test.toBracketString(true, false), "n[43]PEPC[160]PEPM[147]PEPRc[16]") TEST_STRING_SIMILAR(test.toBracketString(false, true), "n[+42.010565]PEPC[+57.021464]PEPM[+15.994915]PEPRc[-0.984016]") TEST_EQUAL(test.toBracketString(true, true), "n[+42]PEPC[+57]PEPM[+16]PEPRc[-1]") AASequence aa_original = AASequence::fromString("DFPANGER"); TEST_REAL_SIMILAR(aa_original.getMonoWeight(), 904.4038997864) AASequence test_seq = AASequence::fromString("DFPANGERX[113.0840643509]"); TEST_EQUAL(test_seq.size(), 9) TEST_STRING_SIMILAR(test_seq.toString(), "DFPANGERX[113.0840643509]") TEST_STRING_SIMILAR(test_seq.toUniModString(), "DFPANGERX[113.0840643509]") TEST_EQUAL(test_seq.toBracketString(true, false), "DFPANGERX[113]") TEST_EQUAL(test_seq.toBracketString(true, true), "DFPANGERX[113]") // difference of 18 (H2O) TEST_STRING_SIMILAR(test_seq.toBracketString(false, false), "DFPANGERX[113.0840643509]") TEST_EQUAL(test_seq.toUnmodifiedString(), "DFPANGERX") TEST_EQUAL(test_seq.hasNTerminalModification(), false) TEST_EQUAL(test_seq.hasCTerminalModification(), false) TEST_REAL_SIMILAR(test_seq.getMonoWeight(), aa_original.getMonoWeight() + 113.0840643509) } END_SECTION START_SECTION([EXTRA] testing uniqueness of modifications) { // Ensuring that we are not mixing and matching modifications { auto tmp1 = AASequence::fromString("PEPTN[1300.230654]IDE"); auto tmp2 = AASequence::fromString("PEPTX[1300.230654]IDE"); AASequence tmp3 = AASequence::fromString("PEPTN[+1318.2412190638]IDE"); AASequence tmp4 = AASequence::fromString("PEPTN[+1186.1877258086]IDE"); // TEST_REAL_SIMILAR(tmp3.getMonoWeight(), tmp4.getMonoWeight() ) // this *needs* to fail!!! TEST_REAL_SIMILAR( fabs(tmp3.getMonoWeight() - tmp4.getMonoWeight()), 132.0534932552 ) // this *needs* to be different! TEST_REAL_SIMILAR( fabs(tmp3.getMonoWeight() - tmp1.getMonoWeight()), 132.0534932552 ) // this *needs* to be different! } } END_SECTION START_SECTION([EXTRA] testing new type of modification with brackets in their name) { AASequence tmp1 = AASequence::fromString("PEPTK(Xlink:DSS[156])IDE"); AASequence tmp2 = AASequence::fromString("PEPTK(Xlink:DSS[155])IDE"); TEST_EQUAL(tmp1[4].getModification()->getDiffMonoMass(), 156.078644) TEST_EQUAL(tmp1.toString(), "PEPTK(Xlink:DSS[156])IDE") TEST_EQUAL(tmp2[4].getModification()->getDiffMonoMass(), 155.094629) TEST_EQUAL(tmp2.toString(), "PEPTK(Xlink:DSS[155])IDE") } END_SECTION START_SECTION([EXTRA] multithreaded example) { OPENMS_LOG_WARN.remove(std::cout); // All measurements are best of three (wall time, Linux, 8 threads) // // Serial execution of code: // 5e4 iterations -> 5.42 seconds // // Parallel execution of code: // original code: // 5e4 iterations -> 4.01 seconds with boost::shared_mutex // 5e4 iterations -> 8.05 seconds with std::mutex // // refactored code that throws exception outside block: // 5e4 iterations -> 8.55 seconds with omp critical // 5e4 iterations -> 8.59 seconds with std::mutex // 5e4 iterations -> 3.94 seconds with boost::shared_mutex int nr_iterations(1000); int test = 0; #pragma omp parallel for reduction (+: test) for (int k = 1; k < nr_iterations + 1; k++) { auto aa = AASequence::fromString("TEST[" + String(0.14*k) + "]PEPTIDE"); test += aa.size(); } TEST_EQUAL(test, nr_iterations*11) } END_SECTION START_SECTION(([EXTRA] std::hash<AASequence>)) { // Test that equal sequences have equal hashes AASequence seq1 = AASequence::fromString("PEPTIDE"); AASequence seq2 = AASequence::fromString("PEPTIDE"); std::hash<AASequence> hasher; TEST_EQUAL(hasher(seq1), hasher(seq2)) // Test that different sequences have different hashes AASequence seq3 = AASequence::fromString("PEPTIDER"); TEST_NOT_EQUAL(hasher(seq1), hasher(seq3)) // Test sequences with modifications AASequence seq4 = AASequence::fromString("PEPTM(Oxidation)IDE"); AASequence seq5 = AASequence::fromString("PEPTM(Oxidation)IDE"); AASequence seq6 = AASequence::fromString("PEPTMIDE"); // Same sequence, no modification TEST_EQUAL(hasher(seq4), hasher(seq5)) TEST_NOT_EQUAL(hasher(seq4), hasher(seq6)) // Modification matters // Test terminal modifications AASequence seq7 = AASequence::fromString(".(Acetyl)PEPTIDE"); AASequence seq8 = AASequence::fromString(".(Acetyl)PEPTIDE"); AASequence seq9 = AASequence::fromString("PEPTIDE"); // No N-term mod TEST_EQUAL(hasher(seq7), hasher(seq8)) TEST_NOT_EQUAL(hasher(seq7), hasher(seq9)) // N-term mod matters AASequence seq10 = AASequence::fromString("PEPTIDE.(Amidated)"); AASequence seq11 = AASequence::fromString("PEPTIDE"); // No C-term mod TEST_NOT_EQUAL(hasher(seq10), hasher(seq11)) // C-term mod matters // Test empty sequence AASequence seq_empty1; AASequence seq_empty2; TEST_EQUAL(hasher(seq_empty1), hasher(seq_empty2)) // Test that sequences work in unordered_set std::unordered_set<AASequence> 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 TEST_EQUAL(seq_set.size(), 3) TEST_EQUAL(seq_set.count(seq1), 1) TEST_EQUAL(seq_set.count(AASequence::fromString("PEPTIDE")), 1) TEST_EQUAL(seq_set.count(seq3), 1) TEST_EQUAL(seq_set.count(seq4), 1) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DataAccessHelper_test.cpp
.cpp
1,068
45
// 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/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(DataAccessHelper, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// DataAccessHelper* ptr = 0; DataAccessHelper* null_ptr = 0; START_SECTION(DataAccessHelper()) { ptr = new DataAccessHelper(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~DataAccessHelper()) { delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MQMsmsExporter_test.cpp
.cpp
3,095
85
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow$ // $Authors: Hendrik Beschorner, Lenny Kovac, Virginia Rossow$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/QC/MQMsmsExporter.h> #include <OpenMS/SYSTEM/File.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/test_config.h> /////////////////////////// /////////////////////////// START_TEST(MQMsms, "$ID$") using namespace OpenMS; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// File::TempDir dir; const String path = dir.getPath(); START_SECTION(MQMsms()) { MQMsms *ptr = nullptr; MQMsms *null_ptr = nullptr; ptr = new MQMsms(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<OpenMS::String,OpenMS::String>& prot_map = {}))) { { MQMsms msms(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); msms.exportFeatureMap(fmap_one, cmap_two, exp); FeatureMap fmap_two; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_2.featureXML"), fmap_two); msms.exportFeatureMap(fmap_two, cmap_two, exp); FeatureMap fmap_three; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_3.featureXML"), fmap_three); msms.exportFeatureMap(fmap_three, cmap_two, exp); FeatureMap fmap_four; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_4.featureXML"), fmap_four); msms.exportFeatureMap(fmap_four, cmap_one, exp); FeatureMap fmap_five; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_5.featureXML"), fmap_five); msms.exportFeatureMap(fmap_five, cmap_one, exp); FeatureMap fmap_six; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_6.featureXML"), fmap_six); msms.exportFeatureMap(fmap_six, cmap_one, exp); } String filename = path + "/msms.txt"; TEST_FILE_SIMILAR(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("MQMsms_result.txt")); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Ribonucleotide_test.cpp
.cpp
7,810
228
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Samuel Wein $ // $Authors: Samuel Wein $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CHEMISTRY/Ribonucleotide.h> #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(Ribonucleotide, "$Id$") ///////////////////////////////////////////////////////////// Ribonucleotide* e_ptr = nullptr; Ribonucleotide* e_nullPointer = nullptr; START_SECTION((Ribonucleotide())) e_ptr = new Ribonucleotide(); TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION((virtual ~Ribonucleotide())) delete e_ptr; END_SECTION Ribonucleotide test_ribo("test", "T"); START_SECTION(Ribonucleotide(const Ribonucleotide& ribonucleotide)) Ribonucleotide copy(test_ribo); TEST_EQUAL(copy, test_ribo) END_SECTION START_SECTION(Ribonucleotide& operator=(const Ribonucleotide& ribonucleotide)) Ribonucleotide copy; copy = test_ribo; TEST_EQUAL(copy, test_ribo); END_SECTION START_SECTION(bool operator==(const Ribonucleotide& ribonucleotide) const) TEST_EQUAL(Ribonucleotide(), Ribonucleotide("unknown ribonucleotide", ".", "", ".", EmpiricalFormula(), '.', 0.0, 0.0, Ribonucleotide::ANYWHERE, EmpiricalFormula("C5H10O5"))); END_SECTION START_SECTION(String getName() const) Ribonucleotide empty = Ribonucleotide(); TEST_EQUAL(empty.getName(), "unknown ribonucleotide"); END_SECTION START_SECTION(String getCode() const) Ribonucleotide empty = Ribonucleotide(); TEST_EQUAL(empty.getCode(), "."); END_SECTION START_SECTION(String getNewCode() const) Ribonucleotide empty = Ribonucleotide(); TEST_EQUAL(empty.getNewCode(), ""); END_SECTION START_SECTION(String getHTMLCode() const) Ribonucleotide empty = Ribonucleotide(); TEST_EQUAL(empty.getHTMLCode(), "."); END_SECTION START_SECTION(EmpiricalFormula getFormula() const) Ribonucleotide empty = Ribonucleotide(); TEST_EQUAL(empty.getFormula(), EmpiricalFormula()); END_SECTION START_SECTION(char getOrigin() const) Ribonucleotide empty = Ribonucleotide(); TEST_EQUAL(empty.getOrigin(), '.'); END_SECTION START_SECTION(double getMonoMass() const) Ribonucleotide empty = Ribonucleotide(); TEST_EQUAL(empty.getMonoMass(), 0.0); END_SECTION START_SECTION(double getAvgMass() const) Ribonucleotide empty = Ribonucleotide(); TEST_EQUAL(empty.getAvgMass(), 0.0); END_SECTION START_SECTION(Ribonucleotide::TermSpecificity getTermSpecificity() const) Ribonucleotide empty = Ribonucleotide(); TEST_EQUAL(empty.getTermSpecificity(), Ribonucleotide::ANYWHERE); END_SECTION START_SECTION(EmpiricalFormula getBaselossFormula() const) Ribonucleotide empty = Ribonucleotide(); TEST_EQUAL(empty.getBaselossFormula(), EmpiricalFormula("C5H10O5")); END_SECTION START_SECTION(setName(string name)) Ribonucleotide empty = Ribonucleotide(); empty.setName("foo"); TEST_EQUAL(empty.getName(), "foo"); END_SECTION START_SECTION(setCode(string code)) Ribonucleotide empty = Ribonucleotide(); empty.setCode("x"); TEST_EQUAL(empty.getCode(), "x"); END_SECTION START_SECTION(setNewCode(String newCode)) Ribonucleotide empty = Ribonucleotide(); empty.setNewCode("y"); TEST_EQUAL(empty.getNewCode(), "y"); END_SECTION START_SECTION(setHTMLCode(String hmtlCode)) Ribonucleotide empty = Ribonucleotide(); empty.setHTMLCode("z"); TEST_EQUAL(empty.getHTMLCode(), "z"); END_SECTION START_SECTION(setFormula(EmpiricalFormula formula)) Ribonucleotide empty = Ribonucleotide(); empty.setFormula(EmpiricalFormula("H2O")); TEST_EQUAL(empty.getFormula(), EmpiricalFormula("H2O")); END_SECTION START_SECTION(setOrigin(char origin)) Ribonucleotide empty = Ribonucleotide(); empty.setOrigin('q'); TEST_EQUAL(empty.getOrigin(), 'q'); END_SECTION START_SECTION(setMonoMass(double mono_mass)) Ribonucleotide empty = Ribonucleotide(); empty.setMonoMass(2.0); TEST_EQUAL(empty.getMonoMass(), 2.0); END_SECTION START_SECTION(setAvgMass(double avg_mass)) Ribonucleotide empty = Ribonucleotide(); empty.setAvgMass(3.0); TEST_EQUAL(empty.getAvgMass(), 3.0); END_SECTION START_SECTION(setTermSpecificity(Ribonucleotide::TermSpecificity specificity)) Ribonucleotide empty = Ribonucleotide(); empty.setTermSpecificity(Ribonucleotide::FIVE_PRIME); TEST_EQUAL(empty.getTermSpecificity(), Ribonucleotide::FIVE_PRIME); END_SECTION START_SECTION(void setBaselossFormula(EmpiricalFormula formula)) Ribonucleotide empty = Ribonucleotide(); empty.setBaselossFormula(EmpiricalFormula("CO2")); TEST_EQUAL(empty.getBaselossFormula(), EmpiricalFormula("CO2")); END_SECTION START_SECTION(bool isModified() const) TEST_EQUAL(test_ribo.isModified(), true); test_ribo.setOrigin('T'); TEST_EQUAL(test_ribo.isModified(), false); test_ribo.setCode("Tm"); TEST_EQUAL(test_ribo.isModified(), true); END_SECTION START_SECTION(([EXTRA] std::hash<Ribonucleotide>)) { // Test that equal objects have equal hashes Ribonucleotide ribo1("adenosine", "A", "A", "A", EmpiricalFormula("C10H13N5O4"), 'A', 267.0968, 267.24, Ribonucleotide::ANYWHERE, EmpiricalFormula("C5H10O5")); Ribonucleotide ribo2("adenosine", "A", "A", "A", EmpiricalFormula("C10H13N5O4"), 'A', 267.0968, 267.24, Ribonucleotide::ANYWHERE, EmpiricalFormula("C5H10O5")); TEST_EQUAL(ribo1 == ribo2, true) TEST_EQUAL(std::hash<Ribonucleotide>{}(ribo1), std::hash<Ribonucleotide>{}(ribo2)) // Test that different objects (likely) have different hashes Ribonucleotide ribo3("guanosine", "G", "G", "G", EmpiricalFormula("C10H13N5O5"), 'G', 283.0917, 283.24, Ribonucleotide::ANYWHERE, EmpiricalFormula("C5H10O5")); TEST_NOT_EQUAL(ribo1 == ribo3, true) // Note: Different objects may have same hash (collision), but this is unlikely for well-designed hashes TEST_NOT_EQUAL(std::hash<Ribonucleotide>{}(ribo1), std::hash<Ribonucleotide>{}(ribo3)) // Test that copies have equal hashes Ribonucleotide ribo_copy(ribo1); TEST_EQUAL(std::hash<Ribonucleotide>{}(ribo1), std::hash<Ribonucleotide>{}(ribo_copy)) // Test use in unordered_set std::unordered_set<Ribonucleotide> ribo_set; ribo_set.insert(ribo1); ribo_set.insert(ribo2); // Should not increase size (duplicate) ribo_set.insert(ribo3); TEST_EQUAL(ribo_set.size(), 2) TEST_EQUAL(ribo_set.count(ribo1), 1) TEST_EQUAL(ribo_set.count(ribo3), 1) // Test use in unordered_map std::unordered_map<Ribonucleotide, std::string> ribo_map; ribo_map[ribo1] = "first"; ribo_map[ribo3] = "third"; TEST_EQUAL(ribo_map.size(), 2) TEST_EQUAL(ribo_map[ribo1], "first") TEST_EQUAL(ribo_map[ribo3], "third") ribo_map[ribo2] = "second"; // Should overwrite ribo1's value TEST_EQUAL(ribo_map.size(), 2) TEST_EQUAL(ribo_map[ribo1], "second") // Test default-constructed ribonucleotide hash consistency Ribonucleotide default1; Ribonucleotide default2; TEST_EQUAL(std::hash<Ribonucleotide>{}(default1), std::hash<Ribonucleotide>{}(default2)) // Test that different term specificities produce different hashes Ribonucleotide five_prime("adenosine", "A", "A", "A", EmpiricalFormula("C10H13N5O4"), 'A', 267.0968, 267.24, Ribonucleotide::FIVE_PRIME, EmpiricalFormula("C5H10O5")); Ribonucleotide three_prime("adenosine", "A", "A", "A", EmpiricalFormula("C10H13N5O4"), 'A', 267.0968, 267.24, Ribonucleotide::THREE_PRIME, EmpiricalFormula("C5H10O5")); TEST_NOT_EQUAL(std::hash<Ribonucleotide>{}(five_prime), std::hash<Ribonucleotide>{}(three_prime)) } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BaseFeature_test.cpp
.cpp
12,878
437
// 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, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/KERNEL/BaseFeature.h> /////////////////////////// #include <OpenMS/METADATA/PeptideIdentification.h> START_TEST(BaseFeature, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; typedef BaseFeature::QualityType QualityType; typedef BaseFeature::WidthType WidthType; BaseFeature* feat_ptr = nullptr; BaseFeature* feat_nullPointer = nullptr; START_SECTION((BaseFeature())) { feat_ptr = new BaseFeature; TEST_NOT_EQUAL(feat_ptr, feat_nullPointer); } END_SECTION START_SECTION((~BaseFeature())) { delete feat_ptr; } END_SECTION START_SECTION((QualityType getQuality() const)) BaseFeature p; TEST_REAL_SIMILAR(p.getQuality(), 0.0) // continued in "setQuality" test END_SECTION START_SECTION((void setQuality(QualityType q))) BaseFeature p; p.setQuality((QualityType) 123.456); TEST_REAL_SIMILAR(p.getQuality(), 123.456) p.setQuality((QualityType)-0.12345); TEST_REAL_SIMILAR(p.getQuality(), -0.12345) p.setQuality((QualityType)0.0); TEST_REAL_SIMILAR(p.getQuality(), 0.0) END_SECTION START_SECTION((WidthType getWidth() const)) BaseFeature p; TEST_REAL_SIMILAR(p.getWidth(), 0.0) // continued in "setWidth" test END_SECTION START_SECTION((void setWidth(WidthType fwhm))) BaseFeature p; p.setWidth((WidthType) 123.456); TEST_REAL_SIMILAR(p.getWidth(), (WidthType) 123.456) p.setWidth((WidthType) -0.12345); TEST_REAL_SIMILAR(p.getWidth(), (WidthType) -0.12345) p.setWidth((WidthType) 0.0); TEST_REAL_SIMILAR(p.getWidth(), (WidthType) 0.0) END_SECTION START_SECTION([EXTRA](IntensityType getIntensity() const)) const BaseFeature p; TEST_REAL_SIMILAR(p.getIntensity(), 0.0) END_SECTION START_SECTION([EXTRA](const PositionType& getPosition() const)) const BaseFeature p; TEST_REAL_SIMILAR(p.getPosition()[0], 0.0) TEST_REAL_SIMILAR(p.getPosition()[1], 0.0) END_SECTION START_SECTION([EXTRA](IntensityType& getIntensity())) BaseFeature p; TEST_REAL_SIMILAR(p.getIntensity(), 0.0f) p.setIntensity(123.456f); TEST_REAL_SIMILAR(p.getIntensity(), 123.456f) p.setIntensity(-0.12345f); TEST_REAL_SIMILAR(p.getIntensity(), -0.12345f) p.setIntensity(0.0f); TEST_REAL_SIMILAR(p.getIntensity(), 0.0f) END_SECTION START_SECTION([EXTRA](PositionType& getPosition())) BaseFeature::PositionType pos; BaseFeature p; pos = p.getPosition(); TEST_REAL_SIMILAR(pos[0], 0.0) TEST_REAL_SIMILAR(pos[1], 0.0) pos[0] = 1.0; pos[1] = 2.0; p.setPosition(pos); BaseFeature::PositionType pos2(p.getPosition()); TEST_REAL_SIMILAR(pos2[0], 1.0) TEST_REAL_SIMILAR(pos2[1], 2.0) END_SECTION START_SECTION((const ChargeType& getCharge() const)) { BaseFeature const tmp; TEST_EQUAL(tmp.getCharge(),0); // continued in "setCharge" test } END_SECTION START_SECTION((void setCharge(const ChargeType &ch))) { BaseFeature tmp; TEST_EQUAL(tmp.getCharge(),0); tmp.setCharge(17); TEST_EQUAL(tmp.getCharge(),17); } END_SECTION START_SECTION((BaseFeature(const BaseFeature &feature))) { BaseFeature::PositionType pos; pos[0] = 21.21; pos[1] = 22.22; BaseFeature p; p.setIntensity(123.456f); p.setPosition(pos); p.setMetaValue("cluster_id", 4711); p.setQuality((QualityType)0.9); BaseFeature copy_of_p(p); BaseFeature::PositionType pos2 = copy_of_p.getPosition(); BaseFeature::IntensityType i2 = copy_of_p.getIntensity(); BaseFeature::QualityType q2 = copy_of_p.getQuality(); TEST_REAL_SIMILAR(i2, 123.456) TEST_REAL_SIMILAR(pos2[0], 21.21) TEST_REAL_SIMILAR(pos2[1], 22.22) TEST_EQUAL(copy_of_p.getMetaValue("cluster_id"), DataValue(4711)); TEST_REAL_SIMILAR(q2, 0.9) } END_SECTION START_SECTION((BaseFeature(BaseFeature &&feature))) { // Ensure that BaseFeature has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(BaseFeature(std::declval<BaseFeature&&>())), true) BaseFeature::PositionType pos; pos[0] = 21.21; pos[1] = 22.22; BaseFeature p; p.setIntensity(123.456f); p.setPosition(pos); p.setMetaValue("cluster_id",4711); p.setQuality((QualityType)0.9); BaseFeature orig = p; BaseFeature copy_of_p(std::move(p)); BaseFeature::PositionType pos2 = copy_of_p.getPosition(); BaseFeature::IntensityType i2 = copy_of_p.getIntensity(); BaseFeature::QualityType q2 = copy_of_p.getQuality(); TEST_REAL_SIMILAR(i2, 123.456) TEST_REAL_SIMILAR(pos2[0], 21.21) TEST_REAL_SIMILAR(pos2[1], 22.22) TEST_EQUAL(copy_of_p.getMetaValue("cluster_id"), DataValue(4711)); TEST_REAL_SIMILAR(q2, 0.9) } END_SECTION START_SECTION((BaseFeature(const Peak2D& point))) { Peak2D point; point.setRT(1.23); point.setMZ(4.56); point.setIntensity(OpenMS::Peak2D::IntensityType(7.89)); BaseFeature copy(point); TEST_REAL_SIMILAR(copy.getRT(), 1.23); TEST_REAL_SIMILAR(copy.getMZ(), 4.56); TEST_REAL_SIMILAR(copy.getIntensity(), 7.89); TEST_EQUAL(copy.getQuality(), 0.0); TEST_EQUAL(copy.getCharge(), 0); TEST_EQUAL(copy.getWidth(), 0.0); TEST_EQUAL(copy.getPeptideIdentifications().empty(), true); } END_SECTION START_SECTION((BaseFeature(const RichPeak2D& point))) { RichPeak2D point; point.setRT(1.23); point.setMZ(4.56); point.setIntensity(OpenMS::Peak2D::IntensityType(7.89)); point.setMetaValue("meta", "test"); BaseFeature copy(point); TEST_REAL_SIMILAR(copy.getRT(), 1.23); TEST_REAL_SIMILAR(copy.getMZ(), 4.56); TEST_REAL_SIMILAR(copy.getIntensity(), 7.89); TEST_EQUAL(copy.getMetaValue("meta"), "test"); TEST_EQUAL(copy.getQuality(), 0.0); TEST_EQUAL(copy.getCharge(), 0); TEST_EQUAL(copy.getWidth(), 0.0); TEST_EQUAL(copy.getPeptideIdentifications().empty(), true); } END_SECTION START_SECTION((BaseFeature& operator=(const BaseFeature& rhs))) BaseFeature::PositionType pos; pos[0] = 21.21; pos[1] = 22.22; BaseFeature p; p.setIntensity(123.456f); p.setPosition(pos); p.setQuality((QualityType)0.9); BaseFeature copy_of_p; copy_of_p = p; BaseFeature::PositionType pos2 = copy_of_p.getPosition(); BaseFeature::IntensityType i2 = copy_of_p.getIntensity(); BaseFeature::QualityType q2 = copy_of_p.getQuality(); TEST_REAL_SIMILAR(i2, 123.456) TEST_REAL_SIMILAR(pos2[0], 21.21) TEST_REAL_SIMILAR(pos2[1], 22.22) TEST_REAL_SIMILAR(q2, 0.9) END_SECTION START_SECTION((bool operator==(const BaseFeature &rhs) const)) { BaseFeature p1; BaseFeature p2(p1); TEST_TRUE(p1 == p2) p1.setIntensity(5.0f); p1.setQuality((QualityType)0.9); TEST_EQUAL(p1 == p2, false) p2.setIntensity(5.0f); p2.setQuality((QualityType)0.9); TEST_TRUE(p1 == p2) p1.getPosition()[0] = 5; TEST_EQUAL(p1 == p2, false) p2.getPosition()[0] = 5; TEST_TRUE(p1 == p2) PeptideIdentificationList peptides(1); p1.setPeptideIdentifications(peptides); TEST_EQUAL(p1 == p2, false); p2.setPeptideIdentifications(peptides); TEST_TRUE(p1 == p2); } END_SECTION START_SECTION((bool operator!=(const BaseFeature& rhs) const)) BaseFeature p1; BaseFeature 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) PeptideIdentificationList peptides(1); p1.setPeptideIdentifications(peptides); TEST_FALSE(p1 == p2); p2.setPeptideIdentifications(peptides); TEST_EQUAL(p1 != p2, false); END_SECTION START_SECTION(([EXTRA]meta info with copy constructor)) BaseFeature p; p.setMetaValue(2,String("bla")); BaseFeature p2(p); TEST_EQUAL(p.getMetaValue(2), "bla") TEST_EQUAL(p2.getMetaValue(2), "bla") p.setMetaValue(2,String("bluff")); TEST_EQUAL(p.getMetaValue(2), "bluff") TEST_EQUAL(p2.getMetaValue(2), "bla") END_SECTION START_SECTION(([EXTRA]meta info with assignment)) BaseFeature p; p.setMetaValue(2,String("bla")); BaseFeature p2 = p; TEST_EQUAL(p.getMetaValue(2), "bla") TEST_EQUAL(p2.getMetaValue(2), "bla") p.setMetaValue(2,String("bluff")); TEST_EQUAL(p.getMetaValue(2), "bluff") TEST_EQUAL(p2.getMetaValue(2), "bla") END_SECTION START_SECTION(([BaseFeature::QualityLess] bool operator()(const BaseFeature &left, const BaseFeature &right) const )) BaseFeature f1, f2; f1.setQuality((QualityType)0.94); f2.setQuality((QualityType)0.78); BaseFeature::QualityLess oql; TEST_EQUAL(oql(f1, f2), 0); TEST_EQUAL(oql(f2, f1), 1); END_SECTION START_SECTION(([BaseFeature::QualityLess] bool operator()(const BaseFeature &left, const QualityType &right) const )) BaseFeature f1, f2; f1.setQuality((QualityType)0.94); f2.setQuality((QualityType)0.78); BaseFeature::QualityType rhs = f1.getQuality(); BaseFeature::QualityLess oql; TEST_EQUAL(oql(f1, rhs), 0); TEST_EQUAL(oql(f2, rhs), 1); END_SECTION START_SECTION(([BaseFeature::QualityLess] bool operator()(const QualityType& left, const BaseFeature& right) const)) BaseFeature f1, f2; f1.setQuality((QualityType)0.94); f2.setQuality((QualityType)0.78); BaseFeature::QualityType lhs = f2.getQuality(); BaseFeature::QualityLess oql; TEST_EQUAL(oql(lhs,f2), 0); TEST_EQUAL(oql(lhs,f1), 1); END_SECTION START_SECTION(([BaseFeature::QualityLess] bool operator()(const QualityType& left, const QualityType& right) const )) BaseFeature f1, f2; f1.setQuality((QualityType)0.94); f2.setQuality((QualityType)0.78); BaseFeature::QualityType lhs = f1.getQuality(); BaseFeature::QualityType rhs = f2.getQuality(); BaseFeature::QualityLess oql; TEST_EQUAL(oql(lhs,rhs), 0); TEST_EQUAL(oql(rhs,lhs), 1); END_SECTION START_SECTION((const PeptideIdentificationList& getPeptideIdentifications() const)) BaseFeature tmp; PeptideIdentificationList vec(tmp.getPeptideIdentifications()); TEST_EQUAL(vec.size(), 0); END_SECTION START_SECTION((void setPeptideIdentifications(const PeptideIdentificationList& peptides))) BaseFeature tmp; PeptideIdentificationList vec; tmp.setPeptideIdentifications(vec); TEST_EQUAL(tmp.getPeptideIdentifications().size(), 0); PeptideIdentification dbs; vec.push_back(dbs); tmp.setPeptideIdentifications(vec); TEST_EQUAL(tmp.getPeptideIdentifications().size(), 1); END_SECTION START_SECTION((PeptideIdentificationList& getPeptideIdentifications())) BaseFeature tmp; tmp.getPeptideIdentifications().resize(1); TEST_EQUAL(tmp.getPeptideIdentifications().size(), 1); END_SECTION START_SECTION((AnnotationState getAnnotationState() const)) BaseFeature tmp; PeptideIdentificationList vec; PeptideIdentificationList& ids = tmp.getPeptideIdentifications(); TEST_EQUAL(tmp.getAnnotationState(), BaseFeature::AnnotationState::FEATURE_ID_NONE); ids.resize(1); TEST_EQUAL(tmp.getAnnotationState(), BaseFeature::AnnotationState::FEATURE_ID_NONE); PeptideHit hit; hit.setSequence(AASequence::fromString("ABCDE")); ids[0].setHits(std::vector<PeptideHit>(1, hit)); TEST_EQUAL(tmp.getAnnotationState(), BaseFeature::AnnotationState::FEATURE_ID_SINGLE); ids.resize(2); ids[1].setHits(std::vector<PeptideHit>(1, hit)); // same as first hit //tmp.setPeptideIdentifications(ids); TEST_EQUAL(tmp.getAnnotationState(), BaseFeature::AnnotationState::FEATURE_ID_MULTIPLE_SAME); hit.setSequence(AASequence::fromString("KRGH")); ids[1].setHits(std::vector<PeptideHit>(1, hit)); // different to first hit TEST_EQUAL(tmp.getAnnotationState(), BaseFeature::AnnotationState::FEATURE_ID_MULTIPLE_DIVERGENT); END_SECTION START_SECTION((sortPeptideIdentifications())) BaseFeature tmp; PeptideIdentificationList vec; PeptideIdentificationList& ids = tmp.getPeptideIdentifications(); ids.resize(3); PeptideHit hit; hit.setSequence(AASequence::fromString("ABCDE")); hit.setScore(0.8); ids[0].setHits(std::vector<PeptideHit>(1, hit)); hit.setScore(0.5); ids[1].getHits().push_back(hit); // same as first hi hit.setSequence(AASequence::fromString("KRGH")); hit.setScore(0.9); ids[1].getHits().push_back(hit); // different to first hit //ids[2] is empty. tmp.sortPeptideIdentifications(); TEST_EQUAL(ids[0].getHits()[0].getScore(), 0.9); TEST_EQUAL(ids[2].empty(), true); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/HDF5_test.cpp
.cpp
4,504
140
// 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/CONCEPT/Types.h> using namespace std; // Example from https://support.hdfgroup.org/HDF5/doc/cpplus_RM/create_8cpp-example.html /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the COPYING file, which can be found at the root of the source code * * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. * * If you do not have access to either file, you may request a copy from * * help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <string> #include "H5Cpp.h" using namespace H5; const H5std_string FILE_NAME( "SDS.h5" ); const H5std_string DATASET_NAME( "IntArray" ); const int NX = 5; // dataset dimensions const int NY = 6; const int RANK = 2; START_TEST(HDF5, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; START_SECTION((HDF5())) /* * Data initialization. */ int i, j; int data[NX][NY]; // buffer for data to write for (j = 0; j < NX; j++) { for (i = 0; i < NY; i++) data[j][i] = i + j; } /* * 0 1 2 3 4 5 * 1 2 3 4 5 6 * 2 3 4 5 6 7 * 3 4 5 6 7 8 * 4 5 6 7 8 9 */ // Try block to detect exceptions raised by any of the calls inside it // try { /* * Turn off the auto-printing when failure occurs so that we can * handle the errors appropriately */ H5::Exception::dontPrint(); /* * Create a new file using H5F_ACC_TRUNC access, * default file creation properties, and default file * access properties. */ H5File file( FILE_NAME, H5F_ACC_TRUNC ); /* * Define the size of the array and create the data space for fixed * size dataset. */ hsize_t dimsf[2]; // dataset dimensions dimsf[0] = NX; dimsf[1] = NY; DataSpace dataspace( RANK, dimsf ); /* * Define datatype for the data in the file. * We will store little endian INT numbers. */ IntType datatype( PredType::NATIVE_INT ); datatype.setOrder( H5T_ORDER_LE ); /* * Create a new dataset within the file using defined dataspace and * datatype and default dataset creation properties. */ DataSet dataset = file.createDataSet( DATASET_NAME, datatype, dataspace ); /* * Write the data to the dataset using default memory space, file * space, and transfer properties. */ dataset.write( data, PredType::NATIVE_INT ); } // end of try block // // catch failure caused by the H5File operations // catch( FileIException error ) // { // error.printError(); // return -1; // } // // catch failure caused by the DataSet operations // catch( DataSetIException error ) // { // error.printError(); // return -1; // } // // catch failure caused by the DataSpace operations // catch( DataSpaceIException error ) // { // error.printError(); // return -1; // } // // catch failure caused by the DataSpace operations // catch( DataTypeIException error ) // { // error.printError(); // return -1; // } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PSMExplainedIonCurrent_test.cpp
.cpp
15,686
389
// 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 <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/PSMExplainedIonCurrent.h> #include <cmath> #include <random> ////////////////////////// using namespace OpenMS; // Functions to create input data std::mt19937 gen(0); void addRandomPeaks(MSSpectrum& spec, double total_intensity = 1.0, Int number_of_peaks = 1) { double peak_intensity = total_intensity / number_of_peaks; spec.sortByPosition(); std::uniform_real_distribution<> distr((*spec.begin()).getMZ(), (*(spec.end() - 1)).getMZ()); for (Int i = 0; i < number_of_peaks; ++i) { spec.emplace_back(distr(gen), peak_intensity); } } // create a MSSpectrum with Precursor, MSLevel and RT without Peaks 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 MSSpectrum with Precursor, MSLevel, RT and fill it with Peaks const MSSpectrum createMSSpectrum(UInt ms_level, double rt, const String& id, const AASequence& seq, Int charge, const Param& theo_gen_params, Precursor::ActivationMethod precursor_method = Precursor::ActivationMethod::CID) { MSSpectrum ms_spec; ms_spec.setRT(rt); ms_spec.setMSLevel(ms_level); ms_spec.setNativeID(id); TheoreticalSpectrumGenerator t; if (!theo_gen_params.empty()) t.setParameters(theo_gen_params); t.getSpectrum(ms_spec, seq, 1, charge <= 2 ? 1 : 2); std::set<Precursor::ActivationMethod> am; am.insert(precursor_method); ms_spec.getPrecursors()[0].setActivationMethods(am); 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(PSMExplainedIonCurrent, "$Id$") AASequence::fromString("").empty(); // Generate test data // MSExperiment Param p; // create b- and y-ion spectrum of peptide sequence HIMALAYA with charge 1 PeakSpectrum ms_spec_2_himalaya = createMSSpectrum(2, 3.7, "XTandem::1", AASequence::fromString("HIMALAYA"), 1, p); addRandomPeaks(ms_spec_2_himalaya, 7.0); // add 7 to 13 -> correctness should be 13/20 // create c- and z-ion spectrum of peptide sequence ALABAMA with charge 2 TheoreticalSpectrumGenerator theo_gen_al; p = theo_gen_al.getParameters(); p.setValue("add_c_ions", "true"); p.setValue("add_zp1_ions", "true"); p.setValue("add_b_ions", "false"); p.setValue("add_y_ions", "false"); PeakSpectrum ms_spec_2_alabama = createMSSpectrum(2, 2, "XTandem::2", AASequence::fromString("ALABAMA"), 2, p, Precursor::ActivationMethod::ECD); addRandomPeaks(ms_spec_2_alabama, 5.0); // add 5 to 10 -> correctness should be 2/3 MSSpectrum empty_spec; MSExperiment exp; exp.setSpectra({empty_spec, ms_spec_2_alabama, ms_spec_2_himalaya}); // MSExperiment with no given fragmentation method (falls back to CID) MSExperiment exp_no_pc(exp); exp_no_pc[0].setPrecursors({}); // MSExperiment with MS1 Spectrum MSExperiment exp_ms1(exp); exp_ms1.setSpectra({createMSSpectrum(1, 5, "XTandem::3")}); // MSExperiment with Sori activation MSExperiment exp_sori(exp); exp_sori.setSpectra({createMSSpectrum(2, 7, "XTandem::5", Precursor::ActivationMethod::SORI)}); // MSExperiment with himalaya, spectrum with peaks with intensity 0 & empty spectrum MSExperiment failing_exp(exp); PeakSpectrum zero_peaks(createMSSpectrum(2, 4, "XTandem::6")); zero_peaks.emplace_back(10, 0); zero_peaks.emplace_back(20, 0); failing_exp.setSpectra({ms_spec_2_himalaya, zero_peaks, empty_spec}); // map the MSExperiment QCBase::SpectraMap spectra_map; // PeptideIdentifications PeptideIdentification empty_id; empty_id.setRT(6); PeptideIdentification himalaya = createPeptideIdentification("XTandem::1", "HIMALAYA", 1, 888); PeptideIdentification alabama = createPeptideIdentification("XTandem::2", "ALABAMA", 2, 264); PeptideIdentification no_hit_id(himalaya); no_hit_id.setHits({}); PeptideIdentificationList pep_ids({himalaya, alabama, empty_id}); // ProteinIdentifications ProteinIdentification protId; ProteinIdentification::SearchParameters param; param.fragment_mass_tolerance_ppm = false; param.fragment_mass_tolerance = 0.3; protId.setSearchParameters(param); // FeatureMap FeatureMap fmap; Feature empty_feat; fmap.setUnassignedPeptideIdentifications(pep_ids); fmap.push_back(empty_feat); fmap.setProteinIdentifications({protId}); PSMExplainedIonCurrent* ptr = nullptr; PSMExplainedIonCurrent* nulpt = nullptr; START_SECTION(PSMExplainedIonCurrent()) { ptr = new PSMExplainedIonCurrent(); TEST_NOT_EQUAL(ptr, nulpt) } END_SECTION START_SECTION(~PSMExplainedIonCurrent()) { delete ptr; } END_SECTION PSMExplainedIonCurrent psm_corr; START_SECTION(void compute(FeatureMap& fmap, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum, ToleranceUnit tolerance_unit = ToleranceUnit::AUTO, double tolerance = 20)) { spectra_map.calculateMap(exp); //-------------------------------------------------------------------- // test with valid input - default parameter //-------------------------------------------------------------------- psm_corr.compute(fmap, exp, spectra_map); std::vector<PSMExplainedIonCurrent::Statistics> result = psm_corr.getResults(); TEST_REAL_SIMILAR(result[0].average_correctness, (13. / 20 + 10. / 15) / 2.) TEST_REAL_SIMILAR(result[0].variance_correctness, 0.000138) //-------------------------------------------------------------------- // test with valid input - ToleranceUnit PPM //-------------------------------------------------------------------- PSMExplainedIonCurrent psm_corr_ppm; psm_corr_ppm.compute(fmap, exp, spectra_map, QCBase::ToleranceUnit::PPM, 6); std::vector<PSMExplainedIonCurrent::Statistics> result_ppm = psm_corr_ppm.getResults(); TEST_REAL_SIMILAR(result_ppm[0].average_correctness, (13. / 20 + 10. / 15) / 2.) TEST_REAL_SIMILAR(result_ppm[0].variance_correctness, 0.000138) //-------------------------------------------------------------------- // test with valid input and flags //-------------------------------------------------------------------- PSMExplainedIonCurrent psm_corr_flag_da; psm_corr_flag_da.compute(fmap, exp, spectra_map, QCBase::ToleranceUnit::DA, 1); std::vector<PSMExplainedIonCurrent::Statistics> result_flag_da = psm_corr_flag_da.getResults(); TEST_REAL_SIMILAR(result_flag_da[0].average_correctness, (13. / 20 + 10. / 15) / 2.) TEST_REAL_SIMILAR(result_flag_da[0].variance_correctness, 0.000138) //-------------------------------------------------------------------- // test with missing toleranceUnit and toleranceValue in featureMap //-------------------------------------------------------------------- // featureMap with missing ProteinIdentifications { FeatureMap fmap_auto = fmap; fmap_auto.getProteinIdentifications().clear(); TEST_EXCEPTION(Exception::MissingInformation, psm_corr.compute(fmap_auto, exp, spectra_map, QCBase::ToleranceUnit::AUTO)) } //-------------------------------------------------------------------- // test with no given fragmentation method //-------------------------------------------------------------------- spectra_map.calculateMap(exp_no_pc); psm_corr.compute(fmap, exp_no_pc, spectra_map); TEST_REAL_SIMILAR(psm_corr.getResults()[1].average_correctness, (13. / 20 + 10. / 15) / 2.) TEST_REAL_SIMILAR(psm_corr.getResults()[1].variance_correctness, 0.000138) //-------------------------------------------------------------------- // test with matching ms1 spectrum //-------------------------------------------------------------------- { spectra_map.calculateMap(exp_ms1); // fmap with PeptideIdentification with spec_ref matching to a MS1 Spectrum FeatureMap fmap_ms1(fmap); fmap_ms1.setUnassignedPeptideIdentifications({createPeptideIdentification("XTandem::3")}); TEST_EXCEPTION(Exception::IllegalArgument, psm_corr.compute(fmap_ms1, exp_ms1, spectra_map)) } //-------------------------------------------------------------------- // test with fragmentation method SORI, which is not supported //-------------------------------------------------------------------- { // put PeptideIdentification with spec_ref matching to MSSpectrum with fragmentation method SORI to fmap FeatureMap fmap_sori; fmap_sori.setProteinIdentifications({protId}); fmap_sori.setUnassignedPeptideIdentifications({createPeptideIdentification("XTandem::5")}); spectra_map.calculateMap(exp_sori); TEST_EXCEPTION(Exception::InvalidParameter, psm_corr.compute(fmap_sori, exp_sori, spectra_map)) } //-------------------------------------------------------------------- // Only failing inputs //-------------------------------------------------------------------- { // put PeptideIdentification without hits & with spec_ref matching to spectrum with no peaks, empty spectrum to fmap FeatureMap failing_fmap; failing_fmap.setProteinIdentifications({protId}); failing_fmap.setUnassignedPeptideIdentifications({no_hit_id, createPeptideIdentification("XTandem::6")}); spectra_map.calculateMap(failing_exp); PSMExplainedIonCurrent psm_corr_failing; TEST_EXCEPTION(Exception::MissingInformation, psm_corr_failing.compute(failing_fmap, failing_exp, spectra_map)) } } END_SECTION START_SECTION(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)) { spectra_map.calculateMap(exp); //-------------------------------------------------------------------- // test with valid input - default parameter //-------------------------------------------------------------------- psm_corr.compute(pep_ids, param, exp, spectra_map); std::vector<PSMExplainedIonCurrent::Statistics> result = psm_corr.getResults(); TEST_REAL_SIMILAR(result[0].average_correctness, (13. / 20 + 10. / 15) / 2.) TEST_REAL_SIMILAR(result[0].variance_correctness, 0.000138) //-------------------------------------------------------------------- // test with valid input - ToleranceUnit PPM //-------------------------------------------------------------------- PSMExplainedIonCurrent psm_corr_ppm; psm_corr_ppm.compute(pep_ids, param, exp, spectra_map, QCBase::ToleranceUnit::PPM, 6); std::vector<PSMExplainedIonCurrent::Statistics> result_ppm = psm_corr_ppm.getResults(); TEST_REAL_SIMILAR(result_ppm[0].average_correctness, (13. / 20 + 10. / 15) / 2.) TEST_REAL_SIMILAR(result_ppm[0].variance_correctness, 0.000138) //-------------------------------------------------------------------- // test with valid input and flags //-------------------------------------------------------------------- PSMExplainedIonCurrent psm_corr_flag_da; psm_corr_flag_da.compute(pep_ids, param, exp, spectra_map, QCBase::ToleranceUnit::DA, 1); std::vector<PSMExplainedIonCurrent::Statistics> result_flag_da = psm_corr_flag_da.getResults(); TEST_REAL_SIMILAR(result_flag_da[0].average_correctness, (13. / 20 + 10. / 15) / 2.) TEST_REAL_SIMILAR(result_flag_da[0].variance_correctness, 0.000138) //-------------------------------------------------------------------- // test with missing toleranceUnit and toleranceValue from params //-------------------------------------------------------------------- // featureMap with missing ProteinIdentifications { ProteinIdentification::SearchParameters no_params; TEST_EXCEPTION(Exception::MissingInformation, psm_corr.compute(pep_ids, no_params, exp, spectra_map, QCBase::ToleranceUnit::AUTO)) } //-------------------------------------------------------------------- // test with no given fragmentation method //-------------------------------------------------------------------- spectra_map.calculateMap(exp_no_pc); psm_corr.compute(pep_ids, param, exp_no_pc, spectra_map); TEST_REAL_SIMILAR(psm_corr.getResults()[1].average_correctness, (13. / 20 + 10. / 15) / 2.) TEST_REAL_SIMILAR(psm_corr.getResults()[1].variance_correctness, 0.000138) //-------------------------------------------------------------------- // test with matching ms1 spectrum //-------------------------------------------------------------------- { spectra_map.calculateMap(exp_ms1); // PeptideIdentification with spec_ref matching to a MS1 Spectrum PeptideIdentificationList ms1_pep({createPeptideIdentification("XTandem::3")}); TEST_EXCEPTION(Exception::IllegalArgument, psm_corr.compute(ms1_pep, param, exp_ms1, spectra_map)) } //-------------------------------------------------------------------- // test with fragmentation method SORI, which is not supported //-------------------------------------------------------------------- { spectra_map.calculateMap(exp_sori); // PeptideIdentification with spec_ref matching to MSSpectrum with fragmentation method SORI PeptideIdentificationList sori_id({createPeptideIdentification("XTandem::5")}); TEST_EXCEPTION(Exception::InvalidParameter, psm_corr.compute(sori_id, param, exp_sori, spectra_map)) } //-------------------------------------------------------------------- // Only failing inputs //-------------------------------------------------------------------- { // put PeptideIdentification with spec_ref matching to MSSpectrum with no peaks to fmap PeptideIdentificationList failing_ids({no_hit_id, createPeptideIdentification("XTandem::6")}); spectra_map.calculateMap(failing_exp); PSMExplainedIonCurrent psm_corr_failing; TEST_EXCEPTION(Exception::MissingInformation, psm_corr_failing.compute(failing_ids, param, failing_exp, spectra_map)) } } END_SECTION START_SECTION(const String& getName() const override) { TEST_EQUAL(psm_corr.getName(), "PSMExplainedIonCurrent"); } END_SECTION START_SECTION(const std::vector<Statistics>& getResults() const) { // tested in compute tests above NOT_TESTABLE; } END_SECTION START_SECTION(QCBase::Status requirements() const override) { QCBase::Status stat = QCBase::Status() | QCBase::Requires::RAWMZML | QCBase::Requires::POSTFDRFEAT; TEST_EQUAL(psm_corr.requirements() == stat, true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Normalizer_test.cpp
.cpp
3,446
134
// 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/SCALING/Normalizer.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/DTAFile.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(Normalizer, "$Id$") ///////////////////////////////////////////////////////////// Normalizer* e_ptr = nullptr; Normalizer* e_nullPointer = nullptr; START_SECTION((Normalizer())) e_ptr = new Normalizer; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION((~Normalizer())) delete e_ptr; END_SECTION e_ptr = new Normalizer(); START_SECTION((Normalizer(const Normalizer& source))) Normalizer copy(*e_ptr); TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) TEST_EQUAL(copy.getName(), e_ptr->getName()) END_SECTION START_SECTION((Normalizer& operator = (const Normalizer& source))) Normalizer copy; copy = *e_ptr; TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) TEST_EQUAL(copy.getName(), e_ptr->getName()) END_SECTION DTAFile dta_file; PeakSpectrum spec_ref; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec_ref); spec_ref.sortByIntensity(); START_SECTION((template<typename SpectrumType> void filterSpectrum(SpectrumType& spectrum) const)) PeakSpectrum spec = spec_ref; TEST_EQUAL(spec.rbegin()->getIntensity(), 46) e_ptr->filterSpectrum(spec); TEST_EQUAL(spec.rbegin()->getIntensity(), 1) Param p(e_ptr->getParameters()); p.setValue("method", "to_TIC"); e_ptr->setParameters(p); e_ptr->filterSpectrum(spec); double sum(0); for (PeakSpectrum::ConstIterator it = spec.begin(); it != spec.end(); ++it) { sum += it->getIntensity(); } TEST_REAL_SIMILAR(sum, 1.0); END_SECTION START_SECTION((void filterPeakMap(PeakMap& exp) const)) delete e_ptr; e_ptr = new Normalizer(); PeakSpectrum spec = spec_ref; PeakMap pm; pm.addSpectrum(spec); TEST_EQUAL(pm.begin()->rbegin()->getIntensity(), 46) e_ptr->filterPeakMap(pm); TEST_EQUAL(pm.begin()->rbegin()->getIntensity(), 1) Param p(e_ptr->getParameters()); p.setValue("method", "to_TIC"); e_ptr->setParameters(p); e_ptr->filterPeakMap(pm); double sum(0); for (PeakMap::SpectrumType::ConstIterator it = pm.begin()->begin(); it != pm.begin()->end(); ++it) { sum += it->getIntensity(); } TEST_REAL_SIMILAR(sum, 1.0); END_SECTION START_SECTION((void filterPeakSpectrum(PeakSpectrum& spectrum) const)) delete e_ptr; e_ptr = new Normalizer(); PeakSpectrum spec = spec_ref; e_ptr->filterPeakSpectrum(spec); TEST_EQUAL(spec.rbegin()->getIntensity(), 1) Param p(e_ptr->getParameters()); p.setValue("method", "to_TIC"); e_ptr->setParameters(p); e_ptr->filterPeakSpectrum(spec); double sum(0); for (PeakSpectrum::ConstIterator it = spec.begin(); it != spec.end(); ++it) { sum += it->getIntensity(); } TEST_REAL_SIMILAR(sum, 1.0); END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/StringListUtils_test.cpp
.cpp
16,630
305
// 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/DATASTRUCTURES/StringListUtils.h> #include <QStringList> #include <OpenMS/DATASTRUCTURES/ListUtils.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(StringList, "$Id$") ///////////////////////////////////////////////////////////// START_SECTION((static StringList fromQStringList(const QStringList &rhs))) { QStringList q_str_list; q_str_list << "First Element" << "Second Element" << "Third Element"; StringList str_list = StringListUtils::fromQStringList(q_str_list); TEST_EQUAL((int)str_list.size(), q_str_list.size()) ABORT_IF((int)str_list.size() != q_str_list.size()) for(Size i = 0 ; i < str_list.size() ; ++i) { TEST_EQUAL(str_list[i], String(q_str_list[(int)i])) } } END_SECTION START_SECTION((static void toUpper(StringList &sl))) { StringList list = ListUtils::create<String>("yes,no"); StringListUtils::toUpper(list); TEST_EQUAL(list[0],"YES") TEST_EQUAL(list[1],"NO") } END_SECTION START_SECTION((static void toLower(StringList &sl))) { StringList list = ListUtils::create<String>("yES,nO"); StringListUtils::toLower(list); TEST_EQUAL(list[0],"yes") TEST_EQUAL(list[1],"no") } END_SECTION StringList tmp_list; tmp_list.push_back("first_line"); tmp_list.push_back(""); tmp_list.push_back(""); tmp_list.push_back("middle_line"); tmp_list.push_back(""); tmp_list.push_back(" space_line"); tmp_list.push_back(" tab_line"); tmp_list.push_back("back_space_line "); tmp_list.push_back("back_tab_line "); tmp_list.push_back(""); tmp_list.push_back("last_line"); StringList tmp_list2; tmp_list2.push_back("first_line"); tmp_list2.push_back(""); tmp_list2.push_back(""); tmp_list2.push_back("middle_line"); tmp_list2.push_back(""); tmp_list2.push_back("space_line"); tmp_list2.push_back("tab_line"); tmp_list2.push_back("back_space_line"); tmp_list2.push_back("back_tab_line"); tmp_list2.push_back(""); tmp_list2.push_back("last_line"); START_SECTION((static Iterator searchPrefix(const Iterator &start, const Iterator &end, const String &text, bool trim=false))) { StringList list(tmp_list); TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "first_line") == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "middle_line") == (list.begin()+3), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "space_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "tab_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "last_line") == (list.end()-1), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "invented_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin()+1, list.end(), "first_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), " ") == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "\t") == (list.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin()+9, list.end() ,"\t") == (list.end()), true) //trim TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "first_line",true) == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "space_line",true) == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "tab_line",true) == (list.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "invented_line",true) == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin()+1, list.end(), "first_line",true) == list.end(), true) //Try it on the same file (but trimmed) list = tmp_list2; TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "first_line") == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "middle_line") == (list.begin()+3), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "space_line",true) == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "tab_line",true) == (list.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "last_line") == (list.end()-1), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "invented_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin()+1, list.end(), "first_line") == list.end(), true) //trim TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "first_line",true) == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "space_line",true) == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "tab_line",true) == (list.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "invented_line",true) == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin()+1, list.end(), "first_line",true) == list.end(), true) } END_SECTION START_SECTION((static Iterator searchPrefix(StringList &container, const String &text, bool trim=false))) { StringList list(tmp_list); TEST_EQUAL(StringListUtils::searchPrefix(list, "first_line") == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "middle_line") == (list.begin()+3), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "space_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "tab_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "last_line") == (list.end()-1), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "invented_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, " ") == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "\t") == (list.begin()+6), true) //trim TEST_EQUAL(StringListUtils::searchPrefix(list, "first_line",true) == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "space_line",true) == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "tab_line",true) == (list.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "invented_line",true) == list.end(), true) //Try it on the same file (but trimmed) list = tmp_list2; TEST_EQUAL(StringListUtils::searchPrefix(list, "first_line") == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "middle_line") == (list.begin()+3), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "space_line",true) == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "tab_line",true) == (list.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "last_line") == (list.end()-1), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "invented_line") == list.end(), true) //trim TEST_EQUAL(StringListUtils::searchPrefix(list, "first_line",true) == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "space_line",true) == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "tab_line",true) == (list.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "invented_line",true) == list.end(), true) } END_SECTION START_SECTION((static Iterator searchSuffix(const Iterator &start, const Iterator &end, const String &text, bool trim=false))) { StringList list(tmp_list); TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "invented_line",true) == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "back_space_line",true) == list.begin()+7, true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "back_tab_line",true) == list.begin()+8, true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin()+8, list.end(), "back_space_line",true) == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "invented_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "back_space_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "back_tab_line") == list.end(), true) } END_SECTION START_SECTION((static Iterator searchSuffix(StringList &container, const String &text, bool trim=false))) { StringList list(tmp_list); TEST_EQUAL(StringListUtils::searchSuffix(list, "invented_line",true) == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list, "back_space_line",true) == list.begin()+7, true) TEST_EQUAL(StringListUtils::searchSuffix(list, "back_tab_line",true) == list.begin()+8, true) TEST_EQUAL(StringListUtils::searchSuffix(list, "invented_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list, "back_space_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list, "back_tab_line") == list.end(), true) } END_SECTION START_SECTION((static ConstIterator searchPrefix(const ConstIterator &start, const ConstIterator &end, const String &text, bool trim=false))) { const StringList list(tmp_list); TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "first_line") == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "middle_line") == (list.begin()+3), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "space_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "tab_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "last_line") == (list.end()-1), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "invented_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin() + 1, list.end(), "first_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), " ") == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "\t") == (list.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin() + 9, list.end(), "\t") == (list.end()), true) //trim TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "first_line",true) == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "space_line",true) == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "tab_line",true) == (list.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin(), list.end(), "invented_line",true) == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list.begin() + 1, list.end(), "first_line",true) == list.end(), true) //Try it on the same file (but trimmed) const StringList list2 = tmp_list2; TEST_EQUAL(StringListUtils::searchPrefix(list2.begin(), list2.end(), "first_line") == list2.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list2.begin(), list2.end(), "middle_line") == (list2.begin()+3), true) TEST_EQUAL(StringListUtils::searchPrefix(list2.begin(), list2.end(), "space_line",true) == (list2.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list2.begin(), list2.end(), "tab_line",true) == (list2.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list2.begin(), list2.end(), "last_line") == (list2.end()-1), true) TEST_EQUAL(StringListUtils::searchPrefix(list2.begin(), list2.end(), "invented_line") == list2.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list2.begin() + 1, list2.end(), "first_line") == list2.end(), true) //trim TEST_EQUAL(StringListUtils::searchPrefix(list2.begin(), list2.end(), "first_line",true) == list2.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list2.begin(), list2.end(), "space_line",true) == (list2.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list2.begin(), list2.end(), "tab_line",true) == (list2.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list2.begin(), list2.end(), "invented_line",true) == list2.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list2.begin() + 1, list2.end(), "first_line",true) == list2.end(), true) } END_SECTION START_SECTION((static ConstIterator searchPrefix(const StringList &container, const String &text, bool trim=false))) { const StringList list(tmp_list); TEST_EQUAL(StringListUtils::searchPrefix(list, "first_line") == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "middle_line") == (list.begin()+3), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "space_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "tab_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "last_line") == (list.end()-1), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "invented_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, " ") == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "\t") == (list.begin()+6), true) //trim TEST_EQUAL(StringListUtils::searchPrefix(list, "first_line",true) == list.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "space_line",true) == (list.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "tab_line",true) == (list.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list, "invented_line",true) == list.end(), true) //Try it on the same file (but trimmed) const StringList list2 = tmp_list2; TEST_EQUAL(StringListUtils::searchPrefix(list2, "first_line") == list2.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list2, "middle_line") == (list2.begin()+3), true) TEST_EQUAL(StringListUtils::searchPrefix(list2, "space_line",true) == (list2.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list2, "tab_line",true) == (list2.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list2, "last_line") == (list2.end()-1), true) TEST_EQUAL(StringListUtils::searchPrefix(list2, "invented_line") == list2.end(), true) //trim TEST_EQUAL(StringListUtils::searchPrefix(list2, "first_line",true) == list2.begin(), true) TEST_EQUAL(StringListUtils::searchPrefix(list2, "space_line",true) == (list2.begin()+5), true) TEST_EQUAL(StringListUtils::searchPrefix(list2, "tab_line",true) == (list2.begin()+6), true) TEST_EQUAL(StringListUtils::searchPrefix(list2, "invented_line",true) == list2.end(), true) } END_SECTION START_SECTION((static ConstIterator searchSuffix(const ConstIterator &start, const ConstIterator &end, const String &text, bool trim=false))) { const StringList list(tmp_list); TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "invented_line",true) == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "back_space_line",true) == list.begin()+7, true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "back_tab_line",true) == list.begin()+8, true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin() + 8, list.end(), "back_space_line",true) == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "invented_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "back_space_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list.begin(), list.end(), "back_tab_line") == list.end(), true) } END_SECTION START_SECTION((static ConstIterator searchSuffix(const StringList &container, const String &text, bool trim=false))) { const StringList list(tmp_list); TEST_EQUAL(StringListUtils::searchSuffix(list, "invented_line",true) == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list, "back_space_line",true) == list.begin()+7, true) TEST_EQUAL(StringListUtils::searchSuffix(list, "back_tab_line",true) == list.begin()+8, true) TEST_EQUAL(StringListUtils::searchSuffix(list, "invented_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list, "back_space_line") == list.end(), true) TEST_EQUAL(StringListUtils::searchSuffix(list, "back_tab_line") == list.end(), true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConsensusIDAlgorithmWorst_test.cpp
.cpp
4,746
152
// 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/ConsensusIDAlgorithmWorst.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(ConsensusIDAlgorithmWorst, "$Id$") ///////////////////////////////////////////////////////////// ConsensusIDAlgorithm* ptr = nullptr; ConsensusIDAlgorithm* null_pointer = nullptr; START_SECTION(ConsensusIDAlgorithmWorst()) { ptr = new ConsensusIDAlgorithmWorst(); TEST_NOT_EQUAL(ptr, null_pointer); } END_SECTION START_SECTION(~ConsensusIDAlgorithmWorst()) { 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) ConsensusIDAlgorithmWorst consensus; // define parameters: Param param; param.setValue("filter:considered_hits", 0); consensus.setParameters(param); // apply: PeptideIdentificationList f = ids; map<String,String> empty; consensus.apply(f, empty); TEST_EQUAL(f.size(), 1); hits = f[0].getHits(); TEST_EQUAL(hits.size(), 11); TEST_EQUAL(hits[0].getSequence(), AASequence::fromString("F")); TEST_REAL_SIMILAR(hits[0].getScore(), 0.0); TEST_EQUAL(hits[1].getSequence(), AASequence::fromString("G")); TEST_REAL_SIMILAR(hits[1].getScore(), 0.2); TEST_EQUAL(hits[2].getSequence(), AASequence::fromString("C")); TEST_REAL_SIMILAR(hits[2].getScore(), 0.3); // hits with the same score get assigned the same rank: TEST_EQUAL(hits[3].getSequence(), AASequence::fromString("A")); TEST_REAL_SIMILAR(hits[3].getScore(), 0.4); TEST_EQUAL(hits[4].getSequence(), AASequence::fromString("D")); TEST_REAL_SIMILAR(hits[4].getScore(), 0.4); TEST_EQUAL(hits[5].getSequence(), AASequence::fromString("E")); TEST_REAL_SIMILAR(hits[5].getScore(), 0.5); TEST_EQUAL(hits[6].getSequence(), AASequence::fromString("B")); TEST_REAL_SIMILAR(hits[6].getScore(), 0.6); TEST_EQUAL(hits[7].getSequence(), AASequence::fromString("H")); TEST_REAL_SIMILAR(hits[7].getScore(), 0.6); TEST_EQUAL(hits[8].getSequence(), AASequence::fromString("I")); TEST_REAL_SIMILAR(hits[8].getScore(), 0.7); TEST_EQUAL(hits[9].getSequence(), AASequence::fromString("J")); TEST_REAL_SIMILAR(hits[9].getScore(), 0.8); TEST_EQUAL(hits[10].getSequence(), AASequence::fromString("K")); TEST_REAL_SIMILAR(hits[10].getScore(), 0.9); ids[2].setHigherScoreBetter(true); TEST_EXCEPTION(Exception::InvalidValue, consensus.apply(ids, empty)); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AhoCorasickAmbiguous_test.cpp
.cpp
13,021
440
// 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/ANALYSIS/ID/AhoCorasickAmbiguous.h> /////////////////////////// #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <array> #include <cassert> #include <string_view> using namespace OpenMS; using namespace std; /////////////////////////// /////////////////////////// void compareHits(int line, const string& protein, String expected_s, StringList& observed) { std::cout << "results of test line " << line << " for protein " << protein << ":\n"; //expected_s.toUpper(); StringList expected = ListUtils::create<String>(expected_s.removeWhitespaces(), ','); std::sort(expected.begin(), expected.end()); std::sort(observed.begin(), observed.end()); TEST_EQUAL(observed.size(), expected.size()) // results should have same number of entries if (expected.size() == observed.size()) { for (size_t i = 0; i < expected.size(); ++i) { //expected[i] = expected[i].toUpper(); std::cout << "hit " << i << ": " << expected[i] << " <> " << observed[i] << "\n"; TEST_EQUAL(expected[i], observed[i]) if (expected[i] != observed[i]) { std::cout << "difference!" << expected[i] << observed[i] << '\n'; } } } else { std::cout << "Results differ in number of hits:\n expected:\n " << ListUtils::concatenate(expected, "\n ") << " \nobserved:\n " << ListUtils::concatenate(observed, "\n ") << "\n"; } } void testCase(const ACTrie& t, const string& protein, const string& expected, vector<string>& needles, int line) { std::vector<String> observed; ACTrieState state; state.setQuery(protein); while (t.nextHits(state)) { for (auto& hit : state.hits) { observed.push_back(needles[hit.needle_index] + "@" + String(hit.query_pos)); } } compareHits(line, protein, expected, observed); } template<int SIZE> void checkAAIterator(const std::array<AA, SIZE>& aa_array, const std::array<size_t, SIZE>& pos_array, ACTrieState& state) { size_t i = 0; for (AA aa = state.nextValidAA(); aa.isValid(); aa = state.nextValidAA(), ++i) { TEST_EQUAL(aa == aa_array[i], true); TEST_EQUAL(state.textPos(), pos_array[i]); } TEST_EQUAL(aa_array.size(), i) } START_TEST(AhoCorasickAmbiguous, "$Id$") ACTrie* ptr = 0; ACTrie* nullPointer = 0; START_SECTION(ACTrie(uint32_t max_aaa = 0, uint32_t max_mm = 0)) { ptr = new ACTrie(1, 0); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~ACTrie()) { delete ptr; } END_SECTION START_SECTION(void addNeedle(const std::string& needle)) ACTrie t(1,2); t.addNeedle("WITHV"); // normal AA's are allowed t.addNeedle("WITHB"); // ambiguous char 'B' is allowed t.addNeedle("WITHJ"); // ambiguous char 'J' is allowed t.addNeedle("WITHZ"); // ambiguous char 'Z' is allowed t.addNeedle("WITHX"); // ambiguous char 'X' is allowed TEST_EXCEPTION(Exception::InvalidValue, t.addNeedle("WITH$")) TEST_EXCEPTION(Exception::InvalidValue, t.addNeedle("WITH*")) TEST_EQUAL(t.getNeedleCount(), 5) TEST_EQUAL(t.getMaxAAACount(), 1) TEST_EQUAL(t.getMaxMMCount(), 2) END_SECTION START_SECTION(void addNeedles(const std::vector<std::string>& needle)) ACTrie t(1, 2); t.addNeedle("WITHV"); // normal AA's are allowed t.addNeedle("WITHB"); // ambiguous char 'B' is allowed t.addNeedle("WITHJ"); // ambiguous char 'J' is allowed TEST_EXCEPTION(Exception::InvalidValue, t.addNeedles({"WITHZ", "WITHX","WITH$"})) TEST_EQUAL(t.getNeedleCount(), 5) END_SECTION START_SECTION(void compressTrie()) NOT_TESTABLE // needs context... END_SECTION START_SECTION(size_t getNeedleCount() const) NOT_TESTABLE // tested above END_SECTION START_SECTION(void setMaxAAACount(const uint32_t max_aaa)) NOT_TESTABLE // tested below END_SECTION START_SECTION(uint32_t getMaxAAACount() const) NOT_TESTABLE // tested above END_SECTION START_SECTION(void setMaxMMCount(const uint32_t max_mm)) NOT_TESTABLE // tested below END_SECTION START_SECTION(uint32_t getMaxMMCount() const) NOT_TESTABLE // tested above END_SECTION START_SECTION(bool nextHits(ACTrieState& state) const) { // // Note: we do not care about trypticity at this level! // ACTrie t(0, 0); std::vector<string> needles = {"acd", "adc", "cad", "cda", "dac", "dca"}; t.addNeedlesAndCompress(needles); ///////////////////////// // "acd,adc,cad,cda,dac,dca" ///////////////////////// // all six hits, found without spawning(ambAA)) testCase(t, "acdIadcIcadIcdaIdacIdca", "acd@0, adc@4, cad@8, cda@12, dac@16, dca@20", needles, __LINE__); /// /// same, but with ambAA's allowed (but not used) /// t.setMaxAAACount(3); // all six hits, found without spawning(ambAA) testCase(t, "acdIadcIcadIcdaIdacIdca", "acd@0, adc@4, cad@8, cda@12, dac@16, dca@20", needles, __LINE__); /// /// all ambAA's /// // all six hits, found at first position testCase(t, "XXX", "dac@0, cad@0, cda@0, dca@0, adc@0, acd@0", needles, __LINE__); /// /// with prefix /// // 2 hits of aXX at first pos; all six hits, found at second position testCase(t, "aXXX", "acd@0, adc@0, dac@1, cad@1, cda@1, dca@1, adc@1, acd@1", needles, __LINE__); /// /// with prefix and B instead of X /// // B = D|N; Z = E|Q testCase(t, "aXBX", "acd@0, cda@1, adc@1", needles, __LINE__); /// /// test with two ambAA's: nothing should be found /// t.setMaxAAACount(2); testCase(t, "XXX", "", needles, __LINE__); /// /// only two hits (due to ambAA==2) /// t.setMaxAAACount(2); // 2 hits of aXX at first pos; nothing at second pos (since that requires three AAA) testCase(t, "aXXX", "acd@0, adc@0", needles, __LINE__); /// /// with suffix /// // 2 hits of XXc at second pos; nothing at first pos (since that requires three AAA) testCase(t, "XXXc", "adc@1, dac@1", needles, __LINE__); /// /// new peptide DB /// t = ACTrie(2, 0); needles = {"eq", "nd", "llll"}; t.addNeedlesAndCompress(needles); /// /// hits across the protein /// // B = D|N, Z = E|Q // both match XX@1, eq matches ZZ, nd matches BB testCase(t, "aXXaBBkkZZlllllk", "nd@1, nd@4, eq@1, eq@8, llll@10, llll@11 ", needles, __LINE__); /// /// mismatches /// /// /// same, but with mm's allowed (but not sufficient) /// t = ACTrie(0, 1); needles = {"acd", "adc", "cad", "cda", "dac", "dca"}; t.addNeedlesAndCompress(needles); testCase(t, "aaaIIcccIIddd", "", needles, __LINE__); /// /// full usage of mm's /// t = ACTrie(0, 3); t.addNeedlesAndCompress(needles); testCase(t, "mmmm", " dac@0, cad@0, cda@0, dca@0, adc@0, acd@0" // all six hits, found at first position ", dac@1, cad@1, cda@1, dca@1, adc@1, acd@1" // all six hits, found at second position , needles, __LINE__); /// /// with prefix /// t.setMaxMMCount(2); testCase(t, "aMMM", "acd@0, adc@0", // 2 hits of aXX at first pos needles, __LINE__); /// /// with prefix and B /// t.setMaxAAACount(1); testCase(t, "aMMB", " adc@0, acd@0" // 2 hits of aXx at first pos ", cad@1, acd@1" // 2 hits of XXB, found at second position , needles, __LINE__); /// /// new peptide DB /// t = ACTrie(1, 1); needles = {"eq", "nd", "llll"}; t.addNeedlesAndCompress(needles); /// /// hits across the protein /// testCase(t, "aXXaBBkkZZlllllk", "nd@0, nd@1, nd@2, nd@3, nd@4, nd@5, eq@0, eq@1, eq@2, eq@7, eq@8, eq@9, llll@9, llll@10, llll@11, llll@12 " // nd matches all positions of 'aXXaBk';; eq matches 'aXXa' and 'kZZl' ;; llll matches 'Zlllllk' , needles, __LINE__); /// /// matching Peptides WITH AAA's in them (should just be matched without digging into AAA/MM reserves) /// t = ACTrie(0, 0); needles = {"acb", "abc", "cda", "bac", "anc", "acn", "dad"}; t.addNeedlesAndCompress(needles); testCase(t, "baxyacbIIabcIIbac", "acb@4, abc@9, bac@14", needles, __LINE__); t = ACTrie(1, 0); // B = D|N, Z = E|Q t.addNeedlesAndCompress(needles); testCase(t, "baxyacbIIabcIIbac", "acb@4, abc@9, bac@0, bac@14, anc@9, acn@4", needles, __LINE__); t = ACTrie(2, 0); // B = D|N, Z = E|Q needles = {"dad", "bax", "bac", "anc", "acn"}; t.addNeedlesAndCompress(needles); testCase(t, "baxyacbIIabcIIbac", "dad@0, bax@0, bac@0, bac@14, anc@9, acn@4", needles, __LINE__); t = ACTrie(2, 2); // B = D|N, Z = E|Q needles = {"dady", "baxy", "iibac", "ancii", "yaknif"}; t.addNeedlesAndCompress(needles); testCase(t, "baxyacbIIabcIIbac", "dady@0, baxy@0, dady@8, ancii@4, ancii@9, iibac@1, iibac@7, iibac@12, yaknif@3", needles, __LINE__); t = ACTrie(0, 0); needles = {"PEPTIDER", "XXXBEBEAR"}; t.addNeedlesAndCompress(needles); testCase(t, "PEPTIDERXXXBEBEAR", "PEPTIDER@0, XXXBEBEAR@8", needles, __LINE__); /// /// TEST if offsets into proteins are correct in the presence of non-AA characters like '*' /// NOTE: offsets will be incorrect if a hit overlaps with a '*', since the trie only knows the length of a hit and the end position /// in the protein, thus computing the start will be off by the amount of '*'s t = ACTrie(0, 0); needles = {"MLTEAEK"}; t.addNeedlesAndCompress(needles); testCase(t, "*MLTEAXK*", "", needles, __LINE__); t = ACTrie(1, 0); needles = {"MLTEAEK"}; t.addNeedlesAndCompress(needles); testCase(t, "*MLTEAXK*", "MLTEAEK@1", needles, __LINE__); /// /// test if spawn does not report hits which do not cover its first AAA /// t = ACTrie(4, 0); needles = {"MDDDEADC", "MDD", "DD", "DEADC"}; t.addNeedlesAndCompress(needles); testCase(t, "MBBDEABCRAFG", "MDDDEADC@0, MDD@0, DD@1, DD@2, DEADC@3", needles, __LINE__); //MDDDEADC } END_SECTION START_SECTION(void getAllHits(ACTrieState& state) const) NOT_TESTABLE // tested above END_SECTION ///////////////////////////////////// //// testing ACTrieState ///////////////////////////////////// START_SECTION(void setQuery(const std::string& haystack)) ACTrieState state; string q("PFAINGER"); state.setQuery(q); TEST_EQUAL(state.getQuery(), q); TEST_EQUAL(state.hits.size(), 0); TEST_EQUAL(state.tree_pos(), 0); TEST_TRUE(*state.textPosIt() == *state.getQuery().cbegin()); TEST_TRUE(state.scouts.empty()); TEST_EQUAL(state.textPos(), 0); END_SECTION START_SECTION(size_t textPos() const) NOT_TESTABLE // tested above END_SECTION START_SECTION(std::string::const_iterator textPosIt() const) NOT_TESTABLE // tested above END_SECTION START_SECTION(const std::string& getQuery() const) NOT_TESTABLE // tested above END_SECTION START_SECTION(AA nextValidAA()) ACTrieState state; { constexpr string_view sv = "PFBNX"; state.setQuery(string(sv.data())); checkAAIterator<5>({AA('P'), AA('F'), AA('B'), AA('N'), AA('X')}, {1, 2, 3, 4, 5}, state); } { constexpr string_view sv = "?X*B**"; state.setQuery(string(sv.data())); TEST_EQUAL(state.getQuery(), sv); checkAAIterator<2>({AA('X'), AA('B')}, {2, 4}, state); } { state.setQuery(""); TEST_EQUAL(state.nextValidAA().isValid(), false); } END_SECTION START_SECTION(AA nextValidAA()) NOT_TESTABLE // tested above END_SECTION ///////////////////////////////////// //// testing AA ///////////////////////////////////// START_SECTION(constexpr AA()) { // make sure ctor is constexpr static_assert(AA('?').isValid() == false); static_assert(AA('?')() == CharToAA[(unsigned char)'?']); static_assert(AA('G') <= AA('B')); static_assert(AA('B').isAmbiguous()); static_assert(AA('J').isAmbiguous()); static_assert(AA('Z').isAmbiguous()); static_assert(AA('X').isAmbiguous()); static_assert(AA('$').isAmbiguous()); static_assert(AA('B')++ == AA('B')); static_assert(++AA('B') == AA('J')); static_assert((AA('B') - AA('B'))() == 0); static_assert((AA('J') - AA('B'))() == 1); static_assert((AA('Z') - AA('B'))() == 2); static_assert((AA('X') - AA('B'))() == 3); for (char c = 'A'; c <= 'Z'; ++c) assert(AA(c).isValidForPeptide()); static_assert(!AA('?').isValidForPeptide()); static_assert(!AA('$').isValidForPeptide()); static_assert(!AA(' ').isValidForPeptide()); static_assert(!AA('*').isValidForPeptide()); static_assert(!AA('3').isValidForPeptide()); static_assert(!AA('#').isValidForPeptide()); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GaussFitter1D_test.cpp
.cpp
2,297
88
// 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/GaussFitter1D.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(GaussFitter1D, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// GaussFitter1D* ptr = nullptr; GaussFitter1D* nullPointer = nullptr; START_SECTION(GaussFitter1D()) { ptr = new GaussFitter1D(); TEST_EQUAL(ptr->getName(), "GaussFitter1D") TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((GaussFitter1D(const GaussFitter1D &source))) GaussFitter1D gf1; Param param; param.setValue( "tolerance_stdev_bounding_box", 1.0); param.setValue( "statistics:mean", 680.1 ); param.setValue( "statistics:variance", 2.0 ); param.setValue( "interpolation_step", 1.0 ); gf1.setParameters(param); GaussFitter1D gf2(gf1); GaussFitter1D gf3; gf3.setParameters(param); gf1 = GaussFitter1D(); TEST_EQUAL(gf3.getParameters(), gf2.getParameters()) END_SECTION START_SECTION((virtual ~GaussFitter1D())) delete ptr; END_SECTION START_SECTION((virtual GaussFitter1D& operator=(const GaussFitter1D &source))) GaussFitter1D gf1; Param param; param.setValue( "tolerance_stdev_bounding_box", 1.0); param.setValue( "statistics:mean", 680.1 ); param.setValue( "statistics:variance", 2.0 ); param.setValue( "interpolation_step", 1.0 ); gf1.setParameters(param); GaussFitter1D gf2; gf2 = gf1; GaussFitter1D gf3; gf3.setParameters(param); gf1 = GaussFitter1D(); TEST_EQUAL(gf3.getParameters(), gf2.getParameters()) END_SECTION START_SECTION((QualityType fit1d(const RawDataArrayType &range, InterpolationModel *&model))) // dummy subtest TEST_EQUAL(1,1) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SequestOutfile_test.cpp
.cpp
25,569
453
// 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/FORMAT/SequestOutfile.h> #include <OpenMS/METADATA/ProteinIdentification.h> using namespace OpenMS; using namespace std; START_TEST(String, "$Id$") SequestOutfile* ptr = nullptr; SequestOutfile* nullPointer = nullptr; START_SECTION(SequestOutfile()) ptr = new SequestOutfile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~SequestOutfile()) delete ptr; END_SECTION START_SECTION((SequestOutfile& operator=(const SequestOutfile &sequest_outfile))) SequestOutfile sequest_outfile1; SequestOutfile sequest_outfile2; sequest_outfile2 = sequest_outfile1; SequestOutfile sequest_outfile3; sequest_outfile1 = SequestOutfile(); TEST_EQUAL(( sequest_outfile2 == sequest_outfile3 ), true) END_SECTION START_SECTION((SequestOutfile(const SequestOutfile &sequest_outfile))) SequestOutfile sequest_outfile1; SequestOutfile sequest_outfile2(sequest_outfile1); SequestOutfile sequest_outfile3; sequest_outfile1 = SequestOutfile(); TEST_EQUAL(( sequest_outfile2 == sequest_outfile3 ), true) END_SECTION START_SECTION((bool operator==(const SequestOutfile &sequest_outfile) const)) SequestOutfile sequest_outfile1; SequestOutfile sequest_outfile2; TEST_EQUAL(( sequest_outfile1 == sequest_outfile2 ), true) END_SECTION SequestOutfile file; START_SECTION(void load(const String& result_filename, std::vector< PeptideIdentification >& peptide_identifications, ProteinIdentification& protein_identification, const double p_value_threshold, std::vector< double >& pvalues, const String& database="", const bool ignore_proteins_per_peptide=false)) PeptideIdentificationList peptide_identifications; ProteinIdentification protein_identification; vector< double > pvalues; // test exceptions TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.load("a", peptide_identifications, protein_identification, 0.01, pvalues), "the file 'a' could not be found") TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.load(OPENMS_GET_TEST_DATA_PATH("SequestOutfile.out1"), peptide_identifications, protein_identification, 0.01, pvalues), OPENMS_GET_TEST_DATA_PATH_MESSAGE("","SequestOutfile.out1", " in: Wrong number of columns in line 16! (11 present, should be 12)")) TEST_EXCEPTION(Exception::IllegalArgument, file.load("", peptide_identifications, protein_identification, 2.0, pvalues)) TEST_EXCEPTION(Exception::IllegalArgument, file.load("", peptide_identifications, protein_identification,-1.0, pvalues)) peptide_identifications.clear(); protein_identification.setHits(vector< ProteinHit >()); pvalues.clear(); // test the actual program file.load(OPENMS_GET_TEST_DATA_PATH("SequestOutfile2.out"), peptide_identifications, protein_identification, 1.0, pvalues); TEST_EQUAL(peptide_identifications.size(), 0) file.load(OPENMS_GET_TEST_DATA_PATH("SequestOutfile.out"), peptide_identifications, protein_identification, 1.0, pvalues); TEST_EQUAL(peptide_identifications.size(), 1) if ( peptide_identifications.size() == 1 ) { TEST_EQUAL(peptide_identifications[0].getHits().size(), 4) TEST_STRING_EQUAL(peptide_identifications[0].getScoreType(), "SEQUEST") TEST_STRING_EQUAL(peptide_identifications[0].getIdentifier(), "TurboSEQUEST_2004-03-16") TEST_REAL_SIMILAR(peptide_identifications[0].getSignificanceThreshold(), 1.0) if ( peptide_identifications[0].getHits().size() == 4 ) { TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[0].getScore(), 0.05) TEST_STRING_EQUAL(peptide_identifications[0].getHits()[0].getSequence().toString(), "ETQAWSIATILETLYDL") vector<PeptideEvidence> pes = peptide_identifications[0].getHits()[0].getPeptideEvidences(); TEST_EQUAL(pes[0].getAABefore(), 'C') TEST_EQUAL(pes[0].getAAAfter(), '-') TEST_EQUAL(peptide_identifications[0].getHits()[0].getRank(), 1) TEST_EQUAL(peptide_identifications[0].getHits()[0].getCharge(), 3) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[0].getMetaValue("RankSp")), "1/80") TEST_EQUAL(static_cast<Int>(peptide_identifications[0].getHits()[0].getMetaValue("SequestId")), 0) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[0].getMetaValue("MH")), 1967.0013) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[0].getMetaValue("DeltCn")), 0.0000) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[0].getMetaValue("XCorr")), 1.5789) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[0].getMetaValue("Sp")), 310.3) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[0].getMetaValue("Sf")), 0.05) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[0].getMetaValue("Ions")), "18/64") set<String> protein_accessions = peptide_identifications[0].getHits()[0].extractProteinAccessionsSet(); TEST_EQUAL(protein_accessions.size(), 3) if (protein_accessions.size() == 3 ) { set<String>::const_iterator s_it = protein_accessions.begin(); TEST_STRING_EQUAL(*s_it++, "2136928") TEST_STRING_EQUAL(*s_it++, "L10605") TEST_STRING_EQUAL(*s_it++, "P35574") } TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[1].getScore(), 0.04) TEST_STRING_EQUAL(peptide_identifications[0].getHits()[1].getSequence().toString(), "QVLNPLLVLIFIPLFDL") PeptideEvidence pe = peptide_identifications[0].getHits()[1].getPeptideEvidences()[0]; TEST_EQUAL(pe.getAABefore(), 'M') TEST_EQUAL(pe.getAAAfter(), 'V') TEST_EQUAL(peptide_identifications[0].getHits()[1].getRank(), 2) TEST_EQUAL(peptide_identifications[0].getHits()[1].getCharge(), 3) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[1].getMetaValue("RankSp")), "2/85") TEST_EQUAL(static_cast<Int>(peptide_identifications[0].getHits()[1].getMetaValue("SequestId")), 0) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[1].getMetaValue("MH")), 1967.1985) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[1].getMetaValue("DeltCn")), 0.0390) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[1].getMetaValue("XCorr")), 1.5173) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[1].getMetaValue("Sp")), 308.3) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[1].getMetaValue("Sf")), 0.04) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[1].getMetaValue("Ions")), "19/64") TEST_EQUAL(peptide_identifications[0].getHits()[1].getPeptideEvidences().size(), 2) if ( peptide_identifications[0].getHits()[1].getPeptideEvidences().size() == 2 ) { TEST_STRING_EQUAL(peptide_identifications[0].getHits()[1].getPeptideEvidences()[0].getProteinAccession(), "P46029") TEST_STRING_EQUAL(peptide_identifications[0].getHits()[1].getPeptideEvidences()[1].getProteinAccession(), "U32507") } TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[2].getScore(), 0.02) TEST_STRING_EQUAL(peptide_identifications[0].getHits()[2].getSequence().toString(), "WVELGPSVLAGVGVMVLLI") pes = peptide_identifications[0].getHits()[2].getPeptideEvidences(); TEST_EQUAL(pes[0].getAABefore(), 'L') TEST_EQUAL(pes[0].getAAAfter(), 'P') TEST_EQUAL(peptide_identifications[0].getHits()[2].getRank(), 3) TEST_EQUAL(peptide_identifications[0].getHits()[2].getCharge(), 3) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[2].getMetaValue("RankSp")), "3/117") TEST_EQUAL(static_cast<Int>(peptide_identifications[0].getHits()[2].getMetaValue("SequestId")), 0) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[2].getMetaValue("MH")), 1968.1244) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[2].getMetaValue("DeltCn")), 0.0501) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[2].getMetaValue("XCorr")), 1.4998) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[2].getMetaValue("Sp")), 292.4) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[2].getMetaValue("Sf")), 0.02) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[2].getMetaValue("Ions")), "17/72") TEST_EQUAL(pes.size(), 1) if ( pes.size() == 1 ) { TEST_STRING_EQUAL(pes[0].getProteinAccession(), "e148876") } TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[3].getScore(), 0.14) TEST_STRING_EQUAL(peptide_identifications[0].getHits()[3].getSequence().toString(), "FDEITAMTGDGVNDAPALK") pes = peptide_identifications[0].getHits()[3].getPeptideEvidences(); TEST_EQUAL(pes[0].getAABefore(), 'S') TEST_EQUAL(pes[0].getAAAfter(), 'K') TEST_EQUAL(peptide_identifications[0].getHits()[3].getRank(), 4) TEST_EQUAL(peptide_identifications[0].getHits()[3].getCharge(), 3) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[3].getMetaValue("RankSp")), "4/1") TEST_EQUAL(static_cast<Int>(peptide_identifications[0].getHits()[3].getMetaValue("SequestId")), 0) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[3].getMetaValue("MH")), 1964.9275) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[3].getMetaValue("DeltCn")), 0.0627) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[3].getMetaValue("XCorr")), 1.4799) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[3].getMetaValue("Sp")), 530.9) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[3].getMetaValue("Sf")), 0.14) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[3].getMetaValue("Ions")), "24/72") TEST_EQUAL(pes.size(), 8) if ( pes.size() == 8 ) { TEST_STRING_EQUAL(pes[0].getProteinAccession(), "P20647") TEST_STRING_EQUAL(pes[1].getProteinAccession(), "P04192") TEST_STRING_EQUAL(pes[2].getProteinAccession(), "67962") TEST_STRING_EQUAL(pes[3].getProteinAccession(), "67961") TEST_STRING_EQUAL(pes[4].getProteinAccession(), "109166") TEST_STRING_EQUAL(pes[5].getProteinAccession(), "224621") TEST_STRING_EQUAL(pes[6].getProteinAccession(), "X02814") TEST_STRING_EQUAL(pes[7].getProteinAccession(), "J04703") } } } peptide_identifications.clear(); pvalues.push_back(0.001); pvalues.push_back(0.01); pvalues.push_back(0.05); pvalues.push_back(0.5); file.load(OPENMS_GET_TEST_DATA_PATH("SequestOutfile.out"), peptide_identifications, protein_identification, 0.01, pvalues); TEST_EQUAL(peptide_identifications.size(), 1) if ( peptide_identifications.size() == 1 ) { TEST_STRING_EQUAL(peptide_identifications[0].getScoreType(), "SEQUEST") TEST_STRING_EQUAL(peptide_identifications[0].getIdentifier(), "TurboSEQUEST_2004-03-16") TEST_EQUAL(peptide_identifications[0].getHits().size(), 2) TEST_REAL_SIMILAR(peptide_identifications[0].getSignificanceThreshold(), 0.01) if ( peptide_identifications[0].getHits().size() == 2 ) { TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[0].getScore(), 0.05) TEST_STRING_EQUAL(peptide_identifications[0].getHits()[0].getSequence().toString(), "ETQAWSIATILETLYDL") vector<PeptideEvidence> pes = peptide_identifications[0].getHits()[0].getPeptideEvidences(); TEST_EQUAL(pes[0].getAABefore(), 'C') TEST_EQUAL(pes[0].getAAAfter(), '-') TEST_EQUAL(peptide_identifications[0].getHits()[0].getRank(), 1) TEST_EQUAL(peptide_identifications[0].getHits()[0].getCharge(), 3) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[0].getMetaValue("RankSp")), "1/80") TEST_EQUAL(static_cast<Int>(peptide_identifications[0].getHits()[0].getMetaValue("SequestId")), 0) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[0].getMetaValue("MH")), 1967.0013) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[0].getMetaValue("DeltCn")), 0.0000) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[0].getMetaValue("XCorr")), 1.5789) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[0].getMetaValue("Sp")), 310.3) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[0].getMetaValue("Sf")), 0.05) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[0].getMetaValue("Ions")), "18/64") TEST_EQUAL(pes.size(), 3) if ( pes.size() == 3 ) { TEST_STRING_EQUAL(pes[0].getProteinAccession(), "P35574") TEST_STRING_EQUAL(pes[1].getProteinAccession(), "2136928") TEST_STRING_EQUAL(pes[2].getProteinAccession(), "L10605") } TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[1].getScore(), 0.04) TEST_STRING_EQUAL(peptide_identifications[0].getHits()[1].getSequence().toString(), "QVLNPLLVLIFIPLFDL") pes = peptide_identifications[0].getHits()[1].getPeptideEvidences(); TEST_EQUAL(pes[0].getAABefore(), 'M') TEST_EQUAL(pes[0].getAAAfter(), 'V') TEST_EQUAL(peptide_identifications[0].getHits()[1].getRank(), 2) TEST_EQUAL(peptide_identifications[0].getHits()[1].getCharge(), 3) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[1].getMetaValue("RankSp")), "2/85") TEST_EQUAL(static_cast<Int>(peptide_identifications[0].getHits()[1].getMetaValue("SequestId")), 0) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[1].getMetaValue("MH")), 1967.1985) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[1].getMetaValue("DeltCn")), 0.0390) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[1].getMetaValue("XCorr")), 1.5173) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[1].getMetaValue("Sp")), 308.3) TEST_REAL_SIMILAR(static_cast<double>(peptide_identifications[0].getHits()[1].getMetaValue("Sf")), 0.04) TEST_STRING_EQUAL(static_cast<String>(peptide_identifications[0].getHits()[1].getMetaValue("Ions")), "19/64") TEST_EQUAL(pes.size(), 2) if ( pes.size() == 2 ) { TEST_STRING_EQUAL(pes[0].getProteinAccession(), "P46029") TEST_STRING_EQUAL(pes[1].getProteinAccession(), "U32507") } } TEST_STRING_EQUAL(peptide_identifications[0].getIdentifier(), "TurboSEQUEST_2004-03-16") } TEST_STRING_EQUAL(protein_identification.getSearchEngine(), "TurboSEQUEST") TEST_STRING_EQUAL(protein_identification.getSearchEngineVersion(), "v.27 (rev. 12)") TEST_STRING_EQUAL(protein_identification.getIdentifier(), "TurboSEQUEST_2004-03-16") END_SECTION START_SECTION(bool getColumns(const String& line, vector< String >& substrings, Size number_of_columns, Size reference_column)) String line = " 1. 1/80 0 1967.0013 0.0000 1.5789 310.3 0.05 0 18/64 gi|544379|sp|P35574|GDE RABIT +2 C.ETQAWSIATILETLYDL.-"; vector< String > substrings, columns; columns.push_back("1."); columns.push_back("1/80"); columns.push_back("0"); columns.push_back("1967.0013"); columns.push_back("0.0000"); columns.push_back("1.5789"); columns.push_back("310.3"); columns.push_back("0.05"); columns.push_back("0"); columns.push_back("18/64"); columns.push_back("gi|544379|sp|P35574|GDE RABIT+2"); columns.push_back("C.ETQAWSIATILETLYDL.-"); TEST_EQUAL(file.getColumns("", substrings, 12, 10), false) TEST_EQUAL(file.getColumns(line, substrings, 12, 10), true) TEST_EQUAL((columns == substrings), true) line = " 1. 1/80 0 1967.0013 0.0000 1.5789 310.3 0.05 0 18/64 gi|544379|sp|P35574|GDE RABIT+2 C.ETQAWSIATILETLYDL.-"; TEST_EQUAL(file.getColumns(line, substrings, 12, 10), true) TEST_EQUAL((columns == substrings), true) line = " 1. 1/80 0 1967.0013 0.0000 1.5789 310.3 0.05 0 18/64 gi|544379|sp|P35574|GDE RABIT +X C.ETQAWSIATILETLYDL.-"; TEST_EQUAL(file.getColumns(line, substrings, 12, 10), true) columns[10] = "gi|544379|sp|P35574|GDE RABIT +X"; TEST_EQUAL((columns == substrings), true) END_SECTION START_SECTION(void getSequences(const String& database_filename, const map< String, Size >& ac_position_map, vector< String >& sequences, vector< pair< String, Size > >& found, map< String, Size >& not_found)) map< String, Size > ac_position_map, not_found; vector< String > sequences, found_sequences; vector< pair< String, Size > > found; // test exceptions TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.getSequences("a", not_found, found_sequences, found, not_found), "the file 'a' could not be found") // test the actual program ac_position_map["P02666"] = 0; ac_position_map["Q9CQV8"] = 1; ac_position_map["Q5EEQ7"] = 2; ac_position_map["P68509"] = 3; sequences.push_back("MKVLILACLVALALARELEELNVPGEIVESLSSSEESITRINKKIEKFQSEEQQQTEDELQDKIHPFAQTQSLVYPFPGPIPNSLPQNIPPLTQTPVVVPPFLQPEVMGVSKVKEAMAPKHKEMPFPKYPVEPFTESQSLTLTDVENLHLPLPLLQSWMHQPHQPLPPTVMFPPQSVLSLSQSKVLPVPQKAVPYPQRDMPIQAFLLYQEPVLGPVRGPFPIIV"); sequences.push_back("TMDKSELVQKAKLAEQAERYDDMAAAMKAVTEQGHELSNEERNLLSVAYKNVVGARRSSWRVISSIEQKTERNEKKQQMGKEYREKIEAELQDICNDVLELLDKYLILNATQAESKVFYLKMKGDYFRYLSEVASGENKQTTVSNSQQAYQEAFEISKKEMQPTHPIRLGLALNFSVFYYEILNSPEKACSLAKTAFDEAIAELDTLNEESYKDSTLIMQLLRDNLTLWTSENQGDEGDAGEGEN"); sequences.push_back("SAPPSLLVLYFGKKELRAMKVLILACLVALALARELEELNVPGEIVESLSSSEESITRINKKIEKFQSEEQQQTEDELQDKIHPFAQTQSLVYPFPGPIPNSLPQNIPPLTQTPVVVPP"); sequences.push_back("GDREQLLQRARLAEQAERYDDMASAMKAVTELNEPLSNEDRNLLSVAYKNVVGARRSSWRVISSIEQKTMADGNEKKLEKVKAYREKIEKELETVCNDVLALLDKFLIKNCNDFQYESKVFYLKMKGDYYRYLAEVASGEKKNSVVEASEAAYKEAFEISKEHMQPTHPIRLGLALNFSVFYYEIQNAPEQACLLAKQAFDDAIAELDTLNEDSYKDSTLIMQLLRDNLTLWTSDQQDEEAGEGN"); ABORT_IF(ac_position_map.size() != 4) file.getSequences(OPENMS_GET_TEST_DATA_PATH("Sequest_test.fasta"), ac_position_map, found_sequences, found, not_found); ABORT_IF(ac_position_map.size() != 4) TEST_EQUAL(found.size(), 2) TEST_EQUAL(not_found.size(), 2) ABORT_IF( found.size() != 2 || not_found.size() != 2 ) TEST_EQUAL(String("P68509"), found[0].first) TEST_EQUAL(ac_position_map["P68509"], found[0].second) TEST_EQUAL(sequences[ac_position_map["P68509"]], found_sequences[0]) TEST_EQUAL(String("Q9CQV8"), found[1].first) TEST_EQUAL(ac_position_map["Q9CQV8"], found[1].second) TEST_EQUAL(sequences[ac_position_map["Q9CQV8"]], found_sequences[1]) // create a copy as getSequences() does some weird things with the actual map map< String, Size > ac_position_map_subset = not_found; file.getSequences(OPENMS_GET_TEST_DATA_PATH("Sequest_test2.fasta"), ac_position_map_subset, found_sequences, found, not_found); TEST_EQUAL(found.size(), 4) TEST_EQUAL(not_found.size(), 0) ABORT_IF(found.size() != 4 || !not_found.empty()) TEST_EQUAL(String("P02666"), found[2].first) TEST_EQUAL(ac_position_map["P02666"], found[2].second) TEST_EQUAL(sequences[ac_position_map["P02666"]], found_sequences[2]) TEST_EQUAL(String("Q5EEQ7"), found[3].first) TEST_EQUAL(ac_position_map["Q5EEQ7"], found[3].second) TEST_EQUAL(sequences[ac_position_map["Q5EEQ7"]], found_sequences[3]) END_SECTION START_SECTION(void getACAndACType(String line, String& accession, String& accession_type)) String accession, accession_type; file.getACAndACType(">sp|P02666|CASB_BOVIN Beta-casein precursor - Bos taurus (Bovine).", accession, accession_type); TEST_STRING_EQUAL(accession, "P02666") TEST_STRING_EQUAL(accession_type, "SwissProt") file.getACAndACType(">tr|Q5EEQ7|Q5EEQ7_BOVIN Beta-casein (Fragment) - Bos taurus (Bovine).", accession, accession_type); TEST_STRING_EQUAL(accession, "Q5EEQ7") TEST_STRING_EQUAL(accession_type, "SwissProt") file.getACAndACType("gi|110174602|gb|DQ660451.1|", accession, accession_type); TEST_STRING_EQUAL("DQ660451.1", accession) TEST_STRING_EQUAL("GenBank", accession_type) file.getACAndACType("gi|1655698|emb|Y07752|VCPHEROPH", accession, accession_type); TEST_STRING_EQUAL(accession, "Y07752") TEST_STRING_EQUAL(accession_type, "EMBL") file.getACAndACType("gi|10038695|dbj|BAB12730|", accession, accession_type); TEST_STRING_EQUAL(accession, "BAB12730") TEST_STRING_EQUAL(accession_type, "DDBJ") file.getACAndACType("gi|9628804|ref|NP_043835|", accession, accession_type); TEST_STRING_EQUAL(accession, "NP_043835") TEST_STRING_EQUAL(accession_type, "NCBI") file.getACAndACType("gi|21362794|sp|P58858.0|", accession, accession_type); TEST_STRING_EQUAL(accession, "P58858.0") TEST_STRING_EQUAL(accession_type, "SwissProt") file.getACAndACType("gi|21362794|tr|P58858.0|", accession, accession_type); TEST_STRING_EQUAL(accession, "P58858.0") TEST_STRING_EQUAL(accession_type, "SwissProt") file.getACAndACType("gi|1619818|gnl|PID|d1013471|", accession, accession_type); TEST_STRING_EQUAL(accession, "d1013471") TEST_STRING_EQUAL(accession_type, "PID") file.getACAndACType("Q30DX2 Gamma-gliadin/LMW-glutenin chimera Ch7 (Fragment).", accession, accession_type); TEST_STRING_EQUAL(accession, "Q30DX2") TEST_STRING_EQUAL(accession_type, "SwissProt") file.getACAndACType(">P68509|1433F_BOVIN", accession, accession_type); TEST_STRING_EQUAL(accession, "P68509") TEST_STRING_EQUAL(accession_type, "SwissProt") file.getACAndACType(">ACBLA (P68509) F_BOVIN", accession, accession_type); TEST_STRING_EQUAL(accession, "P68509") TEST_STRING_EQUAL(accession_type, "SwissProt") END_SECTION START_SECTION(void readOutHeader(const String& result_filename, DateTime& datetime, double& precursor_mz_value, Int& charge, Size& precursor_mass_type, Size& ion_mass_type, Size& displayed_peptides, String& sequest, String& sequest_version, String& database_type, Int& number_column, Int& rank_sp_column, Int& id_column, Int& mh_column, Int& delta_cn_column, Int& xcorr_column, Int& sp_column, Int& sf_column, Int& ions_column, Int& reference_column, Int& peptide_column, Int& score_column, Size& number_of_columns)) String result_filename = OPENMS_GET_TEST_DATA_PATH("Sequest.mzXML.13.1.d.out"); DateTime datetime; double precursor_mz_value(0.0); Int charge(-1), number_column(-1), rank_sp_column(-1), id_column(-1), mh_column(-1), delta_cn_column(-1), xcorr_column(-1), sp_column(-1), sf_column(-1), ions_column(-1), reference_column(-1), peptide_column(-1), score_column(-1); Size precursor_mass_type(0), ion_mass_type(0), displayed_peptides(0), number_of_columns(0); String sequest, sequest_version, database_type; // test exceptions TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.readOutHeader("a", datetime, precursor_mz_value, charge, precursor_mass_type, ion_mass_type, displayed_peptides, sequest, sequest_version, database_type, number_column, rank_sp_column, id_column, mh_column, delta_cn_column, xcorr_column, sp_column, sf_column, ions_column, reference_column, peptide_column, score_column, number_of_columns), "the file 'a' could not be found") TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.readOutHeader(OPENMS_GET_TEST_DATA_PATH("SequestOutfile_headerfile.txt"), datetime, precursor_mz_value, charge, precursor_mass_type, ion_mass_type, displayed_peptides, sequest, sequest_version, database_type, number_column, rank_sp_column, id_column, mh_column, delta_cn_column, xcorr_column, sp_column, sf_column, ions_column, reference_column, peptide_column, score_column, number_of_columns), OPENMS_GET_TEST_DATA_PATH_MESSAGE("","SequestOutfile_headerfile.txt", " in: No Sequest version found!")) // test the actual program file.readOutHeader(result_filename, datetime, precursor_mz_value, charge, precursor_mass_type, ion_mass_type, displayed_peptides, sequest, sequest_version, database_type, number_column, rank_sp_column, id_column, mh_column, delta_cn_column, xcorr_column, sp_column, sf_column, ions_column, reference_column, peptide_column, score_column, number_of_columns); TOLERANCE_ABSOLUTE(0.0001) TEST_REAL_SIMILAR(precursor_mz_value, 866.606) TEST_STRING_EQUAL(sequest, "TurboSEQUEST") TEST_STRING_EQUAL(sequest_version, "v.27 (rev. 12)") TEST_STRING_EQUAL(database_type, "amino acids") TEST_STRING_EQUAL(datetime.get(), "2007-01-17 17:29:00") TEST_EQUAL(charge, 2) TEST_EQUAL(number_column, 0) TEST_EQUAL(rank_sp_column, 1) TEST_EQUAL(id_column, 2) TEST_EQUAL(mh_column, 3) TEST_EQUAL(delta_cn_column, 4) TEST_EQUAL(xcorr_column, 5) TEST_EQUAL(sp_column, 6) TEST_EQUAL(sf_column, 7) TEST_EQUAL(ions_column, 9) TEST_EQUAL(reference_column, 10) TEST_EQUAL(peptide_column, 11) TEST_EQUAL(score_column, 7) TEST_EQUAL(number_of_columns, 12) TEST_EQUAL(precursor_mass_type, 0) TEST_EQUAL(ion_mass_type, 0) TEST_EQUAL(displayed_peptides, 2) END_SECTION END_TEST
C++