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/MultiplexDeltaMasses_test.cpp
.cpp
1,255
39
// 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/MultiplexDeltaMasses.h> using namespace OpenMS; START_TEST(MultiplexDeltaMasses, "$Id$") MultiplexDeltaMasses* nullPointer = nullptr; MultiplexDeltaMasses* ptr; START_SECTION(MultiplexDeltaMasses()) MultiplexDeltaMasses pattern; TEST_EQUAL(pattern.getDeltaMasses().size(), 0); ptr = new MultiplexDeltaMasses(); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION MultiplexDeltaMasses pattern; pattern.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(0, "no_label")); pattern.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(6.031817, "Arg6")); START_SECTION(std::vector<DeltaMass>& getDeltaMasses()) TEST_REAL_SIMILAR(pattern.getDeltaMasses()[0].delta_mass, 0); TEST_REAL_SIMILAR(pattern.getDeltaMasses()[1].delta_mass, 6.031817); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TMTSixPlexQuantitationMethod_test.cpp
.cpp
5,694
185
// 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/TMTSixPlexQuantitationMethod.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/Matrix.h> using namespace OpenMS; using namespace std; START_TEST(TMTSixPlexQuantitationMethod, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TMTSixPlexQuantitationMethod* ptr = nullptr; TMTSixPlexQuantitationMethod* null_ptr = nullptr; START_SECTION(TMTSixPlexQuantitationMethod()) { ptr = new TMTSixPlexQuantitationMethod(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~TMTSixPlexQuantitationMethod()) { delete ptr; } END_SECTION START_SECTION((const String& getMethodName() const )) { TMTSixPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getMethodName(), "tmt6plex") } END_SECTION START_SECTION((const IsobaricChannelList& getChannelInformation() const )) { TMTSixPlexQuantitationMethod quant_meth; IsobaricQuantitationMethod::IsobaricChannelList channel_list = quant_meth.getChannelInformation(); TEST_EQUAL(channel_list.size(), 6) ABORT_IF(channel_list.size() != 6) // 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, "") TEST_STRING_EQUAL(channel_list[4].description, "") TEST_STRING_EQUAL(channel_list[5].description, "") // check masses&co TEST_EQUAL(channel_list[0].name, 126) TEST_EQUAL(channel_list[0].id, 0) TEST_EQUAL(channel_list[0].center, 126.127725) TEST_EQUAL(channel_list[1].name, 127) TEST_EQUAL(channel_list[1].id, 1) TEST_EQUAL(channel_list[1].center, 127.124760) TEST_EQUAL(channel_list[2].name, 128) TEST_EQUAL(channel_list[2].id, 2) TEST_EQUAL(channel_list[2].center, 128.134433) TEST_EQUAL(channel_list[3].name, 129) TEST_EQUAL(channel_list[3].id, 3) TEST_EQUAL(channel_list[3].center, 129.131468) TEST_EQUAL(channel_list[4].name, 130) TEST_EQUAL(channel_list[4].id, 4) TEST_EQUAL(channel_list[4].center, 130.141141) TEST_EQUAL(channel_list[5].name, 131) TEST_EQUAL(channel_list[5].id, 5) TEST_EQUAL(channel_list[5].center, 131.138176) } END_SECTION START_SECTION((Size getNumberOfChannels() const )) { TMTSixPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getNumberOfChannels(), 6) } END_SECTION START_SECTION((virtual Matrix<double> getIsotopeCorrectionMatrix() const )) { TMTSixPlexQuantitationMethod quant_meth; Matrix<double> m = quant_meth.getIsotopeCorrectionMatrix(); TEST_EQUAL(m.rows(), 6) TEST_EQUAL(m.cols(), 6) ABORT_IF(m.rows() != 6) ABORT_IF(m.cols() != 6) /** 0.9390 0.0050 0 0 0 0 0.0610 0.9280 0.0110 0 0 0 0 0.0670 0.9470 0.0170 0 0 0 0 0.0420 0.9420 0.0160 0.0020 0 0 0 0.0410 0.9630 0.0320 0 0 0 0 0.0210 0.9380 */ double real_m[6][6] = {{0.939, 0.0050, 0, 0,0 ,0}, {0.0610, 0.928, 0.0110, 0, 0 ,0}, {0, 0.0670, 0.947, 0.0170,0,0}, {0, 0, 0.0420, 0.942, 0.0160, 0.0020}, {0, 0, 0, 0.0410,0.963,0.0320}, {0, 0, 0, 0, 0.0210, 0.938} }; for (Size i = 0; i < m.rows(); ++i) { for (Size j = 0; j < m.cols(); ++j) { if (i == j) { TEST_TRUE(m(i,j) > 0.5) } // diagonal entries should be largest else { TEST_TRUE(m(i,j) < 0.5) } } } } END_SECTION START_SECTION((Size getReferenceChannel() const )) { TMTSixPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getReferenceChannel(), 0) Param p; p.setValue("reference_channel",128); quant_meth.setParameters(p); TEST_EQUAL(quant_meth.getReferenceChannel(), 2) } END_SECTION START_SECTION((TMTSixPlexQuantitationMethod(const TMTSixPlexQuantitationMethod &other))) { TMTSixPlexQuantitationMethod qm; Param p = qm.getParameters(); p.setValue("channel_127_description", "new_description"); p.setValue("reference_channel", 129); qm.setParameters(p); TMTSixPlexQuantitationMethod qm2(qm); IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation(); TEST_STRING_EQUAL(channel_list[1].description, "new_description") TEST_EQUAL(qm2.getReferenceChannel(), 3) } END_SECTION START_SECTION((TMTSixPlexQuantitationMethod& operator=(const TMTSixPlexQuantitationMethod &rhs))) { TMTSixPlexQuantitationMethod qm; Param p = qm.getParameters(); p.setValue("channel_127_description", "new_description"); p.setValue("reference_channel", 129); qm.setParameters(p); TMTSixPlexQuantitationMethod qm2 = qm; IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation(); TEST_STRING_EQUAL(channel_list[1].description, "new_description") TEST_EQUAL(qm2.getReferenceChannel(), 3) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ToolHandler_test.cpp
.cpp
2,512
86
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/APPLICATIONS/ToolHandler.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ToolHandler, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ToolHandler* ptr = nullptr; ToolHandler* null_ptr = nullptr; START_SECTION(ToolHandler()) { ptr = new ToolHandler(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~ToolHandler()) { delete ptr; } END_SECTION START_SECTION((static ToolListType getTOPPToolList(const bool includeGenericWrapper=false))) { ToolListType list = ToolHandler::getTOPPToolList(); TEST_TRUE(list.find("DecoyDatabase") != list.end()) TEST_FALSE(list.find("GenericWrapper") != list.end()) TEST_TRUE(list.size() > 30) // assume we have over 30 tools in there list = ToolHandler::getTOPPToolList(true); TEST_TRUE(list.find("DecoyDatabase") != list.end()) TEST_TRUE(list.find("GenericWrapper") != list.end()) TEST_TRUE(list.size() > 30) // assume we have over 30 tools in there #ifdef WITH_GUI TEST_TRUE(list.find("ImageCreator") != list.end()) #else TEST_TRUE(list.find("ImageCreator") == list.end()) #endif } END_SECTION START_SECTION((static StringList getTypes(const String &toolname))) { TEST_EQUAL(ToolHandler::getTypes("IsobaricAnalyzer").empty(), true); TEST_EQUAL(ToolHandler::getTypes("IDMapper").empty(), true); } END_SECTION START_SECTION((static String getExternalToolsPath())) { TEST_NOT_EQUAL(ToolHandler::getExternalToolsPath(), String()) } END_SECTION START_SECTION((static String getInternalToolsPath())) { TEST_NOT_EQUAL(ToolHandler::getExternalToolsPath(), String()) } END_SECTION START_SECTION((static String getCategory(const String &toolname))) { TEST_EQUAL(ToolHandler::getCategory("IDFilter"), "File Filtering, Extraction and Merging") TEST_EQUAL(ToolHandler::getCategory("DOESNOTEXIST"), "") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Multithreading_test.cpp
.cpp
1,818
83
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Julianus Pfeuffer $ // $Authors: Julianus Pfeuffer $ // -------------------------------------------------------------------------- /** 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> // OpenMP support #ifdef _OPENMP #include <omp.h> #endif #include <climits> /////////////////////////// using namespace OpenMS; //using namespace Logger; using namespace std; START_TEST(Multithreading, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION((OpenMP test)) { int wanted_threads = 1; int threads = 1; #ifdef _OPENMP wanted_threads = 2; omp_set_dynamic(0); // Explicitly disable dynamic teams // Use 2 threads for all consecutive parallel regions omp_set_num_threads(wanted_threads); threads = omp_get_max_threads(); #endif int max = INT_MIN; int i = 0; #pragma omp parallel private(i) { int maxi = INT_MIN; #pragma omp for for (i = 0; i < 10; i++) { #ifdef _OPENMP int threadnum = omp_get_thread_num() + 1; #else int threadnum = 1; #endif if (threadnum > maxi) maxi = threadnum; } #pragma omp critical { if (maxi > max) max = maxi; } } TEST_EQUAL(threads, wanted_threads) TEST_EQUAL(max, wanted_threads) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PepNovoInfile_test.cpp
.cpp
3,508
114
// 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/PepNovoInfile.h> #include <iostream> #include <vector> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(PepNovoInfile, "$Id$") ///////////////////////////////////////////////////////////// PepNovoInfile* ptr = nullptr; PepNovoInfile* nullPointer = nullptr; START_SECTION(PepNovoInfile()) ptr = new PepNovoInfile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~PepNovoInfile()) delete ptr; END_SECTION StringList fix_mods, var_mods; map<String,String>keys_and_mods; fix_mods.push_back("Phospho (C)"); var_mods.push_back("Phospho (D)"); var_mods.push_back("Ethanolamine (C-term)"); //var_mods.push_back("TMT6plex (N-term)"); START_SECTION((bool operator==(const PepNovoInfile &pepnovo_infile) const)) PepNovoInfile pepnovo_infile1; pepnovo_infile1.setModifications(fix_mods, var_mods); PepNovoInfile pepnovo_infile2; pepnovo_infile2 = pepnovo_infile1; TEST_EQUAL(( pepnovo_infile1 == pepnovo_infile2 ), true) END_SECTION START_SECTION((PepNovoInfile& operator=(const PepNovoInfile& pepnovo_infile))) PepNovoInfile pepnovo_infile1; pepnovo_infile1.setModifications(fix_mods, var_mods); PepNovoInfile pepnovo_infile2; pepnovo_infile2 = pepnovo_infile1; TEST_EQUAL(( pepnovo_infile1 == pepnovo_infile2 ), true) END_SECTION START_SECTION((PepNovoInfile(const PepNovoInfile &pepnovo_infile))) PepNovoInfile pepnovo_infile1; pepnovo_infile1.setModifications(fix_mods, var_mods); PepNovoInfile pepnovo_infile2; pepnovo_infile2 = pepnovo_infile1; TEST_EQUAL(( pepnovo_infile1 == pepnovo_infile2 ), true) END_SECTION START_SECTION((void setModifications(const StringList &fixed_mods, const StringList &variable_mods))) NOT_TESTABLE // will be tested in next section END_SECTION START_SECTION(void getModifications(std::map<String,String>& modification_key_map) const) PepNovoInfile pepnovo_infile; pepnovo_infile.setModifications(fix_mods, var_mods); pepnovo_infile.getModifications(keys_and_mods); //TEST_EQUAL(keys_and_mods.size(), 4) TEST_EQUAL(keys_and_mods.size(), 3) if(keys_and_mods.size()==4) { map<String, String>::iterator mod_it=keys_and_mods.begin(); TEST_EQUAL((mod_it++)->first, "$+43") TEST_EQUAL((mod_it++)->first, "C+80") TEST_EQUAL((mod_it++)->first, "D+80") // TEST_EQUAL((mod_it)->first, "^+229") } END_SECTION START_SECTION(void store(const String& filename)) PepNovoInfile pepnovo_infile; pepnovo_infile.setModifications(fix_mods, var_mods); String filename; NEW_TMP_FILE(filename) // test actual program pepnovo_infile.store(filename); // pepnovo_infile.store("test_infile.txt"); TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("PepNovoInfile_test_template.txt")); // if the comparison fails because the unimod.xml has been replaced, remove non-ascii characters // from the unimod.xml file. E.g. registrated trademark symbol END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MorpheusScore_test.cpp
.cpp
3,686
107
// 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/ANALYSIS/ID/MorpheusScore.h> /////////////////////////// #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> using namespace OpenMS; using namespace std; START_TEST(MorpheusScore, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MorpheusScore* ptr = 0; MorpheusScore* null_ptr = 0; TheoreticalSpectrumGenerator tsg; Param param = tsg.getParameters(); param.setValue("add_metainfo", "true"); tsg.setParameters(param); START_SECTION(MorpheusScore()) { ptr = new MorpheusScore(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~MorpheusScore()) { delete ptr; } END_SECTION START_SECTION((static MorpheusScore::Result compute( double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm, const PeakSpectrum &exp_spectrum, const PeakSpectrum &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(MorpheusScore::compute(0.1, false, exp_spectrum, theo_spectrum).score, 0.0); // full match, 11 identical masses, identical intensities (=1). Total score is number of matches (11) + fraction of TIC (=1) tsg.getSpectrum(exp_spectrum, peptide, 1, 1); TEST_EQUAL(exp_spectrum.size(), 11); TEST_EQUAL(theo_spectrum.size(), 11); TEST_REAL_SIMILAR(MorpheusScore::compute(0.1, false, exp_spectrum, theo_spectrum).score, 11.0 + 1.0); TEST_REAL_SIMILAR(MorpheusScore::compute(10, true, exp_spectrum, theo_spectrum).score, 11.0 + 1.0); exp_spectrum.clear(true); theo_spectrum.clear(true); // no match tsg.getSpectrum(exp_spectrum, peptide, 1, 1); tsg.getSpectrum(theo_spectrum, AASequence::fromString("EDITPEP"), 1, 1); TEST_REAL_SIMILAR(MorpheusScore::compute(1e-5, false, exp_spectrum, theo_spectrum).score, 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(MorpheusScore::compute(0.1, false, exp_spectrum, theo_spectrum).score, 33.0 + 1.0); TEST_REAL_SIMILAR(MorpheusScore::compute(10, true, exp_spectrum, theo_spectrum).score, 33.0 + 1.0); // 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_EQUAL(MorpheusScore::compute(0.1, false, exp_spectrum, theo_spectrum).matches, 4); TEST_REAL_SIMILAR(MorpheusScore::compute(0.1, false, exp_spectrum, theo_spectrum).score, 4.1212); TEST_EQUAL(MorpheusScore::compute(10, true, exp_spectrum, theo_spectrum).matches, 33); TEST_REAL_SIMILAR(MorpheusScore::compute(10, true, exp_spectrum, theo_spectrum).score, 33.0 + 1.0); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FragmentIndex_test.cpp
.cpp
17,778
429
// Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Raphael Förster $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////////// #include <OpenMS/ANALYSIS/ID/FragmentIndex.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/CHEMISTRY/ModifiedPeptideGenerator.h> #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> #include <OpenMS/CONCEPT/Constants.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/FORMAT/FASTAFile.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/Peak1D.h> #include <limits> /* FragmentIndex tests This suite verifies: - build(): digestion and peptide generation across enzyme, length/mass limits, missed cleavages, and modifications; asserts ordering invariants for peptides/fragments. - clear(): resets index state. - querySpectrum(): candidate generation across precursor charges with and without known precursor charge. - isotope_error: precursor m/z isotope offsets map to expected peptide subsequences. - tolerance: fragment and precursor tolerance handling using small deterministic m/z jitter. Invariants validated by helper methods: - Peptides are sorted by precursor_mz_ (non-decreasing). - Fragments are bucketed and within each bucket sorted by peptide_idx_. */ using namespace OpenMS; using namespace std; // Helper test subclass exposing internal invariants (fi_peptides_, fi_fragments_, bucketsize_). // Only used in tests to assert ordering and to craft white-box expectations. class FragmentIndex_test : public FragmentIndex { public: // Verifies that the generated peptide set matches the expected set exactly // (by subsequence window and modification index). bool testDigestion(const std::vector<FragmentIndex::Peptide>& expected) { if (expected.size() != fi_peptides_.size()) return false; for (const auto& exp : expected) { bool found = false; for (const auto& act : fi_peptides_) { if ((exp.sequence_ == act.sequence_) && (exp.modification_idx_ == act.modification_idx_)) { found = true; break; } } if (! found) return false; } return true; } // Checks non-decreasing order of precursor_mz_ across all peptides (invariant of build()). bool peptidesSorted() { float last_mz = std::numeric_limits<float>::lowest(); for (const auto& pep : fi_peptides_) { if (pep.precursor_mz_ >= last_mz) { last_mz = pep.precursor_mz_; } else { return false; } } return true; } // Validates that within each fragment bucket, peptide_idx_ is non-decreasing. // This captures the two-dimensional ordering constraint of the index. bool fragmentsSorted() { for (size_t fi_idx = 0; fi_idx < fi_fragments_.size(); fi_idx += bucketsize_) { UInt32 last_idx = 0; const size_t end = (fi_idx + bucketsize_ > fi_fragments_.size()) ? fi_fragments_.size() : (fi_idx + bucketsize_); for (size_t bucket_idx = fi_idx; bucket_idx < end; ++bucket_idx) { if (fi_fragments_[bucket_idx].peptide_idx_ < last_idx) return false; last_idx = fi_fragments_[bucket_idx].peptide_idx_; } } return true; } bool testQuery(const UInt32 charge, const bool precursor_mz_known, const std::vector<FASTAFile::FASTAEntry>& entries) { // fetch parameters for modification generation auto params = getParameters(); const StringList modifications_fixed_ = ListUtils::toStringList<std::string>(params.getValue("modifications:fixed")); const StringList modifications_variable_ = ListUtils::toStringList<std::string>(params.getValue("modifications:variable")); const ModifiedPeptideGenerator::MapToResidueType fixed_modifications = ModifiedPeptideGenerator::getModifications(modifications_fixed_); const ModifiedPeptideGenerator::MapToResidueType variable_modifications = ModifiedPeptideGenerator::getModifications(modifications_variable_); // Create theoretical spectra for different charges TheoreticalSpectrumGenerator tsg; std::vector<AASequence> mod_peptides; PeakSpectrum b_y_ions; MSSpectrum spec_theo; Precursor prec_theo; const std::vector<FragmentIndex::Peptide>& peptides = getPeptides(); bool test = true; // Create different ms/ms spectra with different charges size_t peptide_idx = 0; // use size_t to match SpectrumMatch::peptide_idx_ type // For each peptide that was created, we now generate a theoretical spectra for the given charge // Each peptide should hit its own entry in the db. In this case the test returns true for (const auto& pep : peptides) { FragmentIndex::SpectrumMatchesTopN sms; b_y_ions.clear(true); mod_peptides.clear(); spec_theo.clear(true); prec_theo.clearMetaInfo(); const AASequence unmod_peptide = AASequence::fromString(entries[0].sequence.substr(pep.sequence_.first, pep.sequence_.second)); AASequence mod_peptide = AASequence(unmod_peptide); // copy the peptide ModifiedPeptideGenerator::applyFixedModifications(fixed_modifications, mod_peptide); ModifiedPeptideGenerator::applyVariableModifications(variable_modifications, mod_peptide, params.getValue("modifications:variable_max_per_peptide"), mod_peptides); mod_peptide = mod_peptides[pep.modification_idx_]; tsg.getSpectrum(b_y_ions, mod_peptide, charge, charge); prec_theo.setMZ(mod_peptide.getMZ(charge)); if (precursor_mz_known) { prec_theo.setCharge(charge); } spec_theo.setMSLevel(2); spec_theo.setPrecursors({prec_theo}); for (const auto& ion : b_y_ions) { spec_theo.push_back(ion); } querySpectrum(spec_theo, sms); bool found = false; // iterate candidates and check matching count for the exact peptide/charge for (const auto& s : sms.hits_) { if ((s.peptide_idx_ == peptide_idx) && (s.precursor_charge_ == charge)) { // All generated peaks must be matched and the correct precursor charge identified found = (s.num_matched_ >= spec_theo.size()); } } test = test && found; peptide_idx++; } return test; } }; ////////////////////////////// START_TEST(FragmentIndex, "$Id") ////////////////////////////// /// Test the build for peptides START_SECTION(build()) { // Test proteins used to generate expected peptides for multiple parameterizations /* Format of expected peptide descriptors below and their mapping to FragmentIndex::Peptide fields: { protein_idx, modification_idx_, { start, length }, precursor_mz_ } Where: - protein_idx: 0-based index into the FASTA entries vector passed to build(); selects the source protein. - modification_idx_: index into mod_peptides returned by ModifiedPeptideGenerator for the given unmodified subsequence (0 = unmodified; higher values enumerate concrete variable-mod combinations). - start: 0-based start offset within the selected protein sequence. - length: number of residues for the peptide (used as std::string::substr(start, length)). - precursor_mz_: mono-isotopic m/z at charge 1 (M+H)+. In these tests we often use a dummy value, as only ordering invariants on peptides/fragment buckets are asserted. Note: testDigestion() compares expected vs. built peptides only by {sequence_, modification_idx_}. */ const std::vector<FASTAFile::FASTAEntry> entries0 {{"t", "t", "ARGEPADSSRKDFDMDMDM"}, {"t2", "t2", "HALLORTSCHSM"}}; // Expected peptides when enabling fixed Carbamidomethyl (C) and variable Oxidation (M) std::vector<FragmentIndex::Peptide> peptides_we_should_hit_mod {{0, 0, {2, 8}, 5}, {0, 0, {11, 8}, 5}, {0, 1, {11, 8}, 5}, {0, 2, {11, 8}, 5}, {0, 3, {11, 8}, 5}, {0, 4, {11, 8}, 5}, {0, 5, {11, 8}, 5}, {0, 6, {11, 8}, 5}, {1, 0, {0, 6}, 5}, {1, 0, {6, 6}, 5}, {1, 1, {6, 6}, 5} }; // Expected peptides without min/max size constraints (no missed cleavages, no modifications) std::vector<FragmentIndex::Peptide> peptides_unmod_no_minmax {{0, 0, {0, 2}, 5}, {0, 0, {2, 8}, 5}, {0, 0, {10, 1}, 5}, {0, 0, {11, 8}, 5}, {1, 0, {0, 6}, 5}, {1, 0, {6, 6}, 5}}; // Expected peptides with size in [min_size, max_size] only std::vector<FragmentIndex::Peptide> peptides_unmod_minmax {{0, 0, {0, 2}, 5}, {1, 0, {0, 6}, 5}, {1, 0, {6, 6}, 5}}; // Expected peptides with one missed cleavage allowed std::vector<FragmentIndex::Peptide> peptides_unmod_minmax_missed_cleavage {{0, 0, {0, 2}, 5}, {0, 0, {2, 8}, 5}, {0, 0, {11, 8}, 5}, {0, 0, {0, 10}, 5}, {0, 0, {2, 9}, 5}, {0, 0, {10, 9}, 5}, {1, 0, {0, 6}, 5}, {1, 0, {6, 6}, 5}, {1, 0, {0, 12}, 5}}; FragmentIndex_test buildTest; auto params = buildTest.getParameters(); params.setValue("enzyme", "Trypsin"); params.setValue("peptide:missed_cleavages", 0); params.setValue("peptide:min_mass", 0); params.setValue("peptide:min_size", 0); params.setValue("peptide:max_mass", 5000); params.setValue("modifications:variable", std::vector<std::string> {}); params.setValue("modifications:fixed", std::vector<std::string> {}); buildTest.setParameters(params); buildTest.build(entries0); TEST_TRUE(buildTest.testDigestion(peptides_unmod_no_minmax)) TEST_TRUE(buildTest.peptidesSorted()) TEST_TRUE(buildTest.fragmentsSorted()) buildTest.clear(); params.setValue("peptide:min_size", 2); params.setValue("peptide:max_size", 6); buildTest.setParameters(params); buildTest.build(entries0); TEST_TRUE(buildTest.testDigestion(peptides_unmod_minmax)) TEST_TRUE(buildTest.peptidesSorted()) TEST_TRUE(buildTest.fragmentsSorted()) buildTest.clear(); params.setValue("peptide:max_size", 100); params.setValue("peptide:missed_cleavages", 1); buildTest.setParameters(params); buildTest.build(entries0); TEST_TRUE(buildTest.testDigestion(peptides_unmod_minmax_missed_cleavage)) TEST_TRUE(buildTest.peptidesSorted()) TEST_TRUE(buildTest.fragmentsSorted()) buildTest.clear(); params.setValue("enzyme", "Trypsin"); params.setValue("peptide:missed_cleavages", 0); params.setValue("peptide:min_mass", 0); params.setValue("peptide:min_size", 6); params.setValue("modifications:variable", std::vector<std::string> {"Oxidation (M)"}); params.setValue("modifications:fixed", std::vector<std::string> {"Carbamidomethyl (C)"}); buildTest.setParameters(params); buildTest.build(entries0); TEST_TRUE(buildTest.testDigestion(peptides_we_should_hit_mod)) TEST_TRUE(buildTest.peptidesSorted()) TEST_TRUE(buildTest.fragmentsSorted()) } END_SECTION // Verify that clear() resets the internal peptide container. START_SECTION(clear()) { const std::vector<FASTAFile::FASTAEntry> entries0 {{"t", "t", "ARGEPADSSRKDFDMDMDM"}, {"t2", "t2", "HALLORTSCHS"}}; FragmentIndex clearTest; clearTest.build(entries0); clearTest.clear(); TEST_TRUE(clearTest.getPeptides().empty()) } END_SECTION ////TEST Different Charges of the query Spectrum //// // For each charge (1..4), a peptide's own theoretical spectrum should self-hit, // with and without explicitly setting the precursor charge. START_SECTION(void querySpectrum(const MSSpectrum& spectrum, SpectrumMatchesTopN& sms)) { const std::vector<FASTAFile::FASTAEntry> entries { {"test1", "test1", "MSDEREVAEAATGEDASSPPPKTEAASDPQHPAASEGAAAAAASPPLLRCLVLTGFGGYDKVKLQSRPAAPPAPGPGQLTLRLRACGLNFADLMARQGLYDRLPPLPVTPGMEGAGVVIAVGEGVSDRKAGDRVMVLNRSGMWQE" "EVTVPSVQTFLIPEAMTFEEAAALLVNYITAYMVLFDFGNLQPGHSVLVHMAAGGVGMAAVQLCRTVENVTVFGTASASKHEALKENGVTHPIDYHTTDYVDEIKKISPKGVDIVMDPLGGSDTAKGYNLLKPMGKVVTYGMANL" "LTGPKRNLMALARTWWNQFSVTALQLLQANRAVCGFHLGYLDGEVELVSGVVARLLALYNQGHIKPHIDSVWPFEKVADAMKQMQEKKNVGKVLLVPGPEKEN"}}; FragmentIndex_test queryTest; auto params = queryTest.getParameters(); params.setValue("fragment:max_charge", 4); params.setValue("precursor:min_charge", 1); params.setValue("precursor:max_charge", 4); params.setValue("fragment:min_mz", 0); // ensure all peptides/fragments are generated for exhaustive self-hit checks params.setValue("fragment:max_mz", 5000000); queryTest.setParameters(params); queryTest.build(entries); // Create different ms/ms spectra with different charges for (uint16_t charge = 1; charge <= 4; ++charge) { TEST_TRUE(queryTest.testQuery(charge, false, entries)) TEST_TRUE(queryTest.testQuery(charge, true, entries)) } } END_SECTION // Shift the precursor by integer isotope errors [-3..3] and expect stable peptide window mapping. START_SECTION(isotope_error) { const std::vector<FASTAFile::FASTAEntry> entries { {"test1", "test1", "MSDEREVAEAATGEDASSPPPKTEAASDPQHPAASEGAAAAAASPPLLRCLVLTGFGGYDKVKLQSRPAAPPAPGPGQLTLRLRACGLNFADLMARQGLYDRLPPLPVTPGMEGAGVVIAVGEGVSDRKAGDRVMVLNRSGMWQE" "EVTVPSVQTFLIPEAMTFEEAAALLVNYITAYMVLFDFGNLQPGHSVLVHMAAGGVGMAAVQLCRTVENVTVFGTASASKHEALKENGVTHPIDYHTTDYVDEIKKISPKGVDIVMDPLGGSDTAKGYNLLKPMGKVVTYGMANL" "LTGPKRNLMALARTWWNQFSVTALQLLQANRAVCGFHLGYLDGEVELVSGVVARLLALYNQGHIKPHIDSVWPFEKVADAMKQMQEKKNVGKVLLVPGPEKEN"}}; FragmentIndex_test isoTest; // Configure parameters before building the index (isotope error and fragment m/z bounds) auto params = isoTest.getParameters(); params.setValue("precursor:isotope_error_min", -3); params.setValue("precursor:isotope_error_max", 3); params.setValue("fragment:min_mz", 0); params.setValue("fragment:max_mz", 90000); params.setValue("modifications:variable", std::vector<std::string> {}); params.setValue("modifications:fixed", std::vector<std::string> {}); isoTest.setParameters(params); // build after parameterization isoTest.build(entries); TheoreticalSpectrumGenerator tsg; PeakSpectrum b_y_ions; AASequence peptide = AASequence::fromString("EVAEAATGEDASSPPPK"); tsg.getSpectrum(b_y_ions, peptide, 1, 1); MSSpectrum theo_spec; Precursor theo_prec; theo_prec.setCharge(1); theo_spec.setMSLevel(2); for (const auto& peak : b_y_ions) { theo_spec.push_back(peak); } for (int iso = -3; iso <= 3; ++iso) { theo_prec.setMZ(peptide.getMZ(1) + iso * Constants::C13C12_MASSDIFF_U); theo_spec.setPrecursors({theo_prec}); FragmentIndex::SpectrumMatchesTopN sms; isoTest.querySpectrum(theo_spec, sms); bool found = false; for (const auto& hit : sms.hits_) { auto result = isoTest.getPeptides()[hit.peptide_idx_]; auto psize = peptide.size(); TEST_EQUAL(result.sequence_.first, 5) TEST_EQUAL(result.sequence_.second, psize) found = true; } TEST_TRUE(found); } } END_SECTION // Apply small deterministic fragment m/z jitter and a precursor offset within tolerances; // expect the correct peptide hit and zero isotope error. START_SECTION(tolerance) { const std::vector<FASTAFile::FASTAEntry> entries { {"test1", "test1", "MSDEREVAEAATGEDASSPPPKTEAASDPQHPAASEGAAAAAASPPLLRCLVLTGFGGYDKVKLQSRPAAPPAPGPGQLTLRLRACGLNFADLMARQGLYDRLPPLPVTPGMEGAGVVIAVGEGVSDRKAGDRVMVLNRSGMWQE" "EVTVPSVQTFLIPEAMTFEEAAALLVNYITAYMVLFDFGNLQPGHSVLVHMAAGGVGMAAVQLCRTVENVTVFGTASASKHEALKENGVTHPIDYHTTDYVDEIKKISPKGVDIVMDPLGGSDTAKGYNLLKPMGKVVTYGMANL" "LTGPKRNLMALARTWWNQFSVTALQLLQANRAVCGFHLGYLDGEVELVSGVVARLLALYNQGHIKPHIDSVWPFEKVADAMKQMQEKKNVGKVLLVPGPEKEN"}}; FragmentIndex_test tolTest; auto params = tolTest.getParameters(); params.setValue("fragment:min_mz", 0); params.setValue("fragment:max_mz", 90000); params.setValue("fragment:mass_tolerance", 0.05); params.setValue("fragment:mass_tolerance_unit", "Da"); params.setValue("precursor:mass_tolerance", 2.0); params.setValue("precursor:mass_tolerance_unit", "Da"); params.setValue("modifications:variable", std::vector<std::string> {}); params.setValue("modifications:fixed", std::vector<std::string> {}); tolTest.setParameters(params); tolTest.build(entries); TheoreticalSpectrumGenerator tsg; PeakSpectrum b_y_ions; AASequence peptide = AASequence::fromString("EVAEAATGEDASSPPPK"); tsg.getSpectrum(b_y_ions, peptide, 1, 1); MSSpectrum theo_spec; Precursor theo_prec; theo_prec.setCharge(1); theo_prec.setMZ(peptide.getMZ(1) + 1.9); theo_spec.setMSLevel(2); theo_spec.setPrecursors({theo_prec}); // Deterministic, small m/z jitter within ±0.045 Da to exercise tolerance handling constexpr float kJitterStep = 0.001f; constexpr int kJitterHalfWidth = 45; size_t i = 0; for (auto& peak : b_y_ions) { const float factor = (static_cast<int>(i % (2 * kJitterHalfWidth + 1)) - kJitterHalfWidth) * kJitterStep; peak.setMZ(peak.getMZ() + factor); theo_spec.push_back(peak); ++i; } FragmentIndex::SpectrumMatchesTopN sms; tolTest.querySpectrum(theo_spec, sms); bool found = false; for (const auto& hit : sms.hits_) { auto sequence = tolTest.getPeptides()[hit.peptide_idx_].sequence_; if ((sequence.first == 5) && (sequence.second == peptide.size()) && (hit.isotope_error_ == 0)) { found = true; TEST_TRUE(hit.num_matched_ >= theo_spec.size()); } } TEST_TRUE(found); } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PercolatorOutfile_test.cpp
.cpp
4,835
126
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hendrik Weisser $ // $Authors: Hendrik Weisser $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/PercolatorOutfile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(PercolatorOutfile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PercolatorOutfile* ptr = nullptr; PercolatorOutfile* null_pointer = nullptr; PercolatorOutfile file; START_SECTION(PercolatorOutfile()) { ptr = new PercolatorOutfile(); TEST_NOT_EQUAL(ptr, null_pointer); } END_SECTION START_SECTION(~PercolatorOutfile()) { delete ptr; } END_SECTION START_SECTION(ScoreType getScoreType(String score_type_name)) { TEST_EQUAL(PercolatorOutfile::getScoreType("qvalue"), PercolatorOutfile::ScoreType::QVALUE); TEST_EQUAL(PercolatorOutfile::getScoreType("q-value"), PercolatorOutfile::ScoreType::QVALUE); TEST_EQUAL(PercolatorOutfile::getScoreType("PEP"), PercolatorOutfile::ScoreType::POSTERRPROB); TEST_EQUAL(PercolatorOutfile::getScoreType("Posterior Error Probability"), PercolatorOutfile::ScoreType::POSTERRPROB); TEST_EQUAL(PercolatorOutfile::getScoreType("score"), PercolatorOutfile::ScoreType::SCORE); } END_SECTION START_SECTION(void load(const String& filename, ProteinIdentification& proteins, PeptideIdentificationList& peptides, SpectrumMetaDataLookup& lookup, ScoreType output_score)) { // mock-up raw data like those used for the search: vector<MSSpectrum> spectra(3); double rt = 2.0; for (vector<MSSpectrum>::iterator it = spectra.begin(); it != spectra.end(); ++it, rt += 1.0) { it->setMSLevel(2); it->setRT(rt); Precursor precursor; precursor.setCharge(Int(rt)); precursor.setMZ(rt * 111.1); it->getPrecursors().push_back(precursor); } SpectrumMetaDataLookup lookup; lookup.readSpectra(spectra, ""); // no native IDs set, so don't parse them String filename = OPENMS_GET_TEST_DATA_PATH("PercolatorOutfile_test.psms"); ProteinIdentification proteins; PeptideIdentificationList peptides; file.load(filename, proteins, peptides, lookup, PercolatorOutfile::ScoreType::SCORE); TEST_EQUAL(proteins.getHits().size(), 3); TEST_STRING_EQUAL(proteins.getHits()[0].getAccession(), "Protein1"); TEST_STRING_EQUAL(proteins.getHits()[1].getAccession(), "Protein2"); TEST_STRING_EQUAL(proteins.getHits()[2].getAccession(), "UniProt_P01834"); TEST_EQUAL(proteins.getSearchParameters().fixed_modifications.size(), 1); TEST_STRING_EQUAL(proteins.getSearchParameters().fixed_modifications[0], "Carbamidomethyl (C)"); TEST_EQUAL(peptides.size(), 3); TEST_REAL_SIMILAR(peptides[0].getRT(), 2.0); TEST_REAL_SIMILAR(peptides[1].getRT(), 3.0); TEST_REAL_SIMILAR(peptides[2].getRT(), 4.0); TEST_REAL_SIMILAR(peptides[0].getMZ(), 222.2); TEST_REAL_SIMILAR(peptides[1].getMZ(), 333.3); TEST_REAL_SIMILAR(peptides[2].getMZ(), 444.4); TEST_EQUAL(peptides[0].getHits().size(), 1); TEST_EQUAL(peptides[1].getHits().size(), 1); TEST_EQUAL(peptides[2].getHits().size(), 1); TEST_EQUAL(peptides[0].getHits()[0].getCharge(), 2); TEST_EQUAL(peptides[1].getHits()[0].getCharge(), 3); TEST_EQUAL(peptides[2].getHits()[0].getCharge(), 4); TEST_REAL_SIMILAR(peptides[0].getHits()[0].getScore(), 6.77991); TEST_REAL_SIMILAR(peptides[1].getHits()[0].getScore(), 6.57945); TEST_REAL_SIMILAR(peptides[2].getHits()[0].getScore(), 6.50586); TEST_STRING_EQUAL(peptides[0].getHits()[0].getSequence().toString(), "VDNALQSGNSQESVTEQDSKDSTYSLSSTLTLSK"); TEST_STRING_EQUAL(peptides[1].getHits()[0].getSequence().toString(), "VDNALQSGNSQESVTEQDSKDSTYSLSSTLTLSK"); TEST_STRING_EQUAL(peptides[2].getHits()[0].getSequence().toString(), "VTLSC(Carbamidomethyl)TGSSSNLGAGYDVHWYQQLPGTAPK"); TEST_REAL_SIMILAR(peptides[0].getHits()[0].getMetaValue("Percolator_score"), 6.77991); TEST_REAL_SIMILAR(peptides[1].getHits()[0].getMetaValue("Percolator_qvalue"), 0.0); TEST_REAL_SIMILAR(peptides[2].getHits()[0].getMetaValue("Percolator_PEP"), 1.8014e-14); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/RankScaler_test.cpp
.cpp
3,076
111
// 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, Andreas Bertsch $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/PROCESSING/SCALING/RankScaler.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/DTAFile.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(RankScaler, "$Id$") ///////////////////////////////////////////////////////////// TOLERANCE_ABSOLUTE(0.01) RankScaler* e_ptr = nullptr; RankScaler* e_nullPointer = nullptr; START_SECTION((RankScaler())) e_ptr = new RankScaler; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION((~RankScaler())) delete e_ptr; END_SECTION e_ptr = new RankScaler(); START_SECTION((RankScaler(const RankScaler& source))) RankScaler copy(*e_ptr); TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) TEST_EQUAL(copy.getName(), e_ptr->getName()) END_SECTION START_SECTION((RankScaler& operator = (const RankScaler& source))) RankScaler copy; copy = *e_ptr; TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) TEST_EQUAL(copy.getName(), e_ptr->getName()) END_SECTION START_SECTION((template<typename SpectrumType> void filterSpectrum(SpectrumType& spectrum))) DTAFile dta_file; PeakSpectrum spec; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec); e_ptr->filterSpectrum(spec); TEST_EQUAL(spec.size(), 121) spec.sortByIntensity(); TEST_REAL_SIMILAR(spec.begin()->getIntensity(), 96) TEST_REAL_SIMILAR((spec.end()-1)->getIntensity(), 121) TEST_REAL_SIMILAR((spec.end()-1)->getPosition()[0], 136.077) 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); e_ptr->filterPeakMap(pm); TEST_EQUAL(pm.begin()->size(), 121) pm.begin()->sortByIntensity(); TEST_REAL_SIMILAR(pm.begin()->begin()->getIntensity(), 96) TEST_REAL_SIMILAR((pm.begin()->end()-1)->getIntensity(), 121) TEST_REAL_SIMILAR((pm.begin()->end()-1)->getPosition()[0], 136.077) 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); e_ptr->filterPeakSpectrum(spec); TEST_EQUAL(spec.size(), 121) spec.sortByIntensity(); TEST_REAL_SIMILAR(spec.begin()->getIntensity(), 96) TEST_REAL_SIMILAR((spec.end()-1)->getIntensity(), 121) TEST_REAL_SIMILAR((spec.end()-1)->getPosition()[0], 136.077) END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DIntervalBase_test.cpp
.cpp
8,781
339
// 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/DATASTRUCTURES/DIntervalBase.h> ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace OpenMS::Internal; using namespace std; START_TEST(DIntervalBase, "$Id$") ///////////////////////////////////////////////////////////// //1D check DIntervalBase<1>* ptr1 = nullptr; DIntervalBase<1>* nullPointer1 = nullptr; START_SECTION((DIntervalBase())) ptr1 = new DIntervalBase<1>; TEST_NOT_EQUAL(ptr1, nullPointer1) END_SECTION START_SECTION((~DIntervalBase())) delete ptr1; END_SECTION //2D check DIntervalBase<2>* ptr2 = nullptr; DIntervalBase<2>* nullPointer2 = nullptr; START_SECTION([EXTRA] DIntervalBase()) ptr2 = new DIntervalBase<2>; TEST_NOT_EQUAL(ptr2, nullPointer2) END_SECTION START_SECTION([EXTRA] ~DIntervalBase()) delete ptr2; END_SECTION //misc stuff for testing typedef DIntervalBase<2> I2; typedef DIntervalBase<2>::PositionType I2Pos; I2Pos p1; p1[0]=5.0; p1[1]=17.5; I2Pos p2; p2[0]=65.0; p2[1]=-57.5; START_SECTION(DIntervalBase operator+(const PositionType& point) const) { I2 di({1, 2}, {3, 4}); I2 r = di + (I2Pos(1, 0.5)); TEST_REAL_SIMILAR(r.minX(), 2) TEST_REAL_SIMILAR(r.minY(), 2.5) TEST_REAL_SIMILAR(r.maxX(), 4) TEST_REAL_SIMILAR(r.maxY(), 4.5) } END_SECTION START_SECTION(DIntervalBase& operator+=(const PositionType& point)) { I2 di({1, 2}, {3, 4}); I2 r = di += (I2Pos(1, 0.5)); TEST_EQUAL(r, di) TEST_REAL_SIMILAR(r.minX(), 2) TEST_REAL_SIMILAR(r.minY(), 2.5) TEST_REAL_SIMILAR(r.maxX(), 4) TEST_REAL_SIMILAR(r.maxY(), 4.5) } END_SECTION START_SECTION(DIntervalBase operator-(const PositionType& point) const) { I2 di({1, 2}, {3, 4}); I2 r = di - (I2Pos(1, 0.5)); TEST_REAL_SIMILAR(r.minX(), 0) TEST_REAL_SIMILAR(r.minY(), 1.5) TEST_REAL_SIMILAR(r.maxX(), 2) TEST_REAL_SIMILAR(r.maxY(), 3.5) } END_SECTION START_SECTION(DIntervalBase& operator-=(const PositionType& point)) { I2 di({1, 2}, {3, 4}); I2 r = di -= (I2Pos(1, 0.5)); TEST_EQUAL(r, di) TEST_REAL_SIMILAR(r.minX(), 0) TEST_REAL_SIMILAR(r.minY(), 1.5) TEST_REAL_SIMILAR(r.maxX(), 2) TEST_REAL_SIMILAR(r.maxY(), 3.5) } END_SECTION START_SECTION((PositionType const& maxPosition() const)) TEST_EQUAL(I2::empty.maxPosition()==I2Pos::minNegative(), true); TEST_EQUAL(I2::zero.maxPosition()==I2Pos::zero(), true); END_SECTION START_SECTION((PositionType const& minPosition() const)) TEST_EQUAL(I2::empty.minPosition()==I2Pos::maxPositive(), true); TEST_EQUAL(I2::zero.minPosition()==I2Pos::zero(), true); END_SECTION START_SECTION((void setMinMax(PositionType const & min, PositionType const & max))) I2 tmp(I2::empty); tmp.setMinMax(p1,p2); TEST_REAL_SIMILAR(tmp.minPosition()[0],5.0); TEST_REAL_SIMILAR(tmp.minPosition()[1],-57.5); TEST_REAL_SIMILAR(tmp.maxPosition()[0],65.0); TEST_REAL_SIMILAR(tmp.maxPosition()[1],17.5); END_SECTION START_SECTION((void setMin(PositionType const & position))) I2 tmp(I2::empty); tmp.setMin(p1); TEST_EQUAL(tmp.minPosition(),p1); TEST_EQUAL(tmp.maxPosition(),p1); tmp.setMin(p2); TEST_REAL_SIMILAR(tmp.minPosition()[0],65.0); TEST_REAL_SIMILAR(tmp.minPosition()[1],-57.5); TEST_REAL_SIMILAR(tmp.maxPosition()[0],65.0); TEST_REAL_SIMILAR(tmp.maxPosition()[1],17.5); END_SECTION START_SECTION((void setMax(PositionType const & position))) I2 tmp(I2::empty); tmp.setMax(p1); TEST_EQUAL(tmp.minPosition(),p1); TEST_EQUAL(tmp.maxPosition(),p1); tmp.setMax(p2); TEST_REAL_SIMILAR(tmp.minPosition()[0],5.0); TEST_REAL_SIMILAR(tmp.minPosition()[1],-57.5); TEST_REAL_SIMILAR(tmp.maxPosition()[0],65.0); TEST_REAL_SIMILAR(tmp.maxPosition()[1],-57.5); END_SECTION START_SECTION((void setDimMinMax(UInt dim, const DIntervalBase<1>& min_max))) I2 tmp(I2::empty); auto min_p = tmp.minPosition(); auto max_p = tmp.maxPosition(); tmp.setDimMinMax(0, {1, 1.1}); min_p.setX(1); max_p.setX(1.1); TEST_EQUAL(tmp.minPosition(), min_p); TEST_EQUAL(tmp.maxPosition(), max_p); END_SECTION START_SECTION((bool operator==(const DIntervalBase &rhs) const )) I2 tmp; TEST_EQUAL(tmp==tmp,true); TEST_EQUAL(tmp==I2::empty,true); tmp.setMax(p1); TEST_EQUAL(tmp==I2::empty,false); END_SECTION START_SECTION((bool operator!=(const DIntervalBase &rhs) const )) I2 tmp; TEST_EQUAL(tmp!=tmp,false); TEST_EQUAL(tmp!=I2::empty,false); tmp.setMax(p1); TEST_EQUAL(tmp!=I2::empty,true); END_SECTION START_SECTION((DIntervalBase(const DIntervalBase& rhs))) I2 tmp(p1,p2); I2 tmp2(tmp); TEST_EQUAL(tmp==tmp2,true); END_SECTION START_SECTION((DIntervalBase( PositionType const & minimum, PositionType const & maximum ))) I2 tmp(p1,p2); I2 tmp2(tmp.minPosition(), tmp.maxPosition()); TEST_EQUAL(tmp==tmp2,true); END_SECTION START_SECTION((DIntervalBase& operator=(const DIntervalBase & rhs))) I2 tmp(p1,p2); I2 tmp2; TEST_EQUAL(tmp==tmp2,false); tmp2 = tmp; TEST_EQUAL(tmp==tmp2,true); tmp2 = tmp = I2::empty; TEST_EQUAL(tmp==tmp2,true); TEST_EQUAL(tmp==I2::empty,true); END_SECTION START_SECTION((void clear())) I2 tmp; TEST_EQUAL(tmp==I2::empty,true); tmp.setMax(p1); TEST_EQUAL(tmp==I2::empty,false); tmp.clear(); TEST_EQUAL(tmp==I2::empty,true); TEST_EQUAL(tmp.maxPosition()==I2Pos::minNegative(), true); TEST_EQUAL(tmp.minPosition()==I2Pos::maxPositive(), true); END_SECTION START_SECTION((bool isEmpty() const)) I2 tmp; TEST_TRUE(tmp.isEmpty()) tmp.setMax(p1); TEST_FALSE(tmp.isEmpty()) tmp.clear(); TEST_TRUE(tmp.isEmpty()) tmp.setDimMinMax(1, {2,2}); // set empty half-open interval (making it non-empty) TEST_FALSE(tmp.isEmpty()) END_SECTION START_SECTION((bool isEmpty(UInt dim) const)) I2 tmp; TEST_TRUE(tmp.isEmpty(0)) TEST_TRUE(tmp.isEmpty(1)) tmp.setMax(p1); TEST_FALSE(tmp.isEmpty(0)) TEST_FALSE(tmp.isEmpty(1)) tmp.clear(); TEST_TRUE(tmp.isEmpty(0)) TEST_TRUE(tmp.isEmpty(1)) tmp.setDimMinMax(1, {2,2}); // set empty half-open interval (making it non-empty) TEST_TRUE(tmp.isEmpty(0)) TEST_FALSE(tmp.isEmpty(1)) END_SECTION START_SECTION((PositionType center() const)) I2 tmp(p1,p2); I2Pos pos(tmp.center()); TEST_REAL_SIMILAR(pos[0],35.0); TEST_REAL_SIMILAR(pos[1],-20.0); END_SECTION START_SECTION((PositionType diagonal() const)) I2 tmp(p1,p2); I2Pos pos(tmp.diagonal()); TEST_REAL_SIMILAR(pos[0],60.0); TEST_REAL_SIMILAR(pos[1],75.0); END_SECTION START_SECTION((CoordinateType width() const)) I2 tmp(p1,p2); TEST_REAL_SIMILAR(tmp.width(),60.0) END_SECTION START_SECTION((CoordinateType height() const)) I2 tmp(p1,p2); TEST_REAL_SIMILAR(tmp.height(),75.0) END_SECTION START_SECTION((CoordinateType maxX() const)) I2 tmp(p1,p2); TEST_REAL_SIMILAR(tmp.maxX(),65.0) END_SECTION START_SECTION((CoordinateType maxY() const)) I2 tmp(p1,p2); TEST_REAL_SIMILAR(tmp.maxY(),17.5) END_SECTION START_SECTION((CoordinateType minX() const)) I2 tmp(p1,p2); TEST_REAL_SIMILAR(tmp.minX(),5.0) END_SECTION START_SECTION((CoordinateType minY() const)) I2 tmp(p1,p2); TEST_REAL_SIMILAR(tmp.minY(),-57.5) END_SECTION START_SECTION((void setMinX(CoordinateType const c))) I2 tmp(p1,p2); tmp.setMinX(57.67); TEST_REAL_SIMILAR(tmp.minX(),57.67) END_SECTION START_SECTION((void setMaxX(CoordinateType const c))) I2 tmp(p1,p2); tmp.setMaxX(57.67); TEST_REAL_SIMILAR(tmp.maxX(),57.67) END_SECTION START_SECTION((void setMinY(CoordinateType const c))) I2 tmp(p1,p2); tmp.setMinY(57.67); TEST_REAL_SIMILAR(tmp.minY(),57.67) END_SECTION START_SECTION((void setMaxY(CoordinateType const c))) I2 tmp(p1,p2); tmp.setMaxY(57.67); TEST_REAL_SIMILAR(tmp.maxY(),57.67) END_SECTION START_SECTION((template <UInt D2> void assign(const DIntervalBase< D2 > rhs))) DIntervalBase<2>::PositionType p1; p1[0]=5.0; p1[1]=17.5; DIntervalBase<2>::PositionType p2; p2[0]=65.0; p2[1]=-57.5; DIntervalBase<2> i2(p1,p2); DIntervalBase<3> tmp; tmp.assign(i2); TEST_REAL_SIMILAR(tmp.minPosition()[0],5.0); TEST_REAL_SIMILAR(tmp.minPosition()[1],-57.5); TEST_REAL_SIMILAR(tmp.maxPosition()[0],65.0); TEST_REAL_SIMILAR(tmp.maxPosition()[1],17.5); DIntervalBase<1> tmp2; tmp2.assign(i2); TEST_REAL_SIMILAR(tmp2.minPosition()[0],5.0); TEST_REAL_SIMILAR(tmp2.maxPosition()[0],65.0); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MassDecompositionAlgorithm_test.cpp
.cpp
1,885
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/CHEMISTRY/MASSDECOMPOSITION/MassDecompositionAlgorithm.h> #include <OpenMS/CHEMISTRY/AASequence.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MassDecompositionAlgorithm, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MassDecompositionAlgorithm* ptr = nullptr; MassDecompositionAlgorithm* nullPointer = nullptr; START_SECTION(MassDecompositionAlgorithm()) { ptr = new MassDecompositionAlgorithm(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~MassDecompositionAlgorithm()) { delete ptr; } END_SECTION START_SECTION((void getDecompositions(std::vector<MassDecomposition>& decomps, double weight))) { vector<MassDecomposition> decomps; double mass = AASequence::fromString("DFPIANGER").getMonoWeight(Residue::Internal); cerr << mass << endl; MassDecompositionAlgorithm mda; Param p(mda.getParameters()); p.setValue("tolerance", 0.0001); mda.setParameters(p); mda.getDecompositions(decomps, mass); TEST_EQUAL(decomps.size(), 842) p.setValue("tolerance", 0.001); mda.setParameters(p); decomps.clear(); mda.getDecompositions(decomps, mass); TEST_EQUAL(decomps.size(), 911); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SpectrumCheapDPCorr_test.cpp
.cpp
3,006
111
// 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/SpectrumCheapDPCorr.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/DTAFile.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(SpectrumCheapDPCorr, "$Id$") ///////////////////////////////////////////////////////////// SpectrumCheapDPCorr* e_ptr = nullptr; SpectrumCheapDPCorr* e_nullPointer = nullptr; START_SECTION(SpectrumCheapDPCorr()) e_ptr = new SpectrumCheapDPCorr; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION(~SpectrumCheapDPCorr()) delete e_ptr; END_SECTION e_ptr = new SpectrumCheapDPCorr(); START_SECTION(SpectrumCheapDPCorr(const SpectrumCheapDPCorr& source)) SpectrumCheapDPCorr copy(*e_ptr); TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) TEST_EQUAL(copy.getName(), e_ptr->getName()) END_SECTION START_SECTION(SpectrumCheapDPCorr& operator = (const SpectrumCheapDPCorr& source)) SpectrumCheapDPCorr copy; copy = *e_ptr; TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) TEST_EQUAL(copy.getName(), e_ptr->getName()) END_SECTION START_SECTION(double operator () (const PeakSpectrum& a, const PeakSpectrum& b) const) DTAFile dta_file; PeakSpectrum spec1; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec1); DTAFile dta_file2; PeakSpectrum spec2; dta_file2.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests_2.dta"), spec2); double score = (*e_ptr)(spec1, spec2); TOLERANCE_ABSOLUTE(0.1) TEST_REAL_SIMILAR(score, 10145.4) score = (*e_ptr)(spec1, spec1); TEST_REAL_SIMILAR(score, 12295.5) SpectrumCheapDPCorr corr; score = corr(spec1, spec2); TEST_REAL_SIMILAR(score, 10145.4) score = corr(spec1, spec1); TEST_REAL_SIMILAR(score, 12295.5) END_SECTION START_SECTION(const PeakSpectrum& lastconsensus() const) TEST_EQUAL(e_ptr->lastconsensus().size(), 121) END_SECTION START_SECTION((Map<UInt, UInt> getPeakMap() const)) TEST_EQUAL(e_ptr->getPeakMap().size(), 121) END_SECTION START_SECTION(double operator () (const PeakSpectrum& a) const) DTAFile dta_file; PeakSpectrum spec1; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec1); double score = (*e_ptr)(spec1); TEST_REAL_SIMILAR(score, 12295.5) END_SECTION START_SECTION(void setFactor(double f)) e_ptr->setFactor(0.3); TEST_EXCEPTION(Exception::OutOfRange, e_ptr->setFactor(1.1)) END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FileTypes_test.cpp
.cpp
7,723
146
// 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, Andreas Bertsch, Marc Sturm, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/FileHandler.h> #include <OpenMS/FORMAT/FileTypes.h> /////////////////////////// START_TEST(FileHandler, "Id") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; START_SECTION((static String typeToName(Type type))) { TEST_EQUAL(FileTypes::typeToName(FileTypes::UNKNOWN), "unknown"); TEST_EQUAL(FileTypes::typeToName(FileTypes::DTA), "dta"); TEST_EQUAL(FileTypes::typeToName(FileTypes::DTA2D), "dta2d"); TEST_EQUAL(FileTypes::typeToName(FileTypes::MZDATA), "mzData"); TEST_EQUAL(FileTypes::typeToName(FileTypes::MZXML), "mzXML"); TEST_EQUAL(FileTypes::typeToName(FileTypes::MZML), "mzML"); TEST_EQUAL(FileTypes::typeToName(FileTypes::FEATUREXML), "featureXML"); TEST_EQUAL(FileTypes::typeToName(FileTypes::IDXML), "idXML"); TEST_EQUAL(FileTypes::typeToName(FileTypes::CONSENSUSXML), "consensusXML"); TEST_EQUAL(FileTypes::typeToName(FileTypes::TRANSFORMATIONXML), "trafoXML"); TEST_EQUAL(FileTypes::typeToName(FileTypes::INI), "ini"); TEST_EQUAL(FileTypes::typeToName(FileTypes::TOPPAS), "toppas"); TEST_EQUAL(FileTypes::typeToName(FileTypes::PNG), "png"); TEST_EQUAL(FileTypes::typeToName(FileTypes::TXT), "txt"); TEST_EQUAL(FileTypes::typeToName(FileTypes::CSV), "csv"); TEST_EQUAL(FileTypes::typeToName(FileTypes::MZTAB), "mzTab"); // try them all, just to make sure they are all there for (int i = 0; i < (int)FileTypes::SIZE_OF_TYPE; ++i) { TEST_EQUAL(FileTypes::nameToType(FileTypes::typeToName(FileTypes::Type(i))), FileTypes::Type(i)); } } END_SECTION START_SECTION((static Type nameToType(const String& name))) TEST_EQUAL(FileTypes::typeToDescription(FileTypes::DTA2D), "dta2d raw data file"); TEST_EQUAL(FileTypes::typeToDescription(FileTypes::UNKNOWN), "unknown file extension"); END_SECTION START_SECTION((static Type nameToType(const String& name))) { TEST_EQUAL(FileTypes::UNKNOWN, FileTypes::nameToType("unknown")); TEST_EQUAL(FileTypes::DTA, FileTypes::nameToType("dta")); TEST_EQUAL(FileTypes::DTA2D, FileTypes::nameToType("dta2d")); TEST_EQUAL(FileTypes::MZDATA, FileTypes::nameToType("mzData")); TEST_EQUAL(FileTypes::MZXML, FileTypes::nameToType("mzXML")); TEST_EQUAL(FileTypes::FEATUREXML, FileTypes::nameToType("featureXML")); TEST_EQUAL(FileTypes::IDXML, FileTypes::nameToType("idXmL")); // case-insensitivity TEST_EQUAL(FileTypes::CONSENSUSXML, FileTypes::nameToType("consensusXML")); TEST_EQUAL(FileTypes::MGF, FileTypes::nameToType("mgf")); TEST_EQUAL(FileTypes::INI, FileTypes::nameToType("ini")); TEST_EQUAL(FileTypes::TOPPAS, FileTypes::nameToType("toppas")); TEST_EQUAL(FileTypes::TRANSFORMATIONXML, FileTypes::nameToType("trafoXML")); TEST_EQUAL(FileTypes::MZML, FileTypes::nameToType("mzML")); TEST_EQUAL(FileTypes::MS2, FileTypes::nameToType("ms2")); TEST_EQUAL(FileTypes::PEPXML, FileTypes::nameToType("pepXML")); TEST_EQUAL(FileTypes::PROTXML, FileTypes::nameToType("protXML")); TEST_EQUAL(FileTypes::MZIDENTML, FileTypes::nameToType("mzid")); TEST_EQUAL(FileTypes::GELML, FileTypes::nameToType("gelML")); TEST_EQUAL(FileTypes::TRAML, FileTypes::nameToType("traML")); TEST_EQUAL(FileTypes::MSP, FileTypes::nameToType("msp")); TEST_EQUAL(FileTypes::OMSSAXML, FileTypes::nameToType("omssaXML")); TEST_EQUAL(FileTypes::PNG, FileTypes::nameToType("png")); TEST_EQUAL(FileTypes::XMASS, FileTypes::nameToType("fid")); TEST_EQUAL(FileTypes::TSV, FileTypes::nameToType("tsv")); TEST_EQUAL(FileTypes::PEPLIST, FileTypes::nameToType("peplist")); TEST_EQUAL(FileTypes::HARDKLOER, FileTypes::nameToType("hardkloer")); TEST_EQUAL(FileTypes::KROENIK, FileTypes::nameToType("kroenik")); TEST_EQUAL(FileTypes::FASTA, FileTypes::nameToType("fasta")); TEST_EQUAL(FileTypes::EDTA, FileTypes::nameToType("edta")); TEST_EQUAL(FileTypes::CSV, FileTypes::nameToType("csv")); TEST_EQUAL(FileTypes::TXT, FileTypes::nameToType("txt")); TEST_EQUAL(FileTypes::PARQUET, FileTypes::nameToType("parquet")); TEST_EQUAL(FileTypes::PARQUET, FileTypes::nameToType("pqt")); // Test alternate extension TEST_EQUAL(FileTypes::UNKNOWN, FileTypes::nameToType("somethingunknown")); } END_SECTION START_SECTION([EXTRA] FileTypes::FileTypeList) FileTypeList list({ FileTypes::MZML, FileTypes::BZ2 }); TEST_EQUAL(list.contains(FileTypes::MZML), true); TEST_EQUAL(list.contains(FileTypes::BZ2), true); TEST_EQUAL(list.contains(FileTypes::MZDATA), false); TEST_EQUAL(list.toFileDialogFilter(FilterLayout::BOTH, true), "all readable files (*.mzML *.bz2);;mzML raw data file (*.mzML);;bzip2 compressed file (*.bz2);;all files (*)") TEST_EQUAL(list.toFileDialogFilter(FilterLayout::COMPACT, true), "all readable files (*.mzML *.bz2);;all files (*)") TEST_EQUAL(list.toFileDialogFilter(FilterLayout::ONE_BY_ONE, true), "mzML raw data file (*.mzML);;bzip2 compressed file (*.bz2);;all files (*)") TEST_EQUAL(list.toFileDialogFilter(FilterLayout::BOTH, false), "all readable files (*.mzML *.bz2);;mzML raw data file (*.mzML);;bzip2 compressed file (*.bz2)") // testing Type FileTypeList::fromFileDialogFilter(const String& filter, const Type fallback = Type::UNKNOWN) const TEST_EQUAL(list.fromFileDialogFilter("all readable files (*.mzML *.bz2)"), FileTypes::UNKNOWN); TEST_EQUAL(list.fromFileDialogFilter("all files (*)"), FileTypes::UNKNOWN); TEST_EQUAL(list.fromFileDialogFilter("mzML raw data file (*.mzML)"), FileTypes::MZML); TEST_EQUAL(list.fromFileDialogFilter("bzip2 compressed file (*.bz2)"), FileTypes::BZ2); TEST_EXCEPTION(Exception::ElementNotFound, list.fromFileDialogFilter("not a valid filter")); // with default TEST_EQUAL(list.fromFileDialogFilter("all readable files (*.mzML *.bz2)", FileTypes::CONSENSUSXML), FileTypes::CONSENSUSXML); TEST_EQUAL(list.fromFileDialogFilter("all files (*)", FileTypes::CONSENSUSXML), FileTypes::CONSENSUSXML); TEST_EQUAL(list.fromFileDialogFilter("mzML raw data file (*.mzML)", FileTypes::CONSENSUSXML), FileTypes::MZML); TEST_EQUAL(list.fromFileDialogFilter("bzip2 compressed file (*.bz2)", FileTypes::CONSENSUSXML), FileTypes::BZ2); TEST_EXCEPTION(Exception::ElementNotFound, list.fromFileDialogFilter("not a valid filter", FileTypes::CONSENSUSXML)); END_SECTION START_SECTION(static FileTypes::FileTypeList typesWithProperties(const std::vector<FileProperties>& features)) { std::vector<FileTypes::FileProperties> f; f.push_back(FileTypes::FileProperties::READABLE); FileTypeList g = FileTypeList::typesWithProperties(f); TEST_EQUAL(g.getTypes().size(), 38); // Test that empty filter returns the full list TEST_EQUAL(FileTypeList::typesWithProperties({}).size(), 61); // Test that the full list is equal to the list of known file types TEST_EQUAL(FileTypeList::typesWithProperties({}).size(),static_cast<size_t>(FileTypes::Type::SIZE_OF_TYPE)); // Check that we don't have duplicate Types in our type_with_annotation__ vector<FileTypes::Type> vec = FileTypeList::typesWithProperties({}); sort(vec.begin(),vec.end()); auto it = std::unique(vec.begin(), vec.end()); TEST_TRUE(it ==vec.end()); } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SpectrumHelpers_test.cpp
.cpp
3,861
106
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest, Witold Wolski $ // $Authors: Witold Wolski $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/SpectrumHelpers.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/MockObjects.h> #include <OpenMS/ANALYSIS/OPENSWATH/DIAScoring.h> #include <OpenMS/ANALYSIS/OPENSWATH/DIAHelper.h> using namespace std; using namespace OpenMS; using namespace OpenSwath; START_TEST(DiaPrescore2, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION ( [EXTRA] testscorefunction) { 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(arr1[0]) ); 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(arr2[0]) ); data1->data = mz; data2->data = intensity; sptr->setMZArray( data1); sptr->setIntensityArray( data2); std::vector<OpenSwath::SpectrumPtr> sptrArr; sptrArr.push_back(sptr); double mzres, intensityres, imres; // mz range from 499 to 501 RangeMZ mz_range(500.); RangeMobility im_range_empty; mz_range.minSpanIfSingular(2.); DIAHelpers::integrateWindow(sptrArr, mzres, imres, intensityres, mz_range, im_range_empty); TEST_REAL_SIMILAR(mzres, 499.392014652015); TEST_REAL_SIMILAR(intensityres, 273 ); // >> exp = [240, 74, 39, 15, 0] > 121 / 500.338842975207 // >> theo = [1, 0.325757771553019, 0.0678711748364005, 0.0105918703087134, 0.00134955223787482] // >> from scipy.stats.stats import pearsonr // >> pearsonr(exp, theo) // (0.99463189043051314, 0.00047175434098498532) // mz_range.setMin(499.6); mz_range.setMax(501.4); DIAHelpers::integrateWindow(sptrArr, mzres, imres, intensityres, mz_range, im_range_empty); TEST_REAL_SIMILAR(mzres, 500.338842975207); TEST_REAL_SIMILAR(intensityres,121 ); std::vector<double> wincenter, mzresv, intresv, imresv; wincenter.push_back(300.); wincenter.push_back(200.); wincenter.push_back(500.); wincenter.push_back(600.); DIAHelpers::integrateWindows(sptrArr,wincenter,0.5, intresv, mzresv, imresv, im_range_empty); TEST_REAL_SIMILAR(mzresv[0], 300); TEST_REAL_SIMILAR(intresv[0],0 ); TEST_REAL_SIMILAR(mzresv[1],200 ); TEST_REAL_SIMILAR(intresv[1],0 ); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IsotopeDistributionMIDAS_test.cpp
.cpp
0
0
null
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AAIndex_test.cpp
.cpp
12,994
280
// 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/CHEMISTRY/AASequence.h> #include <OpenMS/CHEMISTRY/AAIndex.h> using namespace OpenMS; using namespace std; /////////////////////////// AASequence seq1 = AASequence::fromString("ALEGDEK"); AASequence seq2 = AASequence::fromString("GTVVTGR"); AASequence seq3 = AASequence::fromString("EHVLLAR"); START_TEST(AASequenceIndeces, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //sequence spec_id protein_id mass GB500 arginin_count KHAG800101 VASM830103 NADH010106 NADH010107 WILM950102 ROBB760107 OOBM850104 FAUJ880111 FINA770101 ARGP820102 M F H Q Y target_log //ALEGDEK 15 0587 761.368 1337.53 0 129.3 1.145 31 565 1.5200000 -6.60000e+00 -3.240000 1 7.18 5.23 0 0 0 0 0 2.08623342 //GTVVTGR 15 0587 689.394 1442.70 1 383.2 1.042 241 403 7.1800000 -3.00000e-01 -16.010000 1 5.55 5.02 0 0 0 0 0 1.35346120 //EHVLLAR 15 0587 837.494 1442.70 1 318.5 1.259 171 190 18.1300000 3.00000e-01 -9.970000 2 7.73 9.34 0 0 1 0 0 5.22075034 TOLERANCE_ABSOLUTE(0.01) START_SECTION(static double calculateGB(const AASequence& seq, double T=500.0) ) TEST_REAL_SIMILAR(AAIndex::calculateGB(seq1), 1337.53) TEST_REAL_SIMILAR(AAIndex::calculateGB(seq2), 1442.70) TEST_REAL_SIMILAR(AAIndex::calculateGB(seq3), 1442.70) TEST_NOT_EQUAL(AAIndex::calculateGB(seq1,100.0), 1337.53) TEST_NOT_EQUAL(AAIndex::calculateGB(seq2,100.0), 1442.70) TEST_NOT_EQUAL(AAIndex::calculateGB(seq3,100.0), 1442.70) END_SECTION START_SECTION(static double aliphatic(char aa)) TEST_REAL_SIMILAR(AAIndex::aliphatic('A'),1.0) TEST_REAL_SIMILAR(AAIndex::aliphatic('B'),0.0) END_SECTION START_SECTION(static double acidic(char aa)) TEST_REAL_SIMILAR(AAIndex::acidic('D'),1.0) TEST_REAL_SIMILAR(AAIndex::acidic('A'),0.0) END_SECTION START_SECTION(static double basic(char aa)) TEST_REAL_SIMILAR(AAIndex::basic('K'),1.0) TEST_REAL_SIMILAR(AAIndex::basic('A'),0.0) END_SECTION START_SECTION(static double polar(char aa)) TEST_REAL_SIMILAR(AAIndex::polar('S'),1.0) TEST_REAL_SIMILAR(AAIndex::polar('A'),0.0) END_SECTION START_SECTION(static double getKHAG800101(char aa)) TEST_REAL_SIMILAR(AAIndex::getKHAG800101('A'),49.1) END_SECTION START_SECTION(static double getVASM830103(char aa)) TEST_REAL_SIMILAR(AAIndex::getVASM830103('A'),0.159) TEST_REAL_SIMILAR(AAIndex::getVASM830103('R'),0.194) TEST_REAL_SIMILAR(AAIndex::getVASM830103('N'),0.385) TEST_REAL_SIMILAR(AAIndex::getVASM830103('D'),0.283) TEST_REAL_SIMILAR(AAIndex::getVASM830103('C'),0.187) TEST_REAL_SIMILAR(AAIndex::getVASM830103('Q'),0.236) TEST_REAL_SIMILAR(AAIndex::getVASM830103('E'),0.206) TEST_REAL_SIMILAR(AAIndex::getVASM830103('G'),0.049) TEST_REAL_SIMILAR(AAIndex::getVASM830103('H'),0.233) TEST_REAL_SIMILAR(AAIndex::getVASM830103('I'),0.581) TEST_REAL_SIMILAR(AAIndex::getVASM830103('L'),0.083) TEST_REAL_SIMILAR(AAIndex::getVASM830103('K'),0.159) TEST_REAL_SIMILAR(AAIndex::getVASM830103('M'),0.198) TEST_REAL_SIMILAR(AAIndex::getVASM830103('F'),0.682) TEST_REAL_SIMILAR(AAIndex::getVASM830103('P'),0.366) TEST_REAL_SIMILAR(AAIndex::getVASM830103('S'),0.150) TEST_REAL_SIMILAR(AAIndex::getVASM830103('T'),0.074) TEST_REAL_SIMILAR(AAIndex::getVASM830103('W'),0.463) TEST_REAL_SIMILAR(AAIndex::getVASM830103('Y'),0.737) TEST_REAL_SIMILAR(AAIndex::getVASM830103('V'),0.301) END_SECTION START_SECTION(static double getNADH010106(char aa)) TEST_REAL_SIMILAR(AAIndex::getNADH010106('A'),5.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('R'),-57.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('N'),-77.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('D'),45.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('C'),224.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('Q'),-67.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('E'),-8.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('G'),-47.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('H'),-50.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('I'),83.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('L'),82.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('K'),-38.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('M'),83.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('F'),117.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('P'),-103.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('S'),-41.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('T'),79.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('W'),130.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('Y'),27.0) TEST_REAL_SIMILAR(AAIndex::getNADH010106('V'),117.0) END_SECTION START_SECTION(static double getNADH010107(char aa)) TEST_REAL_SIMILAR(AAIndex::getNADH010107('A'),-2.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('R'),-41.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('N'),-97.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('D'),248.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('C'),329.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('Q'),-37.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('E'),117.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('G'),-66.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('H'),-70.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('I'),28.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('L'),36.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('K'),115.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('M'),62.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('F'),120.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('P'),-132.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('S'),-52.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('T'),174.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('W'),179.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('Y'),-7.0) TEST_REAL_SIMILAR(AAIndex::getNADH010107('V'),114.0) END_SECTION START_SECTION(static double getWILM950102(char aa)) TEST_REAL_SIMILAR(AAIndex::getWILM950102('A'),2.62) TEST_REAL_SIMILAR(AAIndex::getWILM950102('R'),1.26) TEST_REAL_SIMILAR(AAIndex::getWILM950102('N'),-1.27) TEST_REAL_SIMILAR(AAIndex::getWILM950102('D'),-2.84) TEST_REAL_SIMILAR(AAIndex::getWILM950102('C'),0.73) TEST_REAL_SIMILAR(AAIndex::getWILM950102('Q'),-1.69) TEST_REAL_SIMILAR(AAIndex::getWILM950102('E'),-0.45) TEST_REAL_SIMILAR(AAIndex::getWILM950102('G'),-1.15) TEST_REAL_SIMILAR(AAIndex::getWILM950102('H'),-0.74) TEST_REAL_SIMILAR(AAIndex::getWILM950102('I'),4.38) TEST_REAL_SIMILAR(AAIndex::getWILM950102('L'),6.57) TEST_REAL_SIMILAR(AAIndex::getWILM950102('K'),-2.78) TEST_REAL_SIMILAR(AAIndex::getWILM950102('M'),-3.12) TEST_REAL_SIMILAR(AAIndex::getWILM950102('F'),9.14) TEST_REAL_SIMILAR(AAIndex::getWILM950102('P'),-0.12) TEST_REAL_SIMILAR(AAIndex::getWILM950102('S'),-1.39) TEST_REAL_SIMILAR(AAIndex::getWILM950102('T'),1.81) TEST_REAL_SIMILAR(AAIndex::getWILM950102('W'),5.91) TEST_REAL_SIMILAR(AAIndex::getWILM950102('Y'),1.39) TEST_REAL_SIMILAR(AAIndex::getWILM950102('V'),2.30) END_SECTION START_SECTION(static double getROBB760107(char aa)) TEST_REAL_SIMILAR(AAIndex::getROBB760107('A'),0.0) TEST_REAL_SIMILAR(AAIndex::getROBB760107('R'),1.1) TEST_REAL_SIMILAR(AAIndex::getROBB760107('N'),-2.0) TEST_REAL_SIMILAR(AAIndex::getROBB760107('D'),-2.6) TEST_REAL_SIMILAR(AAIndex::getROBB760107('C'),5.4) TEST_REAL_SIMILAR(AAIndex::getROBB760107('Q'),2.4) TEST_REAL_SIMILAR(AAIndex::getROBB760107('E'),3.1) TEST_REAL_SIMILAR(AAIndex::getROBB760107('G'),-3.4) TEST_REAL_SIMILAR(AAIndex::getROBB760107('H'),0.8) TEST_REAL_SIMILAR(AAIndex::getROBB760107('I'),-0.1) TEST_REAL_SIMILAR(AAIndex::getROBB760107('L'),-3.7) TEST_REAL_SIMILAR(AAIndex::getROBB760107('K'),-3.1) TEST_REAL_SIMILAR(AAIndex::getROBB760107('M'),-2.1) TEST_REAL_SIMILAR(AAIndex::getROBB760107('F'),0.7) TEST_REAL_SIMILAR(AAIndex::getROBB760107('P'),7.4) TEST_REAL_SIMILAR(AAIndex::getROBB760107('S'),1.3) TEST_REAL_SIMILAR(AAIndex::getROBB760107('T'),0.0) TEST_REAL_SIMILAR(AAIndex::getROBB760107('W'),-3.4) TEST_REAL_SIMILAR(AAIndex::getROBB760107('Y'),4.8) TEST_REAL_SIMILAR(AAIndex::getROBB760107('V'),2.7) END_SECTION START_SECTION(static double getOOBM850104(char aa)) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('A'),-2.49) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('R'),2.55) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('N'),2.27) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('D'),8.86) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('C'),-3.13) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('Q'),1.79) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('E'),4.04) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('G'),-0.56) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('H'),4.22) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('I'),-10.87) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('L'),-7.16) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('K'),-9.97) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('M'),-4.96) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('F'),-6.64) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('P'),5.19) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('S'),-1.60) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('T'),-4.75) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('W'),-17.84) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('Y'),9.25) TEST_REAL_SIMILAR(AAIndex::getOOBM850104('V'),-3.97) END_SECTION START_SECTION(static double getFAUJ880111(char aa)) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('A'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('R'),1.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('N'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('D'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('C'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('Q'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('E'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('G'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('H'),1.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('I'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('L'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('K'),1.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('M'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('F'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('P'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('S'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('T'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('W'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('Y'),0.) TEST_REAL_SIMILAR(AAIndex::getFAUJ880111('V'),0.) END_SECTION START_SECTION(static double getFINA770101(char aa)) TEST_REAL_SIMILAR(AAIndex::getFINA770101('A'),1.08) TEST_REAL_SIMILAR(AAIndex::getFINA770101('R'),1.05) TEST_REAL_SIMILAR(AAIndex::getFINA770101('N'),0.85) TEST_REAL_SIMILAR(AAIndex::getFINA770101('D'),0.85) TEST_REAL_SIMILAR(AAIndex::getFINA770101('C'),0.95) TEST_REAL_SIMILAR(AAIndex::getFINA770101('Q'),0.95) TEST_REAL_SIMILAR(AAIndex::getFINA770101('E'),1.15) TEST_REAL_SIMILAR(AAIndex::getFINA770101('G'),0.55) TEST_REAL_SIMILAR(AAIndex::getFINA770101('H'),1.00) TEST_REAL_SIMILAR(AAIndex::getFINA770101('I'),1.05) TEST_REAL_SIMILAR(AAIndex::getFINA770101('L'),1.25) TEST_REAL_SIMILAR(AAIndex::getFINA770101('K'),1.15) TEST_REAL_SIMILAR(AAIndex::getFINA770101('M'),1.15) TEST_REAL_SIMILAR(AAIndex::getFINA770101('F'),1.10) TEST_REAL_SIMILAR(AAIndex::getFINA770101('P'),0.71) TEST_REAL_SIMILAR(AAIndex::getFINA770101('S'),0.75) TEST_REAL_SIMILAR(AAIndex::getFINA770101('T'),0.75) TEST_REAL_SIMILAR(AAIndex::getFINA770101('W'),1.10) TEST_REAL_SIMILAR(AAIndex::getFINA770101('Y'),1.10) TEST_REAL_SIMILAR(AAIndex::getFINA770101('V'),0.95) END_SECTION START_SECTION(static double getARGP820102(char aa)) TEST_REAL_SIMILAR(AAIndex::getARGP820102('A'),1.18) TEST_REAL_SIMILAR(AAIndex::getARGP820102('R'),0.20) TEST_REAL_SIMILAR(AAIndex::getARGP820102('N'),0.23) TEST_REAL_SIMILAR(AAIndex::getARGP820102('D'),0.05) TEST_REAL_SIMILAR(AAIndex::getARGP820102('C'),1.89) TEST_REAL_SIMILAR(AAIndex::getARGP820102('Q'),0.72) TEST_REAL_SIMILAR(AAIndex::getARGP820102('E'),0.11) TEST_REAL_SIMILAR(AAIndex::getARGP820102('G'),0.49) TEST_REAL_SIMILAR(AAIndex::getARGP820102('H'),0.31) TEST_REAL_SIMILAR(AAIndex::getARGP820102('I'),1.45) TEST_REAL_SIMILAR(AAIndex::getARGP820102('L'),3.23) TEST_REAL_SIMILAR(AAIndex::getARGP820102('K'),0.06) TEST_REAL_SIMILAR(AAIndex::getARGP820102('M'),2.67) TEST_REAL_SIMILAR(AAIndex::getARGP820102('F'),1.96) TEST_REAL_SIMILAR(AAIndex::getARGP820102('P'),0.76) TEST_REAL_SIMILAR(AAIndex::getARGP820102('S'),0.97) TEST_REAL_SIMILAR(AAIndex::getARGP820102('T'),0.84) TEST_REAL_SIMILAR(AAIndex::getARGP820102('W'),0.77) TEST_REAL_SIMILAR(AAIndex::getARGP820102('Y'),0.39) TEST_REAL_SIMILAR(AAIndex::getARGP820102('V'),1.08) END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeptideIdentificationList_test.cpp
.cpp
8,234
295
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Timo Sachsenberg $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/METADATA/PeptideIdentificationList.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(PeptideIdentificationList, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeptideIdentificationList* ptr = nullptr; PeptideIdentificationList* null_ptr = nullptr; START_SECTION(PeptideIdentificationList()) { ptr = new PeptideIdentificationList(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~PeptideIdentificationList()) { delete ptr; } END_SECTION START_SECTION((PeptideIdentificationList(const PeptideIdentificationList& vec))) { PeptideIdentificationList id_list; PeptideIdentification pep_id; pep_id.setRT(1234.5); pep_id.setMZ(567.8); id_list.push_back(pep_id); PeptideIdentificationList pep_ids(id_list); TEST_EQUAL(pep_ids.size(), 1) TEST_REAL_SIMILAR(pep_ids[0].getRT(), 1234.5) TEST_REAL_SIMILAR(pep_ids[0].getMZ(), 567.8) } END_SECTION START_SECTION((PeptideIdentificationList(PeptideIdentificationList&& vec))) { PeptideIdentificationList id_list; PeptideIdentification pep_id; pep_id.setRT(1234.5); pep_id.setMZ(567.8); id_list.push_back(pep_id); PeptideIdentificationList pep_ids(std::move(id_list)); TEST_EQUAL(pep_ids.size(), 1) TEST_EQUAL(id_list.capacity(), 0) // this is a move constructor, so the original id_list should be empty and not occupy any memory on the heap TEST_REAL_SIMILAR(pep_ids[0].getRT(), 1234.5) TEST_REAL_SIMILAR(pep_ids[0].getMZ(), 567.8) } END_SECTION START_SECTION((PeptideIdentificationList(size_type count))) { PeptideIdentificationList pep_ids(5); TEST_EQUAL(pep_ids.size(), 5) } END_SECTION START_SECTION((PeptideIdentificationList(size_type count, const PeptideIdentification& value))) { PeptideIdentification pep_id; pep_id.setRT(1234.5); pep_id.setMZ(567.8); PeptideIdentificationList pep_ids(3, pep_id); TEST_EQUAL(pep_ids.size(), 3) for (size_t i = 0; i < 3; ++i) { TEST_REAL_SIMILAR(pep_ids[i].getRT(), 1234.5) TEST_REAL_SIMILAR(pep_ids[i].getMZ(), 567.8) } } END_SECTION START_SECTION((PeptideIdentificationList(InputIt first, InputIt last))) { PeptideIdentificationList id_list; for (int i = 0; i < 3; ++i) { PeptideIdentification pep_id; pep_id.setRT(i * 100.0); pep_id.setMZ(i * 200.0); id_list.push_back(pep_id); } PeptideIdentificationList pep_ids(id_list.begin(), id_list.end()); TEST_EQUAL(pep_ids.size(), 3) for (size_t i = 0; i < 3; ++i) { TEST_REAL_SIMILAR(pep_ids[i].getRT(), i * 100.0) TEST_REAL_SIMILAR(pep_ids[i].getMZ(), i * 200.0) } } END_SECTION START_SECTION((PeptideIdentificationList(std::initializer_list<PeptideIdentification> init))) { PeptideIdentification pep_id1, pep_id2; pep_id1.setRT(100.0); pep_id1.setMZ(200.0); pep_id2.setRT(300.0); pep_id2.setMZ(400.0); PeptideIdentificationList pep_ids{pep_id1, pep_id2}; TEST_EQUAL(pep_ids.size(), 2) TEST_REAL_SIMILAR(pep_ids[0].getRT(), 100.0) TEST_REAL_SIMILAR(pep_ids[0].getMZ(), 200.0) TEST_REAL_SIMILAR(pep_ids[1].getRT(), 300.0) TEST_REAL_SIMILAR(pep_ids[1].getMZ(), 400.0) } END_SECTION START_SECTION((PeptideIdentificationList(const PeptideIdentificationList&))) { PeptideIdentificationList pep_ids1; PeptideIdentification pep_id; pep_id.setRT(1234.5); pep_id.setMZ(567.8); pep_ids1.push_back(pep_id); PeptideIdentificationList pep_ids2(pep_ids1); TEST_EQUAL(pep_ids2.size(), 1) TEST_REAL_SIMILAR(pep_ids2[0].getRT(), 1234.5) TEST_REAL_SIMILAR(pep_ids2[0].getMZ(), 567.8) } END_SECTION START_SECTION((PeptideIdentificationList(PeptideIdentificationList&&))) { PeptideIdentificationList pep_ids1; PeptideIdentification pep_id; pep_id.setRT(1234.5); pep_id.setMZ(567.8); pep_ids1.push_back(pep_id); PeptideIdentificationList pep_ids2(std::move(pep_ids1)); TEST_EQUAL(pep_ids2.size(), 1) TEST_EQUAL(pep_ids1.capacity(), 0) // this is a move constructor, so the original pep_ids1 should be empty and not occupy any memory on the heap TEST_REAL_SIMILAR(pep_ids2[0].getRT(), 1234.5) TEST_REAL_SIMILAR(pep_ids2[0].getMZ(), 567.8) } END_SECTION START_SECTION((PeptideIdentificationList& operator=(const PeptideIdentificationList&))) { PeptideIdentificationList pep_ids1; PeptideIdentification pep_id; pep_id.setRT(1234.5); pep_id.setMZ(567.8); pep_ids1.push_back(pep_id); PeptideIdentificationList pep_ids2; pep_ids2 = pep_ids1; TEST_EQUAL(pep_ids2.size(), 1) TEST_REAL_SIMILAR(pep_ids2[0].getRT(), 1234.5) TEST_REAL_SIMILAR(pep_ids2[0].getMZ(), 567.8) } END_SECTION START_SECTION((PeptideIdentificationList& operator=(PeptideIdentificationList&&))) { PeptideIdentificationList pep_ids1; PeptideIdentification pep_id; pep_id.setRT(1234.5); pep_id.setMZ(567.8); pep_ids1.push_back(pep_id); PeptideIdentificationList pep_ids2; pep_ids2 = std::move(pep_ids1); TEST_EQUAL(pep_ids2.size(), 1) TEST_REAL_SIMILAR(pep_ids2[0].getRT(), 1234.5) TEST_REAL_SIMILAR(pep_ids2[0].getMZ(), 567.8) } END_SECTION START_SECTION((PeptideIdentificationList& operator=(const PeptideIdentificationList& vec))) { PeptideIdentificationList id_list; PeptideIdentification pep_id; pep_id.setRT(1234.5); pep_id.setMZ(567.8); id_list.push_back(pep_id); PeptideIdentificationList pep_ids; pep_ids = id_list; TEST_EQUAL(pep_ids.size(), 1) TEST_REAL_SIMILAR(pep_ids[0].getRT(), 1234.5) TEST_REAL_SIMILAR(pep_ids[0].getMZ(), 567.8) } END_SECTION START_SECTION((PeptideIdentificationList& operator=(PeptideIdentificationList&& vec))) { PeptideIdentificationList id_list; PeptideIdentification pep_id; pep_id.setRT(1234.5); pep_id.setMZ(567.8); id_list.push_back(pep_id); PeptideIdentificationList pep_ids; pep_ids = std::move(id_list); TEST_EQUAL(pep_ids.size(), 1) TEST_REAL_SIMILAR(pep_ids[0].getRT(), 1234.5) TEST_REAL_SIMILAR(pep_ids[0].getMZ(), 567.8) } END_SECTION START_SECTION((PeptideIdentificationList& operator=(std::initializer_list<PeptideIdentification> init))) { PeptideIdentification pep_id1, pep_id2; pep_id1.setRT(100.0); pep_id1.setMZ(200.0); pep_id2.setRT(300.0); pep_id2.setMZ(400.0); PeptideIdentificationList pep_ids; pep_ids = {pep_id1, pep_id2}; TEST_EQUAL(pep_ids.size(), 2) TEST_REAL_SIMILAR(pep_ids[0].getRT(), 100.0) TEST_REAL_SIMILAR(pep_ids[0].getMZ(), 200.0) TEST_REAL_SIMILAR(pep_ids[1].getRT(), 300.0) TEST_REAL_SIMILAR(pep_ids[1].getMZ(), 400.0) } END_SECTION START_SECTION((Test vector functionality)) { // Test that it behaves like a vector PeptideIdentificationList pep_ids; // Test push_back PeptideIdentification pep_id1; pep_id1.setRT(100.0); pep_ids.push_back(pep_id1); TEST_EQUAL(pep_ids.size(), 1) // Test clear pep_ids.clear(); TEST_EQUAL(pep_ids.size(), 0) TEST_EQUAL(pep_ids.empty(), true) // Test resize pep_ids.resize(5); TEST_EQUAL(pep_ids.size(), 5) } END_SECTION START_SECTION((Test comparison operators)) { PeptideIdentificationList pep_ids1, pep_ids2; // Test equality of empty lists TEST_EQUAL(pep_ids1 == pep_ids2, true) TEST_EQUAL(pep_ids1 != pep_ids2, false) // Add element to one list PeptideIdentification pep_id; pep_id.setRT(100.0); pep_ids1.push_back(pep_id); // Test inequality TEST_EQUAL(pep_ids1 == pep_ids2, false) TEST_EQUAL(pep_ids1 != pep_ids2, true) // Add same element to second list pep_ids2.push_back(pep_id); // Test equality again TEST_EQUAL(pep_ids1 == pep_ids2, true) TEST_EQUAL(pep_ids1 != pep_ids2, false) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Compomer_test.cpp
.cpp
13,808
470
// 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/DATASTRUCTURES/Compomer.h> #include <OpenMS/DATASTRUCTURES/Adduct.h> #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; START_TEST(Compomer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Compomer* ptr = nullptr; Compomer* nullPointer = nullptr; START_SECTION(Compomer()) { ptr = new Compomer(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~Compomer()) { delete ptr; } END_SECTION START_SECTION((Compomer(Int net_charge, double mass, double log_p))) { Compomer c(34, 45.32f, 12.34f); TEST_EQUAL(c.getNetCharge(), 34); TEST_REAL_SIMILAR(c.getMass(), 45.32); TEST_REAL_SIMILAR(c.getLogP(), 12.34); } END_SECTION START_SECTION((Compomer(const Compomer& p) )) { Compomer c(34, 45.32f, 12.34f); Adduct a1(123, 3, 123.456, "S", -0.3453, 0); Adduct b1(3, -2, 1.456, "H", -0.13, 0); c.setID(434); c.add(a1, Compomer::RIGHT); c.add(b1, Compomer::LEFT); Compomer c2(c); TEST_EQUAL(c2.getNetCharge(), c.getNetCharge()); TEST_REAL_SIMILAR(c2.getMass(), c.getMass()); TEST_EQUAL(c2.getPositiveCharges(), c.getPositiveCharges()); TEST_EQUAL(c2.getNegativeCharges(), c.getNegativeCharges()); TEST_REAL_SIMILAR(c2.getLogP(), c.getLogP()); TEST_EQUAL(c2.getID(), c.getID()); } END_SECTION START_SECTION((Compomer& operator=(const Compomer &source))) { Compomer c(34, 45.32f, 12.34f); Adduct a1(123, 3, 123.456, "S", -0.3453, 0); Adduct b1(3, -2, 1.456, "H", -0.13, 0); c.setID(434); c.add(a1, Compomer::RIGHT); c.add(b1, Compomer::LEFT); Compomer c2 = c; TEST_EQUAL(c2.getNetCharge(), c.getNetCharge()); TEST_REAL_SIMILAR(c2.getMass(), c.getMass()); TEST_EQUAL(c2.getPositiveCharges(), c.getPositiveCharges()); TEST_EQUAL(c2.getNegativeCharges(), c.getNegativeCharges()); TEST_REAL_SIMILAR(c2.getLogP(), c.getLogP()); TEST_EQUAL(c2.getID(), c.getID()); } END_SECTION START_SECTION([EXTRA] friend OPENMS_DLLAPI bool operator==(const Compomer& a, const Compomer& b)) { Compomer c(34, 45.32f, 12.34f); Adduct a1(123, 3, 123.456, "S", -0.3453, 0); Adduct b1(3, -2, 1.456, "H", -0.13, 0); c.setID(434); c.add(a1, Compomer::RIGHT); Compomer c2(c); TEST_TRUE(c == c2); c.setID(2); TEST_EQUAL(c==c2, false); } END_SECTION START_SECTION((void add(const Adduct &a, UInt side))) { //Adduct(Int charge, Int amount, double singleMass, String formula, double log_prob Adduct a1(123, 43, 123.456, "S", -0.3453, 0); Adduct a2(123, 3, 123.456, "S", -0.3453, 0); Adduct b1(3, -2, 1.456, "H", -0.13, 0); Compomer c; c.add(a1, Compomer::RIGHT); //PRECISION(0.0001); TEST_EQUAL(c.getNetCharge(), 123*43); TEST_REAL_SIMILAR(c.getMass(), 123.456*43); TEST_REAL_SIMILAR(c.getLogP(), -0.3453*43); TEST_EQUAL(c.getPositiveCharges(), 123*43); TEST_EQUAL(c.getNegativeCharges(), 0); c.add(a2, Compomer::RIGHT); TEST_EQUAL(c.getNetCharge(), 123*46); TEST_REAL_SIMILAR(c.getMass(), 123.456*46); TEST_REAL_SIMILAR(c.getLogP(), -0.3453*46); TEST_EQUAL(c.getPositiveCharges(), 123*46); TEST_EQUAL(c.getNegativeCharges(), 0); c.add(b1, Compomer::RIGHT); TEST_EQUAL(c.getNetCharge(), 123*46+ 3*(-2)); TEST_REAL_SIMILAR(c.getMass(), 123.456*46 - 2*1.456); TEST_REAL_SIMILAR(c.getLogP(), -0.3453*46 -0.13*2); TEST_EQUAL(c.getPositiveCharges(), 123*46); TEST_EQUAL(c.getNegativeCharges(), 6); } END_SECTION START_SECTION(bool isConflicting(const Compomer &cmp, UInt side_this, UInt side_other) const) { EmpiricalFormula ef("H"); Adduct default_adduct(1, 1, ef.getMonoWeight(), ef.toString(), log(0.7f), 0); { Adduct a1(1, 1, 1.007, "H1", -0.13, 0); Adduct a2(1, 2, 123.456, "NH4", -0.3453, 0); Compomer c,d; c.add(a1, Compomer::RIGHT); d.add(a1, Compomer::RIGHT); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::RIGHT), false); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::RIGHT), true); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::LEFT), true); // this should not change the result c.add(a1, Compomer::RIGHT); d.add(a1, Compomer::RIGHT); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::RIGHT), false); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::RIGHT), true); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::LEFT), true); // this neither c.add(a2, Compomer::LEFT); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::RIGHT), false); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::RIGHT), true); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::LEFT), true); } { Adduct a1(1, -2, 123.456f, "NH4", -0.3453f, 0); Adduct a2(1, 1, 1.007, "H1", -0.13f, 0); Adduct b1(1, 2, 1.007, "H1", -0.13, 0); Compomer c,d; c.add(a1, Compomer::RIGHT); c.add(a2, Compomer::RIGHT); d.add(b1, Compomer::RIGHT); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::RIGHT), true); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::LEFT), true); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::RIGHT), true); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::LEFT), false); } { Adduct a1(1, 3, 123.456, "NH4", -0.3453, 0); Adduct a2(1, 3, 1.007, "H1", -0.13, 0); Compomer c,d; c.add(a1, Compomer::RIGHT); d.add(a1, Compomer::LEFT); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::LEFT), false); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::RIGHT), true); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::RIGHT), false); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::LEFT), true); c.add(a1, Compomer::LEFT); c.add(a2, Compomer::RIGHT); d.add(a1, Compomer::LEFT); d.add(a2, Compomer::RIGHT); // C D //a1 a1a2 ; a1a1 a2 TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::LEFT), true); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::RIGHT), true); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::RIGHT), true); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::LEFT), true); c.add(a1, Compomer::RIGHT); d.add(a2, Compomer::LEFT); d.add(a1, Compomer::RIGHT); d.add(a1, Compomer::RIGHT); // C D //a1 a1a2a1 ; a1a1a2 a2a1a1 TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::LEFT), false); TEST_EQUAL(c.isConflicting(d,Compomer::RIGHT,Compomer::RIGHT), false); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::RIGHT), true); TEST_EQUAL(c.isConflicting(d,Compomer::LEFT,Compomer::LEFT), true); } } END_SECTION START_SECTION((void setID(const Size &id))) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((const Size& getID() const)) { Compomer c; c.setID(123); TEST_EQUAL(c.getID(), 123) } END_SECTION START_SECTION((const Int& getNetCharge() const)) { Compomer c(-123,1.23,-0.12); TEST_EQUAL(c.getNetCharge(), -123) } END_SECTION START_SECTION((const double& getMass() const)) { Compomer c(1,-123.12, 0.23); TEST_REAL_SIMILAR(c.getMass(), -123.12) } END_SECTION START_SECTION((const Int& getPositiveCharges() const)) { Compomer c; Adduct a1(3, -2, 123.456, "NH4", -0.3453, 0); Adduct a2(6, 1, 1.007, "H1", -0.13, 0); c.add(a1, Compomer::RIGHT); c.add(a2, Compomer::RIGHT); TEST_EQUAL(c.getPositiveCharges(), 6) } END_SECTION START_SECTION((const Int& getNegativeCharges() const)) { Compomer c; Adduct a1(3, -2, 123.456, "NH4", -0.3453, 0); Adduct a2(6, 1, 1.007, "H1", -0.13, 0); c.add(a1, Compomer::RIGHT); c.add(a2, Compomer::RIGHT); TEST_EQUAL(c.getNegativeCharges(), 6) } END_SECTION START_SECTION((const double& getLogP() const)) { Compomer c(1,1,-123.12); TEST_REAL_SIMILAR(c.getLogP(), -123.12) } END_SECTION START_SECTION((const double& getRTShift() const)) { Compomer c(1,1,-123.12); Adduct a(123, 43, 123.456, "S", -0.3453, -10.12); c.add(a,0); TEST_REAL_SIMILAR(c.getRTShift(), 435.16) } END_SECTION START_SECTION((StringList getLabels(const UInt side) const)) { Compomer c(1,1,-123.12); TEST_EQUAL(c.getLabels(0).size(), 0) Adduct a(123, 43, 123.456, "S", -0.3453, -10.12, "testlabel"); c.add(a,0); TEST_EQUAL(c.getLabels(0).size(), 1) TEST_EQUAL(c.getLabels(1).size(), 0) } END_SECTION START_SECTION((String getAdductsAsString() const)) { Adduct a1(1, 2, 123.456f, "NH4", -0.3453f, 0); Adduct a2(1, -1, 1.007, "H1", -0.13, 0); Compomer c; c.add(a1, Compomer::RIGHT); c.add(a2, Compomer::RIGHT); TEST_EQUAL(c.getAdductsAsString(), "() --> (H-1H8N2)"); c.add(a1, Compomer::LEFT); TEST_EQUAL(c.getAdductsAsString(), "(H8N2) --> (H-1H8N2)"); } END_SECTION START_SECTION((String getAdductsAsString(UInt side) const)) { Adduct a1(1, 2, 123.456f, "NH4", -0.3453f, 0); Adduct a2(1, -1, 1.007, "H1", -0.13, 0); Compomer c; c.add(a1, Compomer::RIGHT); c.add(a2, Compomer::RIGHT); TEST_EQUAL(c.getAdductsAsString(Compomer::LEFT), ""); TEST_EQUAL(c.getAdductsAsString(Compomer::RIGHT), "H-1H8N2"); c.add(a1, Compomer::LEFT); TEST_EQUAL(c.getAdductsAsString(Compomer::LEFT), "H8N2"); TEST_EQUAL(c.getAdductsAsString(Compomer::RIGHT), "H-1H8N2"); } END_SECTION START_SECTION((const CompomerComponents& getComponent() const)) { Adduct a1(1, 2, 123.456f, "NH4", -0.3453f, 0); Adduct a2(1, -1, 1.007, "H1", -0.13, 0); Compomer c; Compomer::CompomerComponents comp(2); TEST_EQUAL(c.getComponent()==comp, true); c.add(a1, Compomer::RIGHT); c.add(a2, Compomer::RIGHT); c.add(a1, Compomer::LEFT); comp[Compomer::RIGHT][a1.getFormula()] = a1; comp[Compomer::RIGHT][a2.getFormula()] = a2; comp[Compomer::LEFT][a1.getFormula()] = a1; TEST_EQUAL(c.getComponent()==comp, true); } END_SECTION START_SECTION((Compomer removeAdduct(const Adduct& a) const)) { Adduct a1(1, 2, 123.456, "NH4", -0.3453, 0); Adduct a2(1, -1, 1.007, "H1", -0.13, 0); Compomer c; c.add(a1, Compomer::RIGHT); c.add(a2, Compomer::RIGHT); c.add(a1, Compomer::LEFT); Compomer tmp = c.removeAdduct(a1); TEST_EQUAL(tmp.getAdductsAsString(), "() --> (H-1)"); } END_SECTION START_SECTION((Compomer removeAdduct(const Adduct& a, const UInt side) const)) { Adduct a1(1, 2, 123.456, "NH4", -0.3453, 0); Adduct a2(1, -1, 1.007, "H1", -0.13, 0); Compomer c; c.add(a1, Compomer::RIGHT); c.add(a2, Compomer::RIGHT); c.add(a1, Compomer::LEFT); Compomer tmp = c.removeAdduct(a1, Compomer::RIGHT); TEST_EQUAL(tmp.getAdductsAsString(), "(H8N2) --> (H-1)"); tmp = c.removeAdduct(a1, Compomer::LEFT); TEST_EQUAL(tmp.getAdductsAsString(), "() --> (H-1H8N2)"); } END_SECTION START_SECTION((void add(const CompomerSide& add_side, UInt side))) { Adduct a1(1, 2, 123.456, "NH4", -0.3453, 0); Adduct a2(1, -1, 1.007, "H1", -0.13, 0); Compomer c; c.add(a1, Compomer::RIGHT); c.add(a2, Compomer::RIGHT); c.add(a1, Compomer::LEFT); TEST_EQUAL(c.getAdductsAsString(), "(H8N2) --> (H-1H8N2)"); Compomer tmp = c; tmp.add(c.getComponent()[Compomer::RIGHT], Compomer::RIGHT); TEST_EQUAL(tmp.getAdductsAsString(), "(H8N2) --> (H-2H16N4)"); tmp.add(c.getComponent()[Compomer::RIGHT], Compomer::LEFT); TEST_EQUAL(tmp.getAdductsAsString(), "(H-1H16N4) --> (H-2H16N4)"); } END_SECTION START_SECTION((bool isSingleAdduct(Adduct &a, const UInt side) const)) Adduct a1(1, 2, 123.456, "NH4", -0.3453, 0); Adduct a2(1, -1, 1.007, "H1", -0.13, 0); Compomer c; c.add(a1, Compomer::RIGHT); c.add(a2, Compomer::RIGHT); c.add(a1, Compomer::LEFT); TEST_EQUAL(c.isSingleAdduct(a1,Compomer::LEFT), true); TEST_EQUAL(c.isSingleAdduct(a2,Compomer::LEFT), false); TEST_EQUAL(c.isSingleAdduct(a1,Compomer::RIGHT), false); TEST_EQUAL(c.isSingleAdduct(a2,Compomer::RIGHT), false); END_SECTION START_SECTION([EXTRA] std::hash<Compomer>) { // Test that equal Compomers produce equal hashes Compomer c1(34, 45.32, 12.34); Adduct a1(123, 3, 123.456, "S", -0.3453, 0); Adduct b1(3, -2, 1.456, "H", -0.13, 0); c1.setID(434); c1.add(a1, Compomer::RIGHT); c1.add(b1, Compomer::LEFT); Compomer c2(c1); // Copy constructor TEST_EQUAL(c1 == c2, true); TEST_EQUAL(std::hash<Compomer>{}(c1), std::hash<Compomer>{}(c2)); // Test that different Compomers (typically) produce different hashes Compomer c3(34, 45.32, 12.34); c3.setID(435); // Different ID c3.add(a1, Compomer::RIGHT); c3.add(b1, Compomer::LEFT); TEST_EQUAL(c1 == c3, false); // Note: Different objects may have the same hash (collision), but it's unlikely // We test that the hash function at least compiles and runs without error // Test use in unordered_set std::unordered_set<Compomer> compomer_set; compomer_set.insert(c1); compomer_set.insert(c2); // Same as c1, should not increase size compomer_set.insert(c3); TEST_EQUAL(compomer_set.size(), 2); TEST_EQUAL(compomer_set.count(c1), 1); TEST_EQUAL(compomer_set.count(c2), 1); TEST_EQUAL(compomer_set.count(c3), 1); // Test use in unordered_map std::unordered_map<Compomer, int> compomer_map; compomer_map[c1] = 1; compomer_map[c3] = 3; TEST_EQUAL(compomer_map.size(), 2); TEST_EQUAL(compomer_map[c1], 1); TEST_EQUAL(compomer_map[c2], 1); // c2 == c1, so should get same value TEST_EQUAL(compomer_map[c3], 3); // Test empty Compomer hash Compomer empty1; Compomer empty2; TEST_EQUAL(std::hash<Compomer>{}(empty1), std::hash<Compomer>{}(empty2)); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MultiplexIsotopicPeakPattern_test.cpp
.cpp
2,817
80
// 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/MultiplexDeltaMasses.h> #include <OpenMS/FEATUREFINDER/MultiplexIsotopicPeakPattern.h> using namespace OpenMS; START_TEST(MultiplexIsotopicPeakPattern, "$Id$") MultiplexDeltaMasses mass_shifts; mass_shifts.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(0,"no_label")); mass_shifts.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(6.031817,"Arg6")); MultiplexIsotopicPeakPattern* nullPointer = nullptr; MultiplexIsotopicPeakPattern* ptr; START_SECTION(MultiplexIsotopicPeakPattern(int c, int ppp, MultiplexDeltaMasses ms, int msi)) MultiplexIsotopicPeakPattern pattern(2, 4, mass_shifts, 3); TEST_EQUAL(pattern.getCharge(), 2); ptr = new MultiplexIsotopicPeakPattern(2, 4, mass_shifts, 3); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION MultiplexIsotopicPeakPattern pattern(2, 4, mass_shifts, 3); START_SECTION(int getCharge() const) TEST_EQUAL(pattern.getCharge(), 2); END_SECTION START_SECTION(int getPeaksPerPeptide() const) TEST_EQUAL(pattern.getPeaksPerPeptide(), 4); END_SECTION START_SECTION(std::vector<double> getMassShifts() const) TEST_EQUAL(pattern.getMassShifts().getDeltaMasses()[0].delta_mass, 0); TEST_EQUAL(pattern.getMassShifts().getDeltaMasses()[1].delta_mass, 6.031817); END_SECTION START_SECTION(int getMassShiftIndex() const) TEST_EQUAL(pattern.getMassShiftIndex(), 3); END_SECTION START_SECTION(unsigned getMassShiftCount() const) TEST_EQUAL(pattern.getMassShiftCount(), 2); END_SECTION START_SECTION(double getMassShiftAt(int i) const) TEST_EQUAL(pattern.getMassShiftAt(0), 0); TEST_EQUAL(pattern.getMassShiftAt(1), 6.031817); END_SECTION /*START_SECTION(double getMZShiftAt(int i) const) TEST_REAL_SIMILAR(pattern.getMZShiftAt(0), -0.501677); TEST_REAL_SIMILAR(pattern.getMZShiftAt(1), 0); TEST_REAL_SIMILAR(pattern.getMZShiftAt(2), 0.501677); TEST_REAL_SIMILAR(pattern.getMZShiftAt(3), 1.00335); TEST_REAL_SIMILAR(pattern.getMZShiftAt(4), 1.50503); TEST_REAL_SIMILAR(pattern.getMZShiftAt(5), 2.51423); TEST_REAL_SIMILAR(pattern.getMZShiftAt(6), 3.01591); TEST_REAL_SIMILAR(pattern.getMZShiftAt(7), 3.51759); TEST_REAL_SIMILAR(pattern.getMZShiftAt(8), 4.01926); TEST_REAL_SIMILAR(pattern.getMZShiftAt(9), 4.52094); END_SECTION START_SECTION(unsigned getMZShiftCount() const) TEST_EQUAL(pattern.getMZShiftCount(), 10); END_SECTION*/ END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ProtXMLFile_test.cpp
.cpp
4,732
119
// 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/FORMAT/ProtXMLFile.h> /////////////////////////// #include <OpenMS/CONCEPT/FuzzyStringComparator.h> using namespace OpenMS; using namespace std; START_TEST(ProtXMLFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ProtXMLFile* ptr = nullptr; ProtXMLFile* nullPointer = nullptr; ProtXMLFile file; START_SECTION(ProtXMLFile()) ptr = new ProtXMLFile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~ProtXMLFile()) delete ptr; END_SECTION START_SECTION(void load(const String &filename, ProteinIdentification &protein_ids, PeptideIdentification &peptide_ids)) { ProtXMLFile f; ProteinIdentification proteins; PeptideIdentification peptides; String prot_file; StringList ids = ListUtils::create<String>("16627578304933075941,13229490167902618598"); // we do this twice, just to check that members are correctly reset etc.. for (Int i=0;i<2;++i) { prot_file = OPENMS_GET_TEST_DATA_PATH("ProtXMLFile_input_1.protXML"); f.load(prot_file, proteins, peptides); // groups TEST_EQUAL(proteins.getProteinGroups().size(), 7); TEST_EQUAL(proteins.getProteinGroups()[0].probability, 0.9990); TEST_EQUAL(proteins.getProteinGroups()[0].accessions.size(), 1); TEST_EQUAL(proteins.getProteinGroups()[3].accessions.size(), 2); TEST_EQUAL(proteins.getProteinGroups()[3].accessions[0], "P01876|IGHA1_HUMAN"); TEST_EQUAL(proteins.getProteinGroups()[3].accessions[1], "P01877|IGHA2_HUMAN"); TEST_EQUAL(proteins.getProteinGroups()[6].probability, 0.2026); TEST_EQUAL(proteins.getProteinGroups()[6].accessions.size(), 1); TEST_EQUAL(proteins.getIndistinguishableProteins().size(), 7); TEST_EQUAL(proteins.getIndistinguishableProteins()[0].accessions.size(), 1); TEST_EQUAL(proteins.getIndistinguishableProteins()[3].accessions.size(), 2); TEST_EQUAL(proteins.getIndistinguishableProteins()[3].accessions[0], "P01876|IGHA1_HUMAN"); TEST_EQUAL(proteins.getIndistinguishableProteins()[3].accessions[1], "P01877|IGHA2_HUMAN"); TEST_EQUAL(proteins.getIndistinguishableProteins()[6].accessions.size(), 1); // proteins TEST_EQUAL(proteins.getHits().size(), 9); TEST_EQUAL(proteins.getHits()[0].getAccession(), "P02787|TRFE_HUMAN"); TEST_EQUAL(proteins.getHits()[0].getCoverage(), 8.6); TEST_EQUAL(proteins.getHits()[0].getScore(), 0.9990); // this one is indistinguishable... therefore no coverage (but the score // got transferred from the "leader" protein): TEST_EQUAL(proteins.getHits()[6].getAccession(), "P00739|HPTR_HUMAN"); TEST_EQUAL(proteins.getHits()[6].getCoverage(), -1); TEST_EQUAL(proteins.getHits()[6].getScore(), 0.2663); TEST_EQUAL(proteins.getHits()[8].getAccession(), "P04217|A1BG_HUMAN"); TEST_EQUAL(proteins.getHits()[8].getCoverage(), 2.0); TEST_EQUAL(proteins.getHits()[8].getScore(), 0.2026); // peptides TEST_EQUAL(peptides.getHits().size(), 16); AASequence aa_seq = AASequence::fromString("MYLGYEYVTAIR"); TEST_EQUAL(peptides.getHits()[0].getSequence(), aa_seq); TEST_EQUAL(peptides.getHits()[0].getCharge(), 2); TEST_EQUAL(peptides.getHits()[0].getScore(), 0.8633); set<String> protein_accessions = peptides.getHits()[0].extractProteinAccessionsSet(); TEST_EQUAL(protein_accessions.size(), 1); TEST_EQUAL(*protein_accessions.begin(), "P02787|TRFE_HUMAN"); TEST_EQUAL(peptides.getHits()[0].getMetaValue("is_unique"), true); TEST_EQUAL(peptides.getHits()[0].getMetaValue("is_contributing"), true); // load 2 nd file and prot_file = OPENMS_GET_TEST_DATA_PATH("ProtXMLFile_input_2.protXML"); } } END_SECTION START_SECTION(void store(const String &filename, const ProteinIdentification &protein_ids, const PeptideIdentification &peptide_ids, const String &document_id="")) { ProtXMLFile f; ProteinIdentification proteins; PeptideIdentification peptides; TEST_EXCEPTION(Exception::NotImplemented, f.store("notimplemented.protXML", proteins, peptides )) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IDDecoyProbability_test.cpp
.cpp
1,700
76
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Sven Nahnsen$ // $Authors: Sven Nahnsen$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/ID/IDDecoyProbability.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(IDDecoyProbability, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// IDDecoyProbability* ptr = 0; IDDecoyProbability* null_ptr = 0; START_SECTION(IDDecoyProbability()) { ptr = new IDDecoyProbability(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~IDDecoyProbability()) { delete ptr; } END_SECTION START_SECTION((IDDecoyProbability(const IDDecoyProbability &rhs))) { // TODO } END_SECTION START_SECTION((virtual ~IDDecoyProbability())) { // TODO } END_SECTION START_SECTION((IDDecoyProbability& operator=(const IDDecoyProbability &rhs))) { // TODO } END_SECTION START_SECTION((void apply(std::vector< PeptideIdentification > &prob_ids, const std::vector< PeptideIdentification > &fwd_ids, const std::vector< PeptideIdentification > &rev_ids))) { // TODO } END_SECTION START_SECTION((void apply(std::vector< PeptideIdentification > &ids))) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MasstraceCorrelator_test.cpp
.cpp
10,364
323
// 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/MasstraceCorrelator.h> /////////////////////////// #include <OpenMS/test_config.h> #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/ANALYSIS/OPENSWATH/MRMScoring.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> using namespace OpenMS; using namespace std; class MasstraceCorrelator_facade : MasstraceCorrelator { public: void matchMassTraces_(const MasstracePointsType& hull_points1, const MasstracePointsType& hull_points2, std::vector<double>& vec1, std::vector<double>& vec2, double mindiff, double padEnds = true) { MasstraceCorrelator::matchMassTraces_(hull_points1, hull_points2, vec1, vec2, mindiff, padEnds); } }; START_TEST(CorrelateMasstraces, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION((virtual void matchMassTraces_())) { MasstraceCorrelator_facade mtcorr; static const double arr1[] = {0,1,3,5,2,0}; static const double arr2[] = {1,3,5,2,0,0}; static const double arr3[] = {0,1,2,3,4,5}; static const double arr4[] = {0,1,2,4,5,6}; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); std::vector<double> data2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); std::vector<double> rt1 (arr3, arr3 + sizeof(arr3) / sizeof(arr3[0]) ); std::vector<double> rt2 (arr4, arr4 + sizeof(arr4) / sizeof(arr4[0]) ); std::vector<double> vec1; std::vector<double> vec2; std::vector<std::pair<double, double> > data1_2d; std::vector<std::pair<double, double> > data2_2d; data1_2d.clear(); data2_2d.clear(); for(Size i = 0; i < data1.size(); i++) { data1_2d.push_back(std::make_pair(rt1[i], data1[i]) ); data2_2d.push_back(std::make_pair(rt2[i], data2[i]) ); } vec1.clear(); vec2.clear(); mtcorr.matchMassTraces_(data1_2d, data2_2d, vec1, vec2, 0.1); TEST_EQUAL(vec1.size(), 7); TEST_EQUAL(vec2.size(), 7); TEST_EQUAL(vec1[0], 0); TEST_EQUAL(vec1[1], 1); TEST_EQUAL(vec1[2], 3); TEST_EQUAL(vec1[3], 5); TEST_EQUAL(vec1[4], 2); TEST_EQUAL(vec1[5], 0); TEST_EQUAL(vec1[6], 0); TEST_EQUAL(vec2[0], 1); TEST_EQUAL(vec2[1], 3); TEST_EQUAL(vec2[2], 5); TEST_EQUAL(vec2[3], 0); TEST_EQUAL(vec2[4], 2); TEST_EQUAL(vec2[5], 0); TEST_EQUAL(vec2[6], 0); vec1.clear(); vec2.clear(); mtcorr.matchMassTraces_(data2_2d, data1_2d, vec2, vec1, 0.1); TEST_EQUAL(vec1.size(), 7); TEST_EQUAL(vec2.size(), 7); TEST_EQUAL(vec1[0], 0); TEST_EQUAL(vec1[1], 1); TEST_EQUAL(vec1[2], 3); TEST_EQUAL(vec1[3], 5); TEST_EQUAL(vec1[4], 2); TEST_EQUAL(vec1[5], 0); TEST_EQUAL(vec1[6], 0); TEST_EQUAL(vec2[0], 1); TEST_EQUAL(vec2[1], 3); TEST_EQUAL(vec2[2], 5); TEST_EQUAL(vec2[3], 0); TEST_EQUAL(vec2[4], 2); TEST_EQUAL(vec2[5], 0); TEST_EQUAL(vec2[6], 0); vec1.clear(); vec2.clear(); mtcorr.matchMassTraces_(data1_2d, data2_2d, vec1, vec2, 1.5); TEST_EQUAL(vec1.size(), 6); TEST_EQUAL(vec2.size(), 6); TEST_EQUAL(vec1[0], 0); TEST_EQUAL(vec1[1], 1); TEST_EQUAL(vec1[2], 3); TEST_EQUAL(vec1[3], 5); TEST_EQUAL(vec1[4], 2); TEST_EQUAL(vec1[5], 0); TEST_EQUAL(vec2[0], 1); TEST_EQUAL(vec2[1], 3); TEST_EQUAL(vec2[2], 5); TEST_EQUAL(vec2[3], 2); TEST_EQUAL(vec2[4], 0); TEST_EQUAL(vec2[5], 0); } END_SECTION START_SECTION((virtual void match_elution_arrays_no_padding())) { MasstraceCorrelator_facade mtcorr; static const double arr1[] = {0,1,3,5,2,0}; static const double arr2[] = {1,3,5,2,0,0}; static const double arr3[] = {0,1,2,3,4,5}; static const double arr4[] = {-1,1,2,4,5,6}; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); std::vector<double> data2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); std::vector<double> rt1 (arr3, arr3 + sizeof(arr3) / sizeof(arr3[0]) ); std::vector<double> rt2 (arr4, arr4 + sizeof(arr4) / sizeof(arr4[0]) ); std::vector<double> vec1; std::vector<double> vec2; std::vector<std::pair<double, double> > data1_2d; std::vector<std::pair<double, double> > data2_2d; data1_2d.clear(); data2_2d.clear(); for(Size i = 0; i < data1.size(); i++) { data1_2d.push_back(std::make_pair(rt1[i], data1[i]) ); data2_2d.push_back(std::make_pair(rt2[i], data2[i]) ); } vec1.clear(); vec2.clear(); TEST_EQUAL(vec1.size(), 0); TEST_EQUAL(vec2.size(), 0); // if we do not pad the ends, this means that we do not add zeros to the first vector that is shorter in RT bool pad_ends = false; mtcorr.matchMassTraces_(data1_2d, data2_2d, vec1, vec2, 0.1, pad_ends); TEST_EQUAL(vec1.size(), 5); TEST_EQUAL(vec2.size(), 5); TEST_EQUAL(vec1[0], 1); TEST_EQUAL(vec1[1], 3); TEST_EQUAL(vec1[2], 5); TEST_EQUAL(vec1[3], 2); TEST_EQUAL(vec1[4], 0); TEST_EQUAL(vec2[0], 3); TEST_EQUAL(vec2[1], 5); TEST_EQUAL(vec2[2], 0); TEST_EQUAL(vec2[3], 2); TEST_EQUAL(vec2[4], 0); vec1.clear(); vec2.clear(); TEST_EQUAL(vec1.size(), 0); TEST_EQUAL(vec2.size(), 0); // if we do pad the ends, this means that we do add zeros to the first vector that is shorter in RT mtcorr.matchMassTraces_(data1_2d, data2_2d, vec1, vec2, 0.1, true); TEST_EQUAL(vec1.size(), 8); TEST_EQUAL(vec2.size(), 8); TEST_EQUAL(vec1[0], 0); // -1 TEST_EQUAL(vec1[1], 0); // 0 TEST_EQUAL(vec1[2], 1); // 1 TEST_EQUAL(vec1[3], 3); // 2 TEST_EQUAL(vec1[4], 5); // 3 TEST_EQUAL(vec1[5], 2); // 4 TEST_EQUAL(vec1[6], 0); // 5 TEST_EQUAL(vec1[7], 0); // 6 TEST_EQUAL(vec2[0], 1); // -1 TEST_EQUAL(vec2[1], 0); // 0 TEST_EQUAL(vec2[2], 3); // 1 TEST_EQUAL(vec2[3], 5); // 2 TEST_EQUAL(vec2[4], 0); // 3 TEST_EQUAL(vec2[5], 2); // 4 TEST_EQUAL(vec2[6], 0); // 5 TEST_EQUAL(vec2[7], 0); // 6 } END_SECTION START_SECTION((virtual void scoreHullpoints())) { OpenMS::MasstraceCorrelator mtcorr; static const double arr1[] = {0,1,3,5,2,0}; static const double arr2[] = {1,3,5,2,0,0}; static const double arr3[] = {0,1,2,3,4,5}; static const double arr4[] = {0,1,2,4,5,6}; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); std::vector<double> data2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); std::vector<double> rt1 (arr3, arr3 + sizeof(arr3) / sizeof(arr3[0]) ); std::vector<double> rt2 (arr4, arr4 + sizeof(arr4) / sizeof(arr4[0]) ); std::vector<std::pair<double, double> > data1_2d; std::vector<std::pair<double, double> > data2_2d; OpenSwath::Scoring::standardize_data(data1); OpenSwath::Scoring::standardize_data(data2); for(Size i = 0; i < data1.size(); i++) { data1_2d.push_back( std::make_pair(rt1[i], data1[i]) ); data2_2d.push_back( std::make_pair(rt1[i], data2[i]) ); } OpenSwath::Scoring::XCorrArrayType result = OpenSwath::Scoring::calculateCrossCorrelation(data1, data2, 2, 1); for(OpenSwath::Scoring::XCorrArrayType::iterator it = result.begin(); it != result.end(); ++it) { it->second = it->second / 6.0; } TEST_EQUAL (result.data[0].first, -2); TEST_EQUAL (result.data[1].first, -1); TEST_EQUAL (result.data[2].first, 0); TEST_EQUAL (result.data[3].first, 1); TEST_EQUAL (result.data[4].first, 2); TEST_REAL_SIMILAR (result.data[4].second, -0.7374631); // .find( 2)-> TEST_REAL_SIMILAR (result.data[3].second, -0.567846); // .find( 1)-> TEST_REAL_SIMILAR (result.data[2].second, 0.4159292); // .find( 0)-> TEST_REAL_SIMILAR (result.data[1].second, 0.8215339); // .find(-1)-> TEST_REAL_SIMILAR (result.data[0].second, 0.15634218); // .find(-2)-> double min_pearson_score = -1.1; int maxlag = data1_2d.size(); int lag; double lag_intensity; double pearson_score; mtcorr.scoreHullpoints(data1_2d, data2_2d, lag, lag_intensity, pearson_score, min_pearson_score, maxlag); TEST_EQUAL(lag, -1); TEST_REAL_SIMILAR(lag_intensity, 0.821534); TEST_REAL_SIMILAR(pearson_score, 0.41593); // now we use different RT data for the 2nd data array data1_2d.clear(); data2_2d.clear(); for(Size i = 0; i < data1.size(); i++) { data1_2d.push_back( std::make_pair(rt1[i], data1[i]) ); data2_2d.push_back( std::make_pair(rt2[i], data2[i]) ); } // if we allow for an RT difference of more than 1, we should get the same result as above mtcorr.scoreHullpoints(data1_2d, data2_2d, lag, lag_intensity, pearson_score, min_pearson_score, maxlag, 1.5); TEST_EQUAL(lag, -1); TEST_REAL_SIMILAR(lag_intensity, 0.821534); TEST_REAL_SIMILAR(pearson_score, 0.41593); // if the allowed difference in RT is less than 1, the algorithm will substitute zeros mtcorr.scoreHullpoints(data1_2d, data2_2d, lag, lag_intensity, pearson_score, min_pearson_score, maxlag, 0.1); TEST_EQUAL(lag, -1); TEST_REAL_SIMILAR(lag_intensity, 0.625368); TEST_REAL_SIMILAR(pearson_score, 0.405604); } END_SECTION START_SECTION((virtual void createPseudoSpectra())) { ConsensusMap masstraces; ConsensusXMLFile().load(OPENMS_GET_TEST_DATA_PATH("Masstraces_Testdata.consensusXML"), masstraces); MSExperiment pseudo_spectra; masstraces.sortByIntensity(true); OpenMS::MasstraceCorrelator mtcorr; mtcorr.createPseudoSpectra(masstraces, pseudo_spectra, 0, 0.7, 1, 3); TEST_EQUAL(pseudo_spectra.size(), 3); TEST_EQUAL(pseudo_spectra[1].size(), 1); TEST_REAL_SIMILAR(pseudo_spectra[1].getRT(), 4203.0); TEST_REAL_SIMILAR(pseudo_spectra[1][0].getMZ(), 668.5); pseudo_spectra.clear(true); mtcorr.createPseudoSpectra(masstraces, pseudo_spectra, 1, 0.7, 1, 3); TEST_EQUAL(pseudo_spectra.size(), 2); TEST_EQUAL(pseudo_spectra[0].size(), 2); TEST_EQUAL(pseudo_spectra[1].size(), 2); TEST_REAL_SIMILAR(pseudo_spectra[0].getRT(), 5201.0); TEST_REAL_SIMILAR(pseudo_spectra[0][0].getMZ(), 568.5); TEST_REAL_SIMILAR(pseudo_spectra[1].getRT(), 5203.0); TEST_REAL_SIMILAR(pseudo_spectra[1][0].getMZ(), 768.5); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MapAlignmentAlgorithmKD_test.cpp
.cpp
1,434
50
// 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/MAPMATCHING/MapAlignmentAlgorithmKD.h> using namespace OpenMS; using namespace std; START_TEST(MapAlignmentAlgorithmKD, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MapAlignmentAlgorithmKD* ptr = nullptr; MapAlignmentAlgorithmKD* nullPointer = nullptr; START_SECTION((MapAlignmentAlgorithmKD(Size num_maps, const Param& param))) ptr = new MapAlignmentAlgorithmKD(42, Param()); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~MapAlignmentAlgorithmKD())) delete ptr; END_SECTION START_SECTION((void addRTFitData(const KDTreeFeatureMaps& kd_data))) NOT_TESTABLE; END_SECTION START_SECTION((void fitLOWESS())) NOT_TESTABLE; END_SECTION START_SECTION((void transform(KDTreeFeatureMaps& kd_data) const)) NOT_TESTABLE; END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BiGaussModel_test.cpp
.cpp
5,850
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/BiGaussModel.h> /////////////////////////// START_TEST(BiGaussModel, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace OpenMS::Math; using std::stringstream; // default ctor BiGaussModel* ptr = nullptr; BiGaussModel* nullPointer = nullptr; START_SECTION((BiGaussModel())) ptr = new BiGaussModel(); TEST_EQUAL(ptr->getName(), "BiGaussModel") TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION // destructor START_SECTION((virtual ~BiGaussModel())) delete ptr; END_SECTION START_SECTION( static BaseModel* create() ) BaseModel* ptr = new BiGaussModel(); TEST_EQUAL(ptr->getName(), "BiGaussModel") TEST_NOT_EQUAL(ptr, nullPointer) delete ptr; END_SECTION // assignment operator START_SECTION((virtual BiGaussModel& operator=(const BiGaussModel &source))) BiGaussModel bgm1; bgm1.setScalingFactor(10.0); bgm1.setInterpolationStep(0.3); Param tmp; tmp.setValue("bounding_box:min", 678.9); tmp.setValue("bounding_box:max", 789.0); tmp.setValue("statistics:mean", 680.1 ); tmp.setValue("statistics:variance1", 2.0); tmp.setValue("statistics:variance2", 5.0 ); bgm1.setParameters(tmp); BiGaussModel bgm2; bgm2 = bgm1; BiGaussModel bgm3; bgm3.setScalingFactor(10.0); bgm3.setInterpolationStep(0.3); bgm3.setParameters(tmp); bgm1 = BiGaussModel(); TEST_EQUAL(bgm3.getParameters(), bgm2.getParameters()) END_SECTION // copy ctor START_SECTION((BiGaussModel(const BiGaussModel& source))) BiGaussModel bgm1; BasicStatistics<> stat; bgm1.setScalingFactor(10.0); bgm1.setInterpolationStep(0.3); Param tmp; tmp.setValue("bounding_box:min", 678.9); tmp.setValue("bounding_box:max", 789.0); tmp.setValue("statistics:mean", 680.1 ); tmp.setValue("statistics:variance1", 2.0); tmp.setValue("statistics:variance2", 5.0 ); bgm1.setParameters(tmp); BiGaussModel bgm2(bgm1); BiGaussModel bgm3; bgm3.setScalingFactor(10.0); bgm3.setInterpolationStep(0.3); bgm3.setParameters(tmp); bgm1 = BiGaussModel(); TEST_EQUAL(bgm3.getParameters(), bgm2.getParameters()) END_SECTION START_SECTION([EXTRA] DefaultParamHandler::setParameters(...)) TOLERANCE_ABSOLUTE(0.001) BiGaussModel bgm1; Param tmp; tmp.setValue("bounding_box:min", 678.9); tmp.setValue("bounding_box:max", 789.0); tmp.setValue("statistics:mean", 680.1 ); tmp.setValue("statistics:variance1", 2.0); tmp.setValue("statistics:variance2", 5.0 ); bgm1.setParameters(tmp); bgm1.setOffset(680.0); BiGaussModel bgm2; bgm2.setParameters(bgm1.getParameters()); TEST_REAL_SIMILAR(bgm1.getCenter(), 681.2) std::vector<Peak1D> dpa1; std::vector<Peak1D> dpa2; bgm1.getSamples(dpa1); bgm2.getSamples(dpa2); TOLERANCE_ABSOLUTE(0.0001) 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((void setOffset(CoordinateType offset))) BiGaussModel bgm1; Param tmp; tmp.setValue("bounding_box:min", 678.9); tmp.setValue("bounding_box:max", 789.0); tmp.setValue("statistics:mean", 680.1 ); tmp.setValue("statistics:variance1", 2.0); tmp.setValue("statistics:variance2", 5.0 ); bgm1.setParameters(tmp); bgm1.setOffset(680.9); BiGaussModel bgm2; tmp.setValue("bounding_box:min", 680.9); tmp.setValue("bounding_box:max", 791.0); tmp.setValue("statistics:mean", 682.1 ); tmp.setValue("statistics:variance1", 2.0); tmp.setValue("statistics:variance2", 5.0 ); bgm2.setParameters(tmp); TEST_EQUAL(bgm1.getParameters(), bgm2.getParameters()) TEST_REAL_SIMILAR(bgm1.getCenter(), bgm2.getCenter()) TEST_REAL_SIMILAR(bgm1.getCenter(), 682.1) std::vector<Peak1D> dpa1; std::vector<Peak1D> dpa2; bgm1.getSamples(dpa1); bgm2.getSamples(dpa2); TOLERANCE_ABSOLUTE(0.001) 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()) } tmp.setValue("bounding_box:min", -4.0); tmp.setValue("bounding_box:max", 4.001); tmp.setValue("statistics:mean", 0.0 ); tmp.setValue("statistics:variance1", 0.81); tmp.setValue("statistics:variance2", 0.81 ); bgm1.setParameters(tmp); bgm1.setOffset(0.123); TEST_REAL_SIMILAR(bgm1.getCenter(), 4.123) TOLERANCE_ABSOLUTE(0.001) TEST_REAL_SIMILAR(bgm1.getIntensity(4.123), 0.4432692); TEST_REAL_SIMILAR(bgm1.getIntensity(4.223), bgm1.getIntensity(4.023)); TEST_REAL_SIMILAR(bgm1.getIntensity(3.123), bgm1.getIntensity(5.123)); END_SECTION START_SECTION( CoordinateType getCenter() const ) // already test above, but just for the sake of it TOLERANCE_ABSOLUTE(0.001) BiGaussModel bgm1; Param tmp; tmp.setValue("bounding_box:min", 678.9); tmp.setValue("bounding_box:max", 789.0); tmp.setValue("statistics:mean", 680.1 ); tmp.setValue("statistics:variance1", 2.0); tmp.setValue("statistics:variance2", 5.0 ); bgm1.setParameters(tmp); bgm1.setOffset(680.0); TEST_REAL_SIMILAR(bgm1.getCenter(), 681.2) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TMTEighteenPlexQuantitationMethod_test.cpp
.cpp
9,146
255
// 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/TMTEighteenPlexQuantitationMethod.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/Matrix.h> using namespace OpenMS; using namespace std; START_TEST(TMTEighteenPlexQuantitationMethod, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TMTEighteenPlexQuantitationMethod* ptr = nullptr; TMTEighteenPlexQuantitationMethod* null_ptr = nullptr; START_SECTION(TMTEighteenPlexQuantitationMethod()) { ptr = new TMTEighteenPlexQuantitationMethod(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~TMTEighteenPlexQuantitationMethod()) { delete ptr; } END_SECTION START_SECTION((const String& getMethodName() const )) { TMTEighteenPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getMethodName(), "tmt18plex") } END_SECTION START_SECTION((const IsobaricChannelList& getChannelInformation() const )) { TMTEighteenPlexQuantitationMethod quant_meth; IsobaricQuantitationMethod::IsobaricChannelList channel_list = quant_meth.getChannelInformation(); TEST_EQUAL(channel_list.size(), 18) ABORT_IF(channel_list.size() != 18) // 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, "") TEST_STRING_EQUAL(channel_list[4].description, "") TEST_STRING_EQUAL(channel_list[5].description, "") TEST_STRING_EQUAL(channel_list[6].description, "") TEST_STRING_EQUAL(channel_list[7].description, "") TEST_STRING_EQUAL(channel_list[8].description, "") TEST_STRING_EQUAL(channel_list[9].description, "") TEST_STRING_EQUAL(channel_list[10].description, "") TEST_STRING_EQUAL(channel_list[11].description, "") TEST_STRING_EQUAL(channel_list[12].description, "") TEST_STRING_EQUAL(channel_list[13].description, "") TEST_STRING_EQUAL(channel_list[14].description, "") TEST_STRING_EQUAL(channel_list[15].description, "") TEST_STRING_EQUAL(channel_list[16].description, "") TEST_STRING_EQUAL(channel_list[17].description, "") // check masses&co TEST_EQUAL(channel_list[0].name, "126") TEST_EQUAL(channel_list[0].id, 0) TEST_EQUAL(channel_list[0].center, 126.127726) TEST_EQUAL(channel_list[1].name, "127N") TEST_EQUAL(channel_list[1].id, 1) TEST_EQUAL(channel_list[1].center, 127.124761) TEST_EQUAL(channel_list[2].name, "127C") TEST_EQUAL(channel_list[2].id, 2) TEST_EQUAL(channel_list[2].center, 127.131081) TEST_EQUAL(channel_list[3].name, "128N") TEST_EQUAL(channel_list[3].id, 3) TEST_EQUAL(channel_list[3].center, 128.128116) TEST_EQUAL(channel_list[4].name, "128C") TEST_EQUAL(channel_list[4].id, 4) TEST_EQUAL(channel_list[4].center, 128.134436) TEST_EQUAL(channel_list[5].name, "129N") TEST_EQUAL(channel_list[5].id, 5) TEST_EQUAL(channel_list[5].center, 129.131471) TEST_EQUAL(channel_list[6].name, "129C") TEST_EQUAL(channel_list[6].id, 6) TEST_EQUAL(channel_list[6].center, 129.137790) TEST_EQUAL(channel_list[7].name, "130N") TEST_EQUAL(channel_list[7].id, 7) TEST_EQUAL(channel_list[7].center, 130.134825) TEST_EQUAL(channel_list[8].name, "130C") TEST_EQUAL(channel_list[8].id, 8) TEST_EQUAL(channel_list[8].center, 130.141145) TEST_EQUAL(channel_list[9].name, "131N") TEST_EQUAL(channel_list[9].id, 9) TEST_EQUAL(channel_list[9].center, 131.138180) TEST_EQUAL(channel_list[10].name, "131C") TEST_EQUAL(channel_list[10].id, 10) TEST_EQUAL(channel_list[10].center, 131.144500) TEST_EQUAL(channel_list[11].name, "132N") TEST_EQUAL(channel_list[11].id, 11) TEST_EQUAL(channel_list[11].center, 132.141535) TEST_EQUAL(channel_list[12].name, "132C") TEST_EQUAL(channel_list[12].id, 12) TEST_EQUAL(channel_list[12].center, 132.147855) TEST_EQUAL(channel_list[13].name, "133N") TEST_EQUAL(channel_list[13].id, 13) TEST_EQUAL(channel_list[13].center, 133.144890) TEST_EQUAL(channel_list[14].name, "133C") TEST_EQUAL(channel_list[14].id, 14) TEST_EQUAL(channel_list[14].center, 133.151210) TEST_EQUAL(channel_list[15].name, "134N") TEST_EQUAL(channel_list[15].id, 15) TEST_EQUAL(channel_list[15].center, 134.148245) TEST_EQUAL(channel_list[16].name, "134C") TEST_EQUAL(channel_list[16].id, 16) TEST_EQUAL(channel_list[16].center, 134.154565) TEST_EQUAL(channel_list[17].name, "135N") TEST_EQUAL(channel_list[17].id, 17) TEST_EQUAL(channel_list[17].center, 135.151600) for (const auto& channel : channel_list) { TEST_EQUAL(channel.affected_channels.size(), 8) } } END_SECTION START_SECTION((Size getNumberOfChannels() const )) { TMTEighteenPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getNumberOfChannels(), 18) } END_SECTION START_SECTION((virtual Matrix<double> getIsotopeCorrectionMatrix() const )) { double test_matrix[18][18] = {{0.9026, 0.0078, 0.0093, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, {0.0031, 0.8948, 0, 0.0082, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, {0.0909, 0, 0.8981, 0.0065, 0.0147, 0, 0.0013, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, {0.0002, 0.0941, 0.0035, 0.9014, 0, 0.0146, 0, 0.0013, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, {0.0032, 0, 0.0863, 0, 0.9113, 0.0128, 0.0259, 0, 0.0004, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, {0, 0.0033, 0.0001, 0.0813, 0.0034, 0.9025, 0, 0.0241, 0, 0.0003, 0, 0, 0, 0, 0, 0, 0, 0, }, {0, 0, 0.0027, 0, 0.0691, 0, 0.907, 0.0027, 0.031, 0, 0.0008, 0, 0, 0, 0, 0, 0, 0, }, {0, 0, 0, 0.0026, 0, 0.0686, 0.0032, 0.9151, 0, 0.0278, 0, 0.0015, 0, 0, 0, 0, 0, 0, }, {0, 0, 0, 0, 0.0015, 0, 0.0607, 0, 0.9154, 0.0063, 0.039, 0.0001, 0.0011, 0, 0, 0, 0, 0, }, {0, 0, 0, 0, 0, 0.0015, 0.001, 0.0558, 0.0042, 0.9187, 0, 0.0358, 0, 0.0007, 0, 0, 0, 0, }, {0, 0, 0, 0, 0, 0, 0.0009, 0, 0.0482, 0, 0.9194, 0.0072, 0.0455, 0.0001, 0.0022, 0, 0, 0, }, {0, 0, 0, 0, 0, 0, 0, 0.001, 0.0002, 0.0457, 0.0047, 0.9374, 0, 0.0314, 0, 0.003, 0, 0, }, {0, 0, 0, 0, 0, 0, 0, 0, 0.0006, 0, 0.0357, 0, 0.9305, 0.0073, 0.0496, 0.0003, 0.0014, 0, }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0012, 0, 0.018, 0.0043, 0.9262, 0, 0.0549, 0, 0.0019, }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0004, 0, 0.0186, 0, 0.9345, 0.0062, 0.0581, 0.0002, }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.034, 0.0034, 0.9242, 0, 0.0542, }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0103, 0, 0.9374, 0.0036, }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0003, 0, 0.0114, 0.0031, 0.9401, } }; Matrix<double> test_Matrix; test_Matrix.setMatrix<double,18,18>(test_matrix); TMTEighteenPlexQuantitationMethod quant_meth; // we only check the default matrix here which is an identity matrix // for tmt18plex Matrix<double> m = quant_meth.getIsotopeCorrectionMatrix(); TEST_EQUAL(m.rows(), 18) TEST_EQUAL(m.cols(), 18) ABORT_IF(m.rows() != 18) ABORT_IF(m.cols() != 18) for(Size i = 0; i < m.rows(); ++i) { for(Size j = 0; j < m.cols(); ++j) { TEST_REAL_SIMILAR(m(i,j), test_Matrix(i,j)) } } } END_SECTION START_SECTION((Size getReferenceChannel() const )) { TMTEighteenPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getReferenceChannel(), 0) Param p; p.setValue("reference_channel","128N"); quant_meth.setParameters(p); TEST_EQUAL(quant_meth.getReferenceChannel(), 3) } END_SECTION START_SECTION((TMTEighteenPlexQuantitationMethod(const TMTEighteenPlexQuantitationMethod &other))) { TMTEighteenPlexQuantitationMethod qm; Param p = qm.getParameters(); p.setValue("channel_127N_description", "new_description"); p.setValue("reference_channel", "129C"); qm.setParameters(p); TMTEighteenPlexQuantitationMethod qm2(qm); IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation(); TEST_STRING_EQUAL(channel_list[1].description, "new_description") TEST_EQUAL(qm2.getReferenceChannel(), 6) } END_SECTION START_SECTION((TMTEighteenPlexQuantitationMethod& operator=(const TMTEighteenPlexQuantitationMethod &rhs))) { TMTEighteenPlexQuantitationMethod qm; Param p = qm.getParameters(); p.setValue("channel_127N_description", "new_description"); p.setValue("reference_channel", "130C"); qm.setParameters(p); TMTEighteenPlexQuantitationMethod qm2 = qm; IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation(); TEST_STRING_EQUAL(channel_list[1].description, "new_description") TEST_EQUAL(qm2.getReferenceChannel(), 8) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SpectrumLookup_test.cpp
.cpp
4,717
161
// 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/METADATA/SpectrumLookup.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(SpectrumLookup, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// SpectrumLookup* ptr = nullptr; SpectrumLookup* null_ptr = nullptr; START_SECTION((SpectrumLookup())) { ptr = new SpectrumLookup(); TEST_NOT_EQUAL(ptr, null_ptr); TEST_REAL_SIMILAR(ptr->rt_tolerance, 0.01); } END_SECTION START_SECTION((~SpectrumLookup())) { delete ptr; } END_SECTION vector<MSSpectrum> spectra; MSSpectrum spectrum; spectrum.setNativeID("spectrum=0"); spectrum.setRT(1.0); spectra.push_back(spectrum); spectrum.setNativeID("spectrum=1"); spectrum.setRT(2.0); spectra.push_back(spectrum); spectrum.setNativeID("spectrum=2"); spectrum.setRT(3.0); spectra.push_back(spectrum); SpectrumLookup lookup; START_SECTION((bool empty() const)) { TEST_EQUAL(lookup.empty(), true); } END_SECTION START_SECTION((template <typename SpectrumContainer> void readSpectra(const SpectrumContainer&, const String&))) { lookup.readSpectra(spectra); TEST_EQUAL(lookup.empty(), false); } END_SECTION START_SECTION((Size findByRT(double) const)) { TEST_EQUAL(lookup.findByRT(2.0), 1); TEST_EXCEPTION(Exception::ElementNotFound, lookup.findByRT(5.0)); } END_SECTION START_SECTION((Size findByNativeID(const String&) const)) { TEST_EQUAL(lookup.findByNativeID("spectrum=1"), 1); TEST_EXCEPTION(Exception::ElementNotFound, lookup.findByNativeID("spectrum=3")); } END_SECTION START_SECTION((Size findByIndex(Size, bool) const)) { TEST_EQUAL(lookup.findByIndex(1), 1); TEST_EQUAL(lookup.findByIndex(1, true), 0); TEST_EXCEPTION(Exception::ElementNotFound, lookup.findByIndex(0, true)); } END_SECTION START_SECTION((Size findByScanNumber(Size) const)) { TEST_EQUAL(lookup.findByScanNumber(1), 1); TEST_EXCEPTION(Exception::ElementNotFound, lookup.findByScanNumber(5)); } END_SECTION START_SECTION((void addReferenceFormat(const String&))) { TEST_EXCEPTION(Exception::IllegalArgument, lookup.addReferenceFormat("XXX")); // tested with other methods below: lookup.addReferenceFormat("scan_number=(?<SCAN>\\d+)"); lookup.addReferenceFormat("(?<ID>spectrum=\\d+)"); } END_SECTION START_SECTION((Size findByReference(const String&) const)) { TEST_EQUAL(lookup.findByReference("scan_number=1"), 1); TEST_EQUAL(lookup.findByReference("name=bla,spectrum=0"), 0); TEST_EXCEPTION(Exception::ParseError, lookup.findByReference("test123")); } END_SECTION START_SECTION((static Int extractScanNumber(const String&, const boost::regex&))) { boost::regex re("spectrum=(?<SCAN>\\d+)"); TEST_EQUAL(SpectrumLookup::extractScanNumber("spectrum=42", re), 42); TEST_EQUAL(SpectrumLookup::extractScanNumber("scan=42", re, true), -1); TEST_EXCEPTION(Exception::ParseError, SpectrumLookup::extractScanNumber("scan=42", re)); } END_SECTION START_SECTION((static Int extractScanNumber(const String&, const String&))) { TEST_EQUAL(SpectrumLookup::extractScanNumber("scan=42", "MS:1000768"), 42); TEST_EQUAL(SpectrumLookup::extractScanNumber("scan=42", "MS:1000769"), 42); TEST_EQUAL(SpectrumLookup::extractScanNumber("scan=42", "MS:1000771"), 42); TEST_EQUAL(SpectrumLookup::extractScanNumber("scan=42", "MS:1000772"), 42); TEST_EQUAL(SpectrumLookup::extractScanNumber("scan=42", "MS:1000776"), 42); TEST_EQUAL(SpectrumLookup::extractScanNumber("sample=1 period=1 cycle=42 experiment=1", "MS:1000770"), 42001); TEST_EQUAL(SpectrumLookup::extractScanNumber("file=42", "MS:1000773"), 42); TEST_EQUAL(SpectrumLookup::extractScanNumber("file=42", "MS:1000775"), 42); TEST_EQUAL(SpectrumLookup::extractScanNumber("index=42", "MS:1000774"), 43); TEST_EQUAL(SpectrumLookup::extractScanNumber("scanId=42", "MS:1001508"), 42); TEST_EQUAL(SpectrumLookup::extractScanNumber("spectrum=42", "MS:1000777"), 42); TEST_EQUAL(SpectrumLookup::extractScanNumber("42", "MS:1001530"), 42); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeptideHit_test.cpp
.cpp
23,270
715
// 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 <string> #include <unordered_set> #include <functional> #include <OpenMS/METADATA/PeptideHit.h> #include <OpenMS/DATASTRUCTURES/String.h> /////////////////////////// START_TEST(PeptideHit, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; double score = 4.4; UInt rank = 3; AASequence sequence = AASequence::fromString("ARRAY"); std::string sequence2 = " ARRAY "; Int charge = 2; PeptideHit* ptr = nullptr; PeptideHit* nullPointer = nullptr; START_SECTION((PeptideHit())) ptr = new PeptideHit(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~PeptideHit())) delete ptr; END_SECTION START_SECTION((PeptideHit(double score, UInt rank, Int charge, const AASequence &sequence))) PeptideHit hit(score, rank, charge, sequence); TEST_EQUAL(hit.getScore(), score) TEST_EQUAL(hit.getRank(), rank) TEST_EQUAL(hit.getCharge(), charge) TEST_EQUAL(hit.getSequence(), sequence) END_SECTION START_SECTION((PeptideHit& operator=(const PeptideHit& source))) PeptideHit hit; PeptideHit hit2(score, rank, charge, sequence); hit2.setMetaValue("label",17); hit = hit2; TEST_EQUAL(hit.getScore(), score) TEST_EQUAL(hit.getRank(), rank) TEST_EQUAL(hit.getCharge(), charge) TEST_EQUAL(hit.getSequence(), sequence) TEST_EQUAL((UInt)hit.getMetaValue("label"),17) END_SECTION START_SECTION((PeptideHit(const PeptideHit& source))) PeptideHit source; source.setScore(score); source.setRank(rank); source.setSequence(sequence); source.setMetaValue("label",17); PeptideHit hit(source); TEST_EQUAL(hit.getScore(), source.getScore()) TEST_EQUAL(hit.getRank(), source.getRank()) TEST_EQUAL(hit.getSequence(), source.getSequence()) TEST_EQUAL((UInt)hit.getMetaValue("label"),17) END_SECTION START_SECTION((bool operator == (const PeptideHit& rhs) const)) PeptideHit hit, hit2; TEST_EQUAL(hit==hit2,true); hit.setScore(score); TEST_EQUAL(hit==hit2,false); hit=hit2; hit.setRank(rank); TEST_EQUAL(hit==hit2,false); hit=hit2; hit.setSequence(sequence); TEST_EQUAL(hit==hit2,false); hit=hit2; hit.setMetaValue("label",17); TEST_EQUAL(hit==hit2,false); hit=hit2; END_SECTION START_SECTION((bool operator != (const PeptideHit& rhs) const)) PeptideHit hit, hit2; TEST_EQUAL(hit!=hit2,false); hit.setScore(score); TEST_EQUAL(hit!=hit2,true); hit=hit2; hit.setRank(rank); TEST_EQUAL(hit!=hit2,true); hit=hit2; hit.setSequence(sequence); TEST_EQUAL(hit!=hit2,true); hit=hit2; hit.setMetaValue("label",17); TEST_EQUAL(hit!=hit2,true); hit=hit2; END_SECTION START_SECTION((double getScore() const )) PeptideHit hit(score, rank, charge, sequence); TEST_EQUAL(hit.getScore(), score) END_SECTION START_SECTION((UInt getRank() const)) PeptideHit hit(score, rank, charge, sequence); TEST_EQUAL(hit.getRank(), rank) END_SECTION START_SECTION((const AASequence& getSequence() const)) PeptideHit hit(score, rank, charge, sequence); TEST_EQUAL(hit.getSequence(), sequence) END_SECTION START_SECTION((void setRank(UInt newrank))) PeptideHit hit; hit.setRank(rank); TEST_EQUAL(hit.getRank(), rank) END_SECTION START_SECTION((void setScore(double score))) PeptideHit hit; hit.setScore(score); TEST_EQUAL(hit.getScore(), score) END_SECTION START_SECTION((void setSequence(const AASequence& sequence))) PeptideHit hit; hit.setSequence(sequence); TEST_EQUAL(hit.getSequence(), sequence) //hit.setSequence(sequence2); // @todo std::string interface? TEST_EQUAL(hit.getSequence(), sequence) END_SECTION ; START_SECTION((void setPeptideEvidences(const vector<PeptideEvidence> & peptide_evidences))) PeptideHit hit; vector<PeptideEvidence> pes(2, PeptideEvidence()); pes[0].setProteinAccession("ACC392"); pes[1].setProteinAccession("ACD392"); hit.setPeptideEvidences(pes); TEST_EQUAL(hit.getPeptideEvidences().size(), 2) TEST_EQUAL(hit.getPeptideEvidences()[0].getProteinAccession() == String("ACC392"), true) TEST_EQUAL(hit.getPeptideEvidences()[1].getProteinAccession() == String("ACD392"), true) END_SECTION START_SECTION((const std::set<String>& extractProteinAccessionsSet() const)) PeptideHit hit; vector<PeptideEvidence> pes(2, PeptideEvidence()); pes[0].setProteinAccession("ACC392"); pes[1].setProteinAccession("ACD392"); hit.setPeptideEvidences(pes); TEST_EQUAL(hit.extractProteinAccessionsSet().size(), 2) TEST_EQUAL(*hit.extractProteinAccessionsSet().begin(), "ACC392") TEST_EQUAL(*hit.extractProteinAccessionsSet().rbegin(), "ACD392") END_SECTION START_SECTION((Int getCharge() const)) PeptideHit hit; hit.setCharge(-43); TEST_EQUAL(-43, hit.getCharge()) END_SECTION START_SECTION((void setCharge(Int charge))) PeptideHit hit; hit.setCharge(-43); TEST_EQUAL(-43, hit.getCharge()) END_SECTION /* START_SECTION((void setAABefore(char acid))) PeptideHit hit; hit.setAABefore('R'); TEST_EQUAL(hit.getAABefore(), 'R') END_SECTION START_SECTION((char getAABefore() const)) PeptideHit hit; hit.setAABefore('R'); TEST_EQUAL(hit.getAABefore(), 'R') END_SECTION START_SECTION((void setAAAfter(char acid))) PeptideHit hit; hit.setAAAfter('R'); TEST_EQUAL(hit.getAAAfter(), 'R') END_SECTION START_SECTION((char getAAAfter() const)) PeptideHit hit; hit.setAAAfter('R'); TEST_EQUAL(hit.getAAAfter(), 'R') END_SECTION */ START_SECTION(([PeptideHit::ScoreLess] template < typename Arg > bool operator()(const Arg &a, const Arg &b))) { PeptideHit a,b; a.setScore(10); b.setScore(20); TEST_EQUAL(PeptideHit::ScoreLess().operator()(a,b), true) TEST_EQUAL(PeptideHit::ScoreLess().operator()(b,a), false) TEST_EQUAL(PeptideHit::ScoreLess().operator()(a,a), false) } END_SECTION START_SECTION(([PeptideHit::ScoreMore] template < typename Arg > bool operator()(const Arg &a, const Arg &b))) { PeptideHit a,b; a.setScore(20); b.setScore(10); TEST_EQUAL(PeptideHit::ScoreMore().operator()(a,b), true) TEST_EQUAL(PeptideHit::ScoreMore().operator()(b,a), false) TEST_EQUAL(PeptideHit::ScoreMore().operator()(a,a), false) } END_SECTION START_SECTION((void setPeakAnnotations(const vector<PeptideHit::PeakAnnotation> & fragment_annotations))) PeptideHit hit; vector<PeptideHit::PeakAnnotation> frag_annos(2, PeptideHit::PeakAnnotation()); frag_annos[0].annotation = "test string"; frag_annos[0].charge = 2; frag_annos[0].mz = 1234.567; frag_annos[0].intensity = 1.0; frag_annos[1].annotation = "second test string"; frag_annos[1].charge = 1; frag_annos[1].mz = 89.10; frag_annos[1].intensity = 0.5; hit.setPeakAnnotations(frag_annos); TEST_EQUAL(hit.getPeakAnnotations().size(), 2) TEST_EQUAL(hit.getPeakAnnotations()[0].annotation == "test string", true) TEST_EQUAL(hit.getPeakAnnotations()[0].charge == 2, true) TEST_EQUAL(hit.getPeakAnnotations()[0].mz == 1234.567, true) TEST_EQUAL(hit.getPeakAnnotations()[0].intensity == 1.0, true) TEST_EQUAL(hit.getPeakAnnotations()[1].annotation == "second test string", true) TEST_EQUAL(hit.getPeakAnnotations()[1].mz == 89.1, true) END_SECTION START_SECTION((void setAnalysisResults(std::vector<PepXMLAnalysisResult> aresult))) { PeptideHit hit; // Create some analysis results std::vector<PeptideHit::PepXMLAnalysisResult> results; PeptideHit::PepXMLAnalysisResult ar1; ar1.score_type = "peptideprophet"; ar1.higher_is_better = true; ar1.main_score = 0.95; ar1.sub_scores["fval"] = 0.7114; ar1.sub_scores["ntt"] = 2.0; PeptideHit::PepXMLAnalysisResult ar2; ar2.score_type = "interprophet"; ar2.higher_is_better = true; ar2.main_score = 0.98; ar2.sub_scores["nss"] = 0.0; ar2.sub_scores["nrs"] = 10.2137; results.push_back(ar1); results.push_back(ar2); // Set the analysis results hit.setAnalysisResults(results); // Check that the analysis results were set correctly TEST_EQUAL(hit.getAnalysisResults().size(), 2); TEST_EQUAL(hit.getAnalysisResults()[0].score_type, "peptideprophet"); TEST_EQUAL(hit.getAnalysisResults()[0].higher_is_better, true); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].main_score, 0.95); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].sub_scores.at("fval"), 0.7114); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].sub_scores.at("ntt"), 2.0); TEST_EQUAL(hit.getAnalysisResults()[1].score_type, "interprophet"); TEST_EQUAL(hit.getAnalysisResults()[1].higher_is_better, true); TEST_REAL_SIMILAR(hit.getAnalysisResults()[1].main_score, 0.98); TEST_REAL_SIMILAR(hit.getAnalysisResults()[1].sub_scores.at("nss"), 0.0); TEST_REAL_SIMILAR(hit.getAnalysisResults()[1].sub_scores.at("nrs"), 10.2137); // Check that the analysis results are stored as meta values TEST_EQUAL(hit.metaValueExists("_ar_0_score_type"), true); TEST_EQUAL(hit.metaValueExists("_ar_0_score"), true); TEST_EQUAL(hit.metaValueExists("_ar_0_higher_is_better"), true); TEST_EQUAL(hit.metaValueExists("_ar_0_subscore_fval"), true); TEST_EQUAL(hit.metaValueExists("_ar_0_subscore_ntt"), true); TEST_EQUAL(hit.metaValueExists("_ar_1_score_type"), true); TEST_EQUAL(hit.metaValueExists("_ar_1_score"), true); TEST_EQUAL(hit.metaValueExists("_ar_1_higher_is_better"), true); TEST_EQUAL(hit.metaValueExists("_ar_1_subscore_nss"), true); TEST_EQUAL(hit.metaValueExists("_ar_1_subscore_nrs"), true); TEST_EQUAL(hit.getMetaValue("_ar_0_score_type").toString(), "peptideprophet"); TEST_REAL_SIMILAR(hit.getMetaValue("_ar_0_score"), 0.95); TEST_EQUAL(hit.getMetaValue("_ar_0_higher_is_better").toBool(), true); TEST_REAL_SIMILAR(hit.getMetaValue("_ar_0_subscore_fval"), 0.7114); TEST_REAL_SIMILAR(hit.getMetaValue("_ar_0_subscore_ntt"), 2.0); TEST_EQUAL(hit.getMetaValue("_ar_1_score_type").toString(), "interprophet"); TEST_REAL_SIMILAR(hit.getMetaValue("_ar_1_score"), 0.98); TEST_EQUAL(hit.getMetaValue("_ar_1_higher_is_better").toBool(), true); TEST_REAL_SIMILAR(hit.getMetaValue("_ar_1_subscore_nss"), 0.0); TEST_REAL_SIMILAR(hit.getMetaValue("_ar_1_subscore_nrs"), 10.2137); // Test overwriting existing analysis results PeptideHit::PepXMLAnalysisResult ar3; ar3.score_type = "mascot"; ar3.higher_is_better = true; ar3.main_score = 100.0; std::vector<PeptideHit::PepXMLAnalysisResult> new_results; new_results.push_back(ar3); hit.setAnalysisResults(new_results); TEST_EQUAL(hit.getAnalysisResults().size(), 1); TEST_EQUAL(hit.getAnalysisResults()[0].score_type, "mascot"); TEST_EQUAL(hit.getAnalysisResults()[0].higher_is_better, true); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].main_score, 100.0); // Check that the old meta values are gone TEST_EQUAL(hit.metaValueExists("_ar_0_score_type"), true); TEST_EQUAL(hit.metaValueExists("_ar_1_score_type"), false); TEST_EQUAL(hit.getMetaValue("_ar_0_score_type").toString(), "mascot"); TEST_REAL_SIMILAR(hit.getMetaValue("_ar_0_score"), 100.0); TEST_EQUAL(hit.getMetaValue("_ar_0_higher_is_better").toBool(), true); } END_SECTION START_SECTION((void addAnalysisResults(const PepXMLAnalysisResult& aresult))) { PeptideHit hit; // Add first analysis result PeptideHit::PepXMLAnalysisResult ar1; ar1.score_type = "peptideprophet"; ar1.higher_is_better = true; ar1.main_score = 0.95; ar1.sub_scores["fval"] = 0.7114; hit.addAnalysisResults(ar1); TEST_EQUAL(hit.getAnalysisResults().size(), 1); TEST_EQUAL(hit.getAnalysisResults()[0].score_type, "peptideprophet"); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].main_score, 0.95); // Add second analysis result PeptideHit::PepXMLAnalysisResult ar2; ar2.score_type = "interprophet"; ar2.higher_is_better = true; ar2.main_score = 0.98; ar2.sub_scores["nrs"] = 10.2137; hit.addAnalysisResults(ar2); TEST_EQUAL(hit.getAnalysisResults().size(), 2); TEST_EQUAL(hit.getAnalysisResults()[1].score_type, "interprophet"); TEST_REAL_SIMILAR(hit.getAnalysisResults()[1].main_score, 0.98); // Check meta values TEST_EQUAL(hit.metaValueExists("_ar_0_score_type"), true); TEST_EQUAL(hit.metaValueExists("_ar_1_score_type"), true); TEST_EQUAL(hit.getMetaValue("_ar_0_score_type").toString(), "peptideprophet"); TEST_EQUAL(hit.getMetaValue("_ar_1_score_type").toString(), "interprophet"); } END_SECTION START_SECTION((const std::vector<PepXMLAnalysisResult>& getAnalysisResults() const)) { PeptideHit hit; // Test empty analysis results TEST_EQUAL(hit.getAnalysisResults().size(), 0); // Add analysis results PeptideHit::PepXMLAnalysisResult ar1; ar1.score_type = "peptideprophet"; ar1.higher_is_better = true; ar1.main_score = 0.95; hit.addAnalysisResults(ar1); TEST_EQUAL(hit.getAnalysisResults().size(), 1); TEST_EQUAL(hit.getAnalysisResults()[0].score_type, "peptideprophet"); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].main_score, 0.95); } END_SECTION START_SECTION((PeptideHit(const PeptideHit& source) - with analysis results)) { PeptideHit source; // Add analysis results to source PeptideHit::PepXMLAnalysisResult ar1; ar1.score_type = "peptideprophet"; ar1.higher_is_better = true; ar1.main_score = 0.95; ar1.sub_scores["fval"] = 0.7114; source.addAnalysisResults(ar1); // Copy construct PeptideHit hit(source); // Check that analysis results were copied TEST_EQUAL(hit.getAnalysisResults().size(), 1); TEST_EQUAL(hit.getAnalysisResults()[0].score_type, "peptideprophet"); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].main_score, 0.95); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].sub_scores.at("fval"), 0.7114); // Check meta values TEST_EQUAL(hit.metaValueExists("_ar_0_score_type"), true); TEST_EQUAL(hit.getMetaValue("_ar_0_score_type").toString(), "peptideprophet"); } END_SECTION START_SECTION((PeptideHit& operator=(const PeptideHit& source) - with analysis results)) { PeptideHit source; // Add analysis results to source PeptideHit::PepXMLAnalysisResult ar1; ar1.score_type = "peptideprophet"; ar1.higher_is_better = true; ar1.main_score = 0.95; ar1.sub_scores["fval"] = 0.7114; source.addAnalysisResults(ar1); // Assignment PeptideHit hit; hit = source; // Check that analysis results were copied TEST_EQUAL(hit.getAnalysisResults().size(), 1); TEST_EQUAL(hit.getAnalysisResults()[0].score_type, "peptideprophet"); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].main_score, 0.95); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].sub_scores.at("fval"), 0.7114); // Check meta values TEST_EQUAL(hit.metaValueExists("_ar_0_score_type"), true); TEST_EQUAL(hit.getMetaValue("_ar_0_score_type").toString(), "peptideprophet"); } END_SECTION START_SECTION((bool operator==(const PeptideHit& rhs) const - with analysis results)) { PeptideHit hit1, hit2; // Empty hits should be equal TEST_EQUAL(hit1 == hit2, true); // Add analysis results to hit1 PeptideHit::PepXMLAnalysisResult ar1; ar1.score_type = "peptideprophet"; ar1.higher_is_better = true; ar1.main_score = 0.95; hit1.addAnalysisResults(ar1); // Now they should be different TEST_EQUAL(hit1 == hit2, false); // Add same analysis results to hit2 hit2.addAnalysisResults(ar1); // Now they should be equal again TEST_EQUAL(hit1 == hit2, true); // Add different analysis results to hit2 PeptideHit::PepXMLAnalysisResult ar2; ar2.score_type = "interprophet"; ar2.higher_is_better = true; ar2.main_score = 0.98; hit2.addAnalysisResults(ar2); // Now they should be different again TEST_EQUAL(hit1 == hit2, false); } END_SECTION START_SECTION((PeptideHit(PeptideHit&& source) noexcept - with analysis results)) { PeptideHit source; // Add analysis results to source PeptideHit::PepXMLAnalysisResult ar1; ar1.score_type = "peptideprophet"; ar1.higher_is_better = true; ar1.main_score = 0.95; ar1.sub_scores["fval"] = 0.7114; source.addAnalysisResults(ar1); // Move construct PeptideHit hit(std::move(source)); // Check that analysis results were moved TEST_EQUAL(hit.getAnalysisResults().size(), 1); TEST_EQUAL(hit.getAnalysisResults()[0].score_type, "peptideprophet"); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].main_score, 0.95); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].sub_scores.at("fval"), 0.7114); // Check meta values TEST_EQUAL(hit.metaValueExists("_ar_0_score_type"), true); TEST_EQUAL(hit.getMetaValue("_ar_0_score_type").toString(), "peptideprophet"); // Source should have no meta values after move TEST_EQUAL(source.metaValueExists("_ar_0_score_type"), false); TEST_EQUAL(source.getAnalysisResults().size(), 0); } END_SECTION START_SECTION((PeptideHit& operator=(PeptideHit&& source) noexcept - with analysis results)) { PeptideHit source; // Add analysis results to source PeptideHit::PepXMLAnalysisResult ar1; ar1.score_type = "peptideprophet"; ar1.higher_is_better = true; ar1.main_score = 0.95; ar1.sub_scores["fval"] = 0.7114; source.addAnalysisResults(ar1); // Move assignment PeptideHit hit; hit = std::move(source); // Check that analysis results were moved TEST_EQUAL(hit.getAnalysisResults().size(), 1); TEST_EQUAL(hit.getAnalysisResults()[0].score_type, "peptideprophet"); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].main_score, 0.95); TEST_REAL_SIMILAR(hit.getAnalysisResults()[0].sub_scores.at("fval"), 0.7114); // Check meta values TEST_EQUAL(hit.metaValueExists("_ar_0_score_type"), true); TEST_EQUAL(hit.getMetaValue("_ar_0_score_type").toString(), "peptideprophet"); // Source should have no meta values after move TEST_EQUAL(source.metaValueExists("_ar_0_score_type"), false); TEST_EQUAL(source.getAnalysisResults().size(), 0); } END_SECTION START_SECTION((bool isDecoy() const)) { PeptideHit hit; // Test default behavior (no target_decoy meta value set) // Should return false since default is "target" TEST_EQUAL(hit.isDecoy(), false); // Test with explicit "target" value hit.setMetaValue("target_decoy", "target"); TEST_EQUAL(hit.isDecoy(), false); // Test with "decoy" value hit.setMetaValue("target_decoy", "decoy"); TEST_EQUAL(hit.isDecoy(), true); // Test with "DECOY" (case insensitive) hit.setMetaValue("target_decoy", "DECOY"); TEST_EQUAL(hit.isDecoy(), true); // Test with other values hit.setMetaValue("target_decoy", "target+decoy"); TEST_EQUAL(hit.isDecoy(), false); } END_SECTION START_SECTION((void setTargetDecoyType(TargetDecoyType type))) { PeptideHit hit; // Test setting TARGET hit.setTargetDecoyType(PeptideHit::TargetDecoyType::TARGET); TEST_EQUAL(hit.getMetaValue("target_decoy"), "target"); // Test setting DECOY hit.setTargetDecoyType(PeptideHit::TargetDecoyType::DECOY); TEST_EQUAL(hit.getMetaValue("target_decoy"), "decoy"); // Test setting TARGET_DECOY hit.setTargetDecoyType(PeptideHit::TargetDecoyType::TARGET_DECOY); TEST_EQUAL(hit.getMetaValue("target_decoy"), "target+decoy"); // Test setting UNKNOWN (should remove meta value) hit.setTargetDecoyType(PeptideHit::TargetDecoyType::UNKNOWN); TEST_EQUAL(hit.metaValueExists("target_decoy"), false); TEST_EQUAL(hit.getTargetDecoyType(), PeptideHit::TargetDecoyType::UNKNOWN); } END_SECTION START_SECTION((TargetDecoyType getTargetDecoyType() const)) { PeptideHit hit; // Test default behavior (should return UNKNOWN when meta value doesn't exist) TEST_EQUAL(hit.getTargetDecoyType(), PeptideHit::TargetDecoyType::UNKNOWN); // Test with explicit "target" value hit.setMetaValue("target_decoy", "target"); TEST_EQUAL(hit.getTargetDecoyType(), PeptideHit::TargetDecoyType::TARGET); // Test with "decoy" value hit.setMetaValue("target_decoy", "decoy"); TEST_EQUAL(hit.getTargetDecoyType(), PeptideHit::TargetDecoyType::DECOY); // Test with "DECOY" (case insensitive) hit.setMetaValue("target_decoy", "DECOY"); TEST_EQUAL(hit.getTargetDecoyType(), PeptideHit::TargetDecoyType::DECOY); // Test with "target+decoy" value hit.setMetaValue("target_decoy", "target+decoy"); TEST_EQUAL(hit.getTargetDecoyType(), PeptideHit::TargetDecoyType::TARGET_DECOY); // Test with "TARGET+DECOY" (case insensitive) hit.setMetaValue("target_decoy", "TARGET+DECOY"); TEST_EQUAL(hit.getTargetDecoyType(), PeptideHit::TargetDecoyType::TARGET_DECOY); // Test with unrecognized value (should throw InvalidValue exception) hit.setMetaValue("target_decoy", "unrecognized_value"); TEST_EXCEPTION(Exception::InvalidValue, hit.getTargetDecoyType()); // Test after removing meta value (should return UNKNOWN) hit.removeMetaValue("target_decoy"); TEST_EQUAL(hit.getTargetDecoyType(), PeptideHit::TargetDecoyType::UNKNOWN); } END_SECTION START_SECTION(([EXTRA] PeptideHit::SequenceChargeHash and SequenceChargeEqual)) { // Test SequenceChargeHash - hashes based on sequence and charge PeptideHit hit1(1.0, 1, 2, AASequence::fromString("PEPTIDE")); PeptideHit hit2(2.0, 2, 2, AASequence::fromString("PEPTIDE")); // Same seq+charge, different score/rank PeptideHit hit3(1.0, 1, 3, AASequence::fromString("PEPTIDE")); // Different charge PeptideHit hit4(1.0, 1, 2, AASequence::fromString("PEPTIDER")); // Different sequence PeptideHit::SequenceChargeHash hasher; PeptideHit::SequenceChargeEqual equal; // Same sequence and charge should have equal hashes TEST_EQUAL(hasher(hit1), hasher(hit2)) TEST_EQUAL(equal(hit1, hit2), true) // Different charge should have different hashes TEST_NOT_EQUAL(hasher(hit1), hasher(hit3)) TEST_EQUAL(equal(hit1, hit3), false) // Different sequence should have different hashes TEST_NOT_EQUAL(hasher(hit1), hasher(hit4)) TEST_EQUAL(equal(hit1, hit4), false) // Test with modifications PeptideHit hit5(1.0, 1, 2, AASequence::fromString("PEPTM(Oxidation)IDE")); PeptideHit hit6(1.0, 1, 2, AASequence::fromString("PEPTMIDE")); // No modification TEST_NOT_EQUAL(hasher(hit5), hasher(hit6)) // Modification matters // Test use in unordered_set with custom hasher std::unordered_set<PeptideHit, PeptideHit::SequenceChargeHash, PeptideHit::SequenceChargeEqual> hit_set; hit_set.insert(hit1); hit_set.insert(hit2); // Same seq+charge as hit1, should not increase size hit_set.insert(hit3); // Different charge hit_set.insert(hit4); // Different sequence TEST_EQUAL(hit_set.size(), 3) // Verify we can find elements PeptideHit query(99.0, 99, 2, AASequence::fromString("PEPTIDE")); // Different score/rank but same seq+charge TEST_EQUAL(hit_set.count(query), 1) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DTA2DFile_test.cpp
.cpp
17,168
578
// 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/FORMAT/DTA2DFile.h> #include <OpenMS/FORMAT/FileTypes.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/Peak2D.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(DTAFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// DTA2DFile* ptr = nullptr; DTA2DFile* nullPointer = nullptr; START_SECTION((DTA2DFile())) ptr = new DTA2DFile; TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~DTA2DFile())) delete ptr; END_SECTION START_SECTION(const PeakFileOptions& getOptions() const) DTA2DFile file; TEST_EQUAL(file.getOptions().hasMSLevels(),false) END_SECTION START_SECTION(PeakFileOptions& getOptions()) DTA2DFile file; file.getOptions().addMSLevel(1); TEST_EQUAL(file.getOptions().hasMSLevels(),true); END_SECTION START_SECTION((template<typename MapType> void load(const String& filename, MapType& map) )) TOLERANCE_ABSOLUTE(0.01) PeakMap e; DTA2DFile file; //test exception TEST_EXCEPTION( Exception::FileNotFound , file.load("dummy/dummy.dta2d",e) ) // real test file.load(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"),e); //test DocumentIdentifier addition TEST_STRING_EQUAL(e.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d")); TEST_STRING_EQUAL(FileTypes::typeToName(e.getLoadedFileType()),"dta2d"); TEST_EQUAL(e.size(), 9); ABORT_IF(e.size() != 9) TEST_STRING_EQUAL(e[0].getNativeID(),"index=0") TEST_STRING_EQUAL(e[1].getNativeID(),"index=1") TEST_STRING_EQUAL(e[2].getNativeID(),"index=2") TEST_STRING_EQUAL(e[3].getNativeID(),"index=3") TEST_STRING_EQUAL(e[4].getNativeID(),"index=4") TEST_STRING_EQUAL(e[5].getNativeID(),"index=5") TEST_STRING_EQUAL(e[6].getNativeID(),"index=6") TEST_STRING_EQUAL(e[7].getNativeID(),"index=7") TEST_STRING_EQUAL(e[8].getNativeID(),"index=8") PeakMap::const_iterator it(e.begin()); TEST_REAL_SIMILAR((*it)[0].getPosition()[0], 230.02) TEST_REAL_SIMILAR(it->getRT(), 4711.1) TEST_REAL_SIMILAR((*it)[0].getIntensity(), 47218.89) ++it; TEST_REAL_SIMILAR((*it)[0].getPosition()[0], 231.51) TEST_REAL_SIMILAR(it->getRT(), 4711.2) TEST_REAL_SIMILAR((*it)[0].getIntensity(), 89935.22) ++it; TEST_REAL_SIMILAR((*it)[0].getPosition()[0], 139.42) TEST_REAL_SIMILAR(it->getRT(), 4711.3) TEST_REAL_SIMILAR((*it)[0].getIntensity(), 318.52) ++it; TEST_REAL_SIMILAR((*it)[0].getPosition()[0], 149.93) TEST_REAL_SIMILAR(it->getRT(), 4711.4) TEST_REAL_SIMILAR((*it)[0].getIntensity(), 61870.99) ++it; TEST_REAL_SIMILAR((*it)[0].getPosition()[0], 169.65) TEST_REAL_SIMILAR(it->getRT(), 4711.5) TEST_REAL_SIMILAR((*it)[0].getIntensity(), 62074.22) ++it; TEST_REAL_SIMILAR((*it)[0].getPosition()[0], 189.30) TEST_REAL_SIMILAR(it->getRT(), 4711.6) TEST_REAL_SIMILAR((*it)[0].getIntensity(), 53737.85) ++it; TEST_REAL_SIMILAR((*it)[0].getPosition()[0], 202.28) TEST_REAL_SIMILAR(it->getRT(), 4711.7) TEST_REAL_SIMILAR((*it)[0].getIntensity(), 49410.25) ++it; TEST_REAL_SIMILAR((*it)[0].getPosition()[0], 207.82) TEST_REAL_SIMILAR(it->getRT(), 4711.8) TEST_REAL_SIMILAR((*it)[0].getIntensity(), 17038.71) ++it; TEST_REAL_SIMILAR((*it)[0].getPosition()[0], 219.72) TEST_REAL_SIMILAR(it->getRT(), 4711.9) TEST_REAL_SIMILAR((*it)[0].getIntensity(), 73629.98) //test with header file.load(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_2.dta2d"),e); std::vector<Peak2D> array; e.get2DData(array); TEST_EQUAL(array.size(), 11); ABORT_IF(array.size() != 11) std::vector<Peak2D>::const_iterator it2 = array.begin(); TEST_REAL_SIMILAR(it2->getMZ(), 230.02) TEST_REAL_SIMILAR(it2->getRT(), 4711.1) TEST_REAL_SIMILAR(it2->getIntensity(), 47218.89) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 430.02) TEST_REAL_SIMILAR(it2->getRT(), 4711.1) TEST_REAL_SIMILAR(it2->getIntensity(), 47219.89) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 630.02) TEST_REAL_SIMILAR(it2->getRT(), 4711.1) TEST_REAL_SIMILAR(it2->getIntensity(), 47210.89) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 231.51) TEST_REAL_SIMILAR(it2->getRT(), 4711.2) TEST_REAL_SIMILAR(it2->getIntensity(), 89935.22) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 139.42) TEST_REAL_SIMILAR(it2->getRT(), 4711.3) TEST_REAL_SIMILAR(it2->getIntensity(), 318.52) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 149.93) TEST_REAL_SIMILAR(it2->getRT(), 4711.4) TEST_REAL_SIMILAR(it2->getIntensity(), 61870.99) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 169.65) TEST_REAL_SIMILAR(it2->getRT(), 4711.5) TEST_REAL_SIMILAR(it2->getIntensity(), 62074.22) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 189.30) TEST_REAL_SIMILAR(it2->getRT(), 4711.6) TEST_REAL_SIMILAR(it2->getIntensity(), 53737.85) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 202.28) TEST_REAL_SIMILAR(it2->getRT(), 4711.7) TEST_REAL_SIMILAR(it2->getIntensity(), 49410.25) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 207.82) TEST_REAL_SIMILAR(it2->getRT(), 4711.8) TEST_REAL_SIMILAR(it2->getIntensity(), 17038.71) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 219.72) TEST_REAL_SIMILAR(it2->getRT(), 4711.9) TEST_REAL_SIMILAR(it2->getIntensity(), 73629.98) PeakMap e3; file.load(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"),e3); TEST_EQUAL(e3.size(), 9); ABORT_IF(e3.size() != 9) PeakMap::const_iterator it3(e3.begin()); TEST_EQUAL(it3->size(), 3); ABORT_IF(it3->size() != 3) TEST_REAL_SIMILAR(it3->getRT(), 4711.1) TEST_REAL_SIMILAR((*it3)[0].getPosition()[0], 230.02) TEST_REAL_SIMILAR((*it3)[0].getIntensity(), 47218.89) TEST_REAL_SIMILAR((*it3)[1].getPosition()[0], 430.02) TEST_REAL_SIMILAR((*it3)[1].getIntensity(), 47219.89) TEST_REAL_SIMILAR((*it3)[2].getPosition()[0], 630.02) TEST_REAL_SIMILAR((*it3)[2].getIntensity(), 47210.89) ++it3; TEST_REAL_SIMILAR((*it3)[0].getPosition()[0], 231.51) TEST_REAL_SIMILAR(it3->getRT(), 4711.2) TEST_REAL_SIMILAR((*it3)[0].getIntensity(), 89935.22) ++it3; TEST_REAL_SIMILAR((*it3)[0].getPosition()[0], 139.42) TEST_REAL_SIMILAR(it3->getRT(), 4711.3) TEST_REAL_SIMILAR((*it3)[0].getIntensity(), 318.52) ++it3; TEST_REAL_SIMILAR((*it3)[0].getPosition()[0], 149.93) TEST_REAL_SIMILAR(it3->getRT(), 4711.4) TEST_REAL_SIMILAR((*it3)[0].getIntensity(), 61870.99) ++it3; TEST_REAL_SIMILAR((*it3)[0].getPosition()[0], 169.65) TEST_REAL_SIMILAR(it3->getRT(), 4711.5) TEST_REAL_SIMILAR((*it3)[0].getIntensity(), 62074.22) ++it3; TEST_REAL_SIMILAR((*it3)[0].getPosition()[0], 189.30) TEST_REAL_SIMILAR(it3->getRT(), 4711.6) TEST_REAL_SIMILAR((*it3)[0].getIntensity(), 53737.85) ++it3; TEST_REAL_SIMILAR((*it3)[0].getPosition()[0], 202.28) TEST_REAL_SIMILAR(it3->getRT(), 4711.7) TEST_REAL_SIMILAR((*it3)[0].getIntensity(), 49410.25) ++it3; TEST_REAL_SIMILAR((*it3)[0].getPosition()[0], 207.82) TEST_REAL_SIMILAR(it3->getRT(), 4711.8) TEST_REAL_SIMILAR((*it3)[0].getIntensity(), 17038.71) ++it3; TEST_REAL_SIMILAR((*it3)[0].getPosition()[0], 219.72) TEST_REAL_SIMILAR(it3->getRT(), 4711.9) TEST_REAL_SIMILAR((*it3)[0].getIntensity(), 73629.98) //test with header and minutes instead of seconds PeakMap e4; file.load(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_3.dta2d"),e4); TEST_EQUAL(e4.size(),9) TEST_REAL_SIMILAR(e4[0].getRT(), 282666) TEST_REAL_SIMILAR(e4[1].getRT(), 282672) TEST_REAL_SIMILAR(e4[2].getRT(), 282678) TEST_REAL_SIMILAR(e4[3].getRT(), 282684) TEST_REAL_SIMILAR(e4[4].getRT(), 282690) END_SECTION START_SECTION((template<typename MapType> void store(const String& filename, const MapType& map) const )) TOLERANCE_ABSOLUTE(0.1) std::string tmp_filename; PeakMap e; DTA2DFile f; NEW_TMP_FILE(tmp_filename); f.load(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"),e); f.store(tmp_filename,e); PeakMap e2; f.load(tmp_filename,e2); std::vector<Peak2D> array; e2.get2DData(array); TEST_EQUAL(array.size(), 11); ABORT_IF(array.size() != 11) std::vector<Peak2D>::const_iterator it2 = array.begin(); TEST_REAL_SIMILAR(it2->getMZ(), 230.02) TEST_REAL_SIMILAR(it2->getRT(), 4711.1) TEST_REAL_SIMILAR(it2->getIntensity(), 47218.89) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 430.02) TEST_REAL_SIMILAR(it2->getRT(), 4711.1) TEST_REAL_SIMILAR(it2->getIntensity(), 47219.89) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 630.02) TEST_REAL_SIMILAR(it2->getRT(), 4711.1) TEST_REAL_SIMILAR(it2->getIntensity(), 47210.89) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 231.51) TEST_REAL_SIMILAR(it2->getRT(), 4711.2) TEST_REAL_SIMILAR(it2->getIntensity(), 89935.22) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 139.42) TEST_REAL_SIMILAR(it2->getRT(), 4711.3) TEST_REAL_SIMILAR(it2->getIntensity(), 318.52) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 149.93) TEST_REAL_SIMILAR(it2->getRT(), 4711.4) TEST_REAL_SIMILAR(it2->getIntensity(), 61870.99) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 169.65) TEST_REAL_SIMILAR(it2->getRT(), 4711.5) TEST_REAL_SIMILAR(it2->getIntensity(), 62074.22) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 189.30) TEST_REAL_SIMILAR(it2->getRT(), 4711.6) TEST_REAL_SIMILAR(it2->getIntensity(), 53737.85) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 202.28) TEST_REAL_SIMILAR(it2->getRT(), 4711.7) TEST_REAL_SIMILAR(it2->getIntensity(), 49410.25) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 207.82) TEST_REAL_SIMILAR(it2->getRT(), 4711.8) TEST_REAL_SIMILAR(it2->getIntensity(), 17038.71) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 219.72) TEST_REAL_SIMILAR(it2->getRT(), 4711.9) TEST_REAL_SIMILAR(it2->getIntensity(), 73629.98) PeakMap e3; f.load(tmp_filename,e3); std::vector<Peak2D > array2; e2.get2DData(array2); TEST_EQUAL(array2.size(), 11); ABORT_IF(array2.size() != 11) std::vector<Peak2D >::const_iterator it3 = array2.begin(); TEST_REAL_SIMILAR(it3->getMZ(), 230.02) TEST_REAL_SIMILAR(it3->getRT(), 4711.1) TEST_REAL_SIMILAR(it3->getIntensity(), 47218.89) ++it3; TEST_REAL_SIMILAR(it3->getMZ(), 430.02) TEST_REAL_SIMILAR(it3->getRT(), 4711.1) TEST_REAL_SIMILAR(it3->getIntensity(), 47219.89) ++it3; TEST_REAL_SIMILAR(it3->getMZ(), 630.02) TEST_REAL_SIMILAR(it3->getRT(), 4711.1) TEST_REAL_SIMILAR(it3->getIntensity(), 47210.89) ++it3; TEST_REAL_SIMILAR(it3->getMZ(), 231.51) TEST_REAL_SIMILAR(it3->getRT(), 4711.2) TEST_REAL_SIMILAR(it3->getIntensity(), 89935.22) ++it3; TEST_REAL_SIMILAR(it3->getMZ(), 139.42) TEST_REAL_SIMILAR(it3->getRT(), 4711.3) TEST_REAL_SIMILAR(it3->getIntensity(), 318.52) ++it3; TEST_REAL_SIMILAR(it3->getMZ(), 149.93) TEST_REAL_SIMILAR(it3->getRT(), 4711.4) TEST_REAL_SIMILAR(it3->getIntensity(), 61870.99) ++it3; TEST_REAL_SIMILAR(it3->getMZ(), 169.65) TEST_REAL_SIMILAR(it3->getRT(), 4711.5) TEST_REAL_SIMILAR(it3->getIntensity(), 62074.22) ++it3; TEST_REAL_SIMILAR(it3->getMZ(), 189.30) TEST_REAL_SIMILAR(it3->getRT(), 4711.6) TEST_REAL_SIMILAR(it3->getIntensity(), 53737.85) ++it3; TEST_REAL_SIMILAR(it3->getMZ(), 202.28) TEST_REAL_SIMILAR(it3->getRT(), 4711.7) TEST_REAL_SIMILAR(it3->getIntensity(), 49410.25) ++it3; TEST_REAL_SIMILAR(it3->getMZ(), 207.82) TEST_REAL_SIMILAR(it3->getRT(), 4711.8) TEST_REAL_SIMILAR(it3->getIntensity(), 17038.71) ++it3; TEST_REAL_SIMILAR(it3->getMZ(), 219.72) TEST_REAL_SIMILAR(it3->getRT(), 4711.9) TEST_REAL_SIMILAR(it3->getIntensity(), 73629.98) END_SECTION START_SECTION((template<typename MapType> void storeTIC(const String& filename, const MapType& map) const )) TOLERANCE_ABSOLUTE(0.1) std::string tmp_filename; PeakMap e; DTA2DFile f; NEW_TMP_FILE(tmp_filename); f.load(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"),e); f.storeTIC(tmp_filename,e); PeakMap e2; f.load(tmp_filename,e2); std::vector<Peak2D> array; e2.get2DData(array); TEST_EQUAL(array.size(), 9); ABORT_IF(array.size() != 9) std::vector<Peak2D>::const_iterator it2 = array.begin(); TEST_REAL_SIMILAR(it2->getMZ(), 0) TEST_REAL_SIMILAR(it2->getRT(), 4711.1) TEST_REAL_SIMILAR(it2->getIntensity(), 141650) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 0) TEST_REAL_SIMILAR(it2->getRT(), 4711.2) TEST_REAL_SIMILAR(it2->getIntensity(), 89935.22) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 0) TEST_REAL_SIMILAR(it2->getRT(), 4711.3) TEST_REAL_SIMILAR(it2->getIntensity(), 318.52) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 0) TEST_REAL_SIMILAR(it2->getRT(), 4711.4) TEST_REAL_SIMILAR(it2->getIntensity(), 61870.99) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 0) TEST_REAL_SIMILAR(it2->getRT(), 4711.5) TEST_REAL_SIMILAR(it2->getIntensity(), 62074.22) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 0) TEST_REAL_SIMILAR(it2->getRT(), 4711.6) TEST_REAL_SIMILAR(it2->getIntensity(), 53737.85) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 0) TEST_REAL_SIMILAR(it2->getRT(), 4711.7) TEST_REAL_SIMILAR(it2->getIntensity(), 49410.25) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 0) TEST_REAL_SIMILAR(it2->getRT(), 4711.8) TEST_REAL_SIMILAR(it2->getIntensity(), 17038.71) ++it2; TEST_REAL_SIMILAR(it2->getMZ(), 0) TEST_REAL_SIMILAR(it2->getRT(), 4711.9) TEST_REAL_SIMILAR(it2->getIntensity(), 73629.98) END_SECTION START_SECTION(([EXTRA] load with RT range)) TOLERANCE_ABSOLUTE(0.01) PeakMap e; DTA2DFile file; file.getOptions().setRTRange(makeRange(4711.15, 4711.45)); file.load(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"),e); TEST_EQUAL(e.size(), 3) TEST_REAL_SIMILAR(e[0].getRT(), 4711.2) TEST_EQUAL(e[0].size(), 1) TEST_REAL_SIMILAR(e[0][0].getMZ(), 231.51) TEST_STRING_EQUAL(e[0].getNativeID(),"index=1") TEST_REAL_SIMILAR(e[1].getRT(), 4711.3) TEST_EQUAL(e[1].size(), 1) TEST_REAL_SIMILAR(e[1][0].getMZ(), 139.42) TEST_STRING_EQUAL(e[1].getNativeID(),"index=2") TEST_REAL_SIMILAR(e[2].getRT(), 4711.4) TEST_EQUAL(e[2].size(), 1) TEST_REAL_SIMILAR(e[2][0].getMZ(), 149.93) TEST_STRING_EQUAL(e[2].getNativeID(),"index=3") END_SECTION START_SECTION(([EXTRA] load with MZ range)) TOLERANCE_ABSOLUTE(0.01) PeakMap e; DTA2DFile file; file.getOptions().setMZRange(makeRange(150, 220)); file.load(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"),e); TEST_EQUAL(e.size(), 5) TEST_REAL_SIMILAR(e[0].getRT(), 4711.5) TEST_EQUAL(e[0].size(), 1) TEST_REAL_SIMILAR(e[0][0].getMZ(), 169.65) TEST_STRING_EQUAL(e[0].getNativeID(),"index=4") TEST_REAL_SIMILAR(e[1].getRT(), 4711.6) TEST_EQUAL(e[1].size(), 1) TEST_REAL_SIMILAR(e[1][0].getMZ(), 189.30) TEST_STRING_EQUAL(e[1].getNativeID(),"index=5") TEST_REAL_SIMILAR(e[2].getRT(), 4711.7) TEST_EQUAL(e[2].size(), 1) TEST_REAL_SIMILAR(e[2][0].getMZ(), 202.28) TEST_STRING_EQUAL(e[2].getNativeID(),"index=6") TEST_REAL_SIMILAR(e[3].getRT(), 4711.8) TEST_EQUAL(e[3].size(), 1) TEST_REAL_SIMILAR(e[3][0].getMZ(), 207.82) TEST_STRING_EQUAL(e[3].getNativeID(),"index=7") TEST_REAL_SIMILAR(e[4].getRT(), 4711.9) TEST_EQUAL(e[4].size(), 1) TEST_REAL_SIMILAR(e[4][0].getMZ(), 219.72) TEST_STRING_EQUAL(e[4].getNativeID(),"index=8") END_SECTION START_SECTION(([EXTRA] load with intensity range)) TOLERANCE_ABSOLUTE(0.01) PeakMap e; DTA2DFile file; file.getOptions().setIntensityRange(makeRange(30000, 70000)); file.load(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"),e); TEST_EQUAL(e.size(), 5) TEST_REAL_SIMILAR(e[0].getRT(), 4711.1) TEST_EQUAL(e[0].size(), 3) TEST_REAL_SIMILAR(e[0][0].getMZ(), 230.02) TEST_REAL_SIMILAR(e[0][1].getMZ(), 430.02) TEST_REAL_SIMILAR(e[0][2].getMZ(), 630.02) TEST_STRING_EQUAL(e[0].getNativeID(),"index=0") TEST_REAL_SIMILAR(e[1].getRT(), 4711.4) TEST_EQUAL(e[1].size(), 1) TEST_REAL_SIMILAR(e[1][0].getMZ(), 149.93) TEST_STRING_EQUAL(e[1].getNativeID(),"index=3") TEST_REAL_SIMILAR(e[2].getRT(), 4711.5) TEST_EQUAL(e[2].size(), 1) TEST_REAL_SIMILAR(e[2][0].getMZ(), 169.65) TEST_STRING_EQUAL(e[2].getNativeID(),"index=4") TEST_REAL_SIMILAR(e[3].getRT(), 4711.6) TEST_EQUAL(e[3].size(), 1) TEST_REAL_SIMILAR(e[3][0].getMZ(), 189.30) TEST_STRING_EQUAL(e[3].getNativeID(),"index=5") TEST_REAL_SIMILAR(e[4].getRT(), 4711.7) TEST_EQUAL(e[4].size(), 1) TEST_REAL_SIMILAR(e[4][0].getMZ(), 202.28) TEST_STRING_EQUAL(e[4].getNativeID(),"index=6") END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BasicStatistics_test.cpp
.cpp
12,694
402
// 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> /////////////////////////// // This one is going to be tested. #include <OpenMS/MATH/STATISTICS/BasicStatistics.h> /////////////////////////// // More headers #include <algorithm> #include <functional> #include <iostream> #include <iterator> #include <vector> #include <string> /////////////////////////// namespace OpenMS { // extra stuff required for this test double dvector_data[] = { 82.70033, 18.53697, 130.43985, 71.42455, 50.63099, 20.31581, 30.19521, 36.79161, 135.08596, 84.68491, 124.30681, 71.33620, 126.07538, 73.61598, 130.07241, 88.97545, 112.80919, 81.12736, 170.80468, 74.20200, 29.40524, 44.20175, 124.63237, 84.51534, 165.35688, 79.33067, 68.44432, 18.62523, 112.01351, 77.03597, 29.93905, 49.71414, 30.82335, 61.01894, 113.46661, 78.16001, 162.25406, 89.78833, 158.70900, 74.51220, 73.57289, 124.63237, 84.51534, 165.35688, 79.33067, 68.44432, 18.62523, 112.01351, 77.03597, 29.93905, 49.71414, 30.82335, 61.01894, 113.46661, 78.16001, 162.25406, 89.78833, 158.70900, 74.51220, 73.57289, 17.14514, 130.14515, 83.68410, 29.89634, 47.08373, 76.58917, 29.00928, 57.22767, 22.04459, 108.34564, 79.49656, 140.83229, 67.81030, 28.82848, 78.72329, 31.32767, 62.28604, 29.48579, 76.01188, 142.99623, 71.69667, 140.45532, 78.81924, 57.99051, 19.66125, 29.71268, 63.73135, 65.07940, 27.78494, 127.22279, 67.27982, 29.50484, 142.99623, 71.69667, 140.45532, 78.81924, 57.99051, 19.66125, 29.71268, 63.73135, 65.07940, 27.78494, 127.22279, 67.27982, 29.50484, 142.99623, 71.69667, 140.45532, 78.81924, 57.99051, 19.66125, 29.71268, 63.73135, 65.07940, 27.78494, 127.22279, 67.27982, 29.50484, 54.54108, 30.53517, 86.44319, 67.76178, 18.95834, 123.73745, 77.66034, 30.29570, 60.94120, 142.92731, 82.77405, 141.99247, 76.17666, 157.02459, 78.28177, 96.25540, 19.82469, 27.72561, 53.91157, 29.91151, 60.05424, 61.35466, 16.14011, 163.18400, 77.86948, 153.28102, 91.43451, 29.32177, 83.93723, 111.66644, 80.25561, 129.31559, 90.71809, 107.97381, 75.83463, 147.61897, 78.47707, 29.93856, 68.92398, 177.78189, 81.44311, 68.58626, 24.30645, 132.16980, 79.22136, 28.12488, 78.71920, 151.88722, 83.39256, 29.69833, 71.72692, 52.76207, 15.71214, 116.18279, 75.74875, 115.52147, 91.14405, 127.02429, 95.27849, 67.42286, 20.34733, 102.67339, 93.84615, 128.95366, 69.28015, 138.62953, 94.72963, 129.24376, 66.28535, 27.90273, 58.98529, 29.84631, 47.59564, 118.73823, 77.77458, 72.75859, 18.41622 }; double dvector_zero_data[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; size_t num_numbers = sizeof (dvector_data) / sizeof (*dvector_data); size_t num_zeros = 12; } // namespace OpenMS using namespace OpenMS; using namespace OpenMS::Math; ///////////////////////////////////////////////////////////// START_TEST( BasicStatistics, "$Id$" ); ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION((BasicStatistics())) { BasicStatistics <> stats; stats.update( &*dvector_data, dvector_data + num_numbers ); TEST_EQUAL(num_numbers,195); TOLERANCE_ABSOLUTE(0.1); STATUS( stats ); TEST_REAL_SIMILAR( stats.sum(), 15228.2 ); TEST_REAL_SIMILAR( stats.mean(), 96.4639 ); TEST_REAL_SIMILAR( stats.variance(), 3276.51 ); float fvector_coord[195]; for ( int i = 0; i < 195; fvector_coord[i] = 1000.f - i, ++i ) ; BasicStatistics < double > stats2; stats2.update( &*dvector_data, dvector_data + num_numbers, &*fvector_coord ); STATUS( stats ); TEST_REAL_SIMILAR( stats2.sum(), stats.sum() ); TEST_REAL_SIMILAR( stats2.mean(), 1000. - stats.mean() ); TEST_REAL_SIMILAR( stats2.variance(), 3276.51 ); } END_SECTION //----------------------------------------------------------- START_SECTION((BasicStatistics(BasicStatistics const &arg))) { BasicStatistics <> stats; stats.update( &*dvector_data, dvector_data + num_numbers ); TEST_EQUAL(num_numbers,195); TOLERANCE_ABSOLUTE(0.1); BasicStatistics<> const & stats_cref = stats; BasicStatistics<> stats_copy (stats_cref); TEST_REAL_SIMILAR( stats_copy.sum(), stats.sum() ); TEST_REAL_SIMILAR( stats_copy.mean(), stats.mean() ); TEST_REAL_SIMILAR( stats_copy.variance(), stats.variance() ); } END_SECTION //----------------------------------------------------------- START_SECTION((BasicStatistics& operator=(BasicStatistics const &arg))) { BasicStatistics <> stats; stats.update( &*dvector_data, dvector_data + num_numbers ); TEST_EQUAL(num_numbers,195); TOLERANCE_ABSOLUTE(0.1); BasicStatistics<> const & stats_cref = stats; BasicStatistics<> stats_copy; stats_copy = stats_cref; TEST_REAL_SIMILAR( stats_copy.sum(), stats.sum() ); TEST_REAL_SIMILAR( stats_copy.mean(), stats.mean() ); TEST_REAL_SIMILAR( stats_copy.variance(), stats.variance() ); } END_SECTION //----------------------------------------------------------- START_SECTION((void clear())) { BasicStatistics <> stats; stats.update( &*dvector_data, dvector_data + num_numbers ); TOLERANCE_ABSOLUTE(0.1); TEST_REAL_SIMILAR( stats.sum(), 15228.2 ); TEST_REAL_SIMILAR( stats.mean(), 96.4639 ); TEST_REAL_SIMILAR( stats.variance(), 3276.51 ); stats.clear(); TEST_REAL_SIMILAR( stats.sum(), 0. ); TEST_REAL_SIMILAR( stats.mean(), 0. ); TEST_REAL_SIMILAR( stats.variance(), 0. ); } END_SECTION //----------------------------------------------------------- START_SECTION((template <typename ProbabilityIterator> void update(ProbabilityIterator probability_begin, ProbabilityIterator const probability_end))) { BasicStatistics<> stats; TEST_REAL_SIMILAR( stats.sum(), 0. ); TEST_REAL_SIMILAR( stats.mean(), 0. ); TEST_REAL_SIMILAR( stats.variance(), 0. ); stats.update( &*dvector_data, dvector_data + num_numbers ); TOLERANCE_ABSOLUTE(0.1); TEST_REAL_SIMILAR( stats.sum(), 15228.2 ); TEST_REAL_SIMILAR( stats.mean(), 96.4639 ); TEST_REAL_SIMILAR( stats.variance(), 3276.51 ); stats.update( &*dvector_zero_data, dvector_zero_data + num_zeros ); TEST_REAL_SIMILAR( stats.sum(), 0 ); TEST_REAL_SIMILAR( stats.mean(), 0 ); TEST_REAL_SIMILAR( stats.variance(), 0 ); } END_SECTION //----------------------------------------------------------- START_SECTION((template <typename ProbabilityIterator, typename CoordinateIterator> void update(ProbabilityIterator const probability_begin, ProbabilityIterator const probability_end, CoordinateIterator const coordinate_begin))) { BasicStatistics<> stats; TEST_REAL_SIMILAR( stats.sum(), 0. ); TEST_REAL_SIMILAR( stats.mean(), 0. ); TEST_REAL_SIMILAR( stats.variance(), 0. ); float fvector_coord[195]; for ( int i = 0; i < 195; fvector_coord[i] = 1000.f - i, ++i ) ; stats.update( &*dvector_data, dvector_data + num_numbers, &*fvector_coord ); TOLERANCE_ABSOLUTE(0.1); TEST_REAL_SIMILAR( stats.sum(), 15228.2 ); TEST_REAL_SIMILAR( stats.mean(), 1000.-96.4639 ); TEST_REAL_SIMILAR( stats.variance(), 3276.51 ); } END_SECTION; //----------------------------------------------------------- BasicStatistics<double> bid; START_SECTION((RealType mean() const)) { TEST_EQUAL(bid.mean(),0.); // continued below } END_SECTION START_SECTION((void setMean(RealType const &mean))) { TEST_EQUAL(bid.mean(),0.); bid.setMean(17.); TEST_EQUAL(bid.mean(),17.); } END_SECTION START_SECTION((RealType variance() const)) { TEST_EQUAL(bid.variance(),0.); // continued below } END_SECTION START_SECTION((void setVariance(RealType const &variance))) { TEST_EQUAL(bid.variance(),0.); bid.setVariance(18.); TEST_EQUAL(bid.variance(),18.); } END_SECTION START_SECTION((RealType sum() const)) { TEST_EQUAL(bid.sum(),0.); // continued below } END_SECTION START_SECTION((void setSum(RealType const &sum))) { TEST_EQUAL(bid.sum(),0.); bid.setSum(19.); TEST_EQUAL(bid.sum(),19.); } END_SECTION //----------------------------------------------------------- START_SECTION((static RealType sqrt2pi())) { TEST_EQUAL(BasicStatistics<>::sqrt2pi(),2.50662827463100050240); } END_SECTION START_SECTION((RealType normalDensity_sqrt2pi(RealType coordinate) const)) { bid.clear(); bid.setMean(10.); bid.setVariance(3.); TOLERANCE_ABSOLUTE(.0001); TEST_REAL_SIMILAR(bid.normalDensity_sqrt2pi(10.),1.); TEST_REAL_SIMILAR(bid.normalDensity_sqrt2pi(7.),.22313016014842982893); TEST_REAL_SIMILAR(bid.normalDensity_sqrt2pi(9.),.84648172489061407405); TEST_REAL_SIMILAR(bid.normalDensity_sqrt2pi(11.),.84648172489061407405); } END_SECTION START_SECTION((RealType normalDensity(RealType const coordinate) const)) { bid.clear(); bid.setMean(10.); bid.setVariance(3.); TOLERANCE_ABSOLUTE(.0001); TEST_REAL_SIMILAR(bid.normalDensity(10.),1./2.50662827463100050240); TEST_REAL_SIMILAR(bid.normalDensity(7.),.22313016014842982893/2.50662827463100050240); TEST_REAL_SIMILAR(bid.normalDensity(9.),.84648172489061407405/2.50662827463100050240); TEST_REAL_SIMILAR(bid.normalDensity(11.),.84648172489061407405/2.50662827463100050240); } END_SECTION //----------------------------------------------------------- START_SECTION((void normalApproximation(probability_container &probability, typename probability_container::size_type const size))) { double dvector2_data[] = { 0, 1, 3, 2, 0 }; size_t num2_numbers = sizeof (dvector2_data) / sizeof (*dvector2_data); BasicStatistics <> stats; stats.update( &*dvector2_data, dvector2_data + num2_numbers ); TEST_EQUAL(num2_numbers,5); TOLERANCE_ABSOLUTE(0.1); STATUS( stats ); TEST_REAL_SIMILAR( stats.sum(), 6. ); TEST_REAL_SIMILAR( stats.mean(), 13. / 6. ); TEST_REAL_SIMILAR( stats.variance(), 17. / 36. ); TOLERANCE_ABSOLUTE(0.000001); TEST_REAL_SIMILAR( stats.sqrt2pi(), 2.50662827463100050240 ); TOLERANCE_ABSOLUTE(0.1); for ( double pos = -2.; pos < 6.; pos += .25 ) { STATUS( std::showpoint << "pos:" << pos << " density:" << stats.normalDensity_sqrt2pi ( pos ) / stats.sqrt2pi() ); } std::vector < double > probs; stats.normalApproximation ( probs, 6 ); double good_probs [] = { 0.0241689, 0.824253, 3.38207, 1.66963, 0.0991695, 0.000708684 }; for ( UInt i = 0; i < probs.size(); ++i ) { // STATUS( std::showpoint << "i:" << i << " probs[i]:" << probs[i] << '\n'); TEST_REAL_SIMILAR( probs[i], good_probs[i] ); } // testing START_SECTION((void normalApproximation(probability_container &probability))) std::vector < double > probs2(6); stats.normalApproximation ( probs2 ); for ( UInt i = 0; i < probs2.size(); ++i ) { // STATUS( std::showpoint << "i:" << i << " probs[i]:" << probs[i] << '\n'); TEST_REAL_SIMILAR( probs2[i], good_probs[i] ); } } END_SECTION //----------------------------------------------------------- START_SECTION((void normalApproximation(probability_container &probability))) { // already tested in START_SECTION((void normalApproximation(probability_container &probability, typename probability_container::size_type const size))) NOT_TESTABLE; } END_SECTION //----------------------------------------------------------- START_SECTION((void normalApproximation(probability_container &probability, coordinate_container const &coordinate))) { double magic1 = 200, magic2 = 100; std::vector < double > data ( (UInt) magic1 ); std::copy ( &*dvector_data, dvector_data + num_numbers, std::back_inserter ( data ) ); BasicStatistics <> stats; stats.update( data.begin(), data.end() ); std::vector < double > fit; stats.normalApproximation ( fit, UInt ( data.size() + magic1 ) ); BasicStatistics <> stats2; stats2.update( fit.begin(), fit.end() ); STATUS( stats ); STATUS( stats2 ); TOLERANCE_ABSOLUTE(0.1); TEST_REAL_SIMILAR( stats.sum(), stats2.sum() ); TEST_REAL_SIMILAR( stats.mean(), stats2.mean() ); TEST_REAL_SIMILAR( stats.variance(), stats2.variance() ); std::vector < double > pos2; for ( double i = 0; i < fit.size(); pos2.push_back(i), i += 1./magic2 ) ; std::vector < double > fit2; stats.normalApproximation ( fit2, pos2 ); stats2.update ( fit2.begin(), fit2.end() ); STATUS( stats ); STATUS( stats2 ); TEST_REAL_SIMILAR( stats.sum(), stats2.sum() ); TEST_REAL_SIMILAR( stats.mean(), stats2.mean() / magic2 ); TEST_REAL_SIMILAR( stats.variance(), stats2.variance() / magic2 / magic2 ); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FineIsotopeDistribution_test.cpp
.cpp
15,405
451
// 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/CHEMISTRY/ISOTOPEDISTRIBUTION/FineIsotopePatternGenerator.h> /////////////////////////// #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h> #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsoSpecWrapper.h> #include <OpenMS/CHEMISTRY/Element.h> #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> using namespace OpenMS; using namespace std; START_TEST(FineIsotopePatternGenerator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FineIsotopePatternGenerator* ptr = nullptr; FineIsotopePatternGenerator* nullPointer = nullptr; START_SECTION((FineIsotopePatternGenerator())) ptr = new FineIsotopePatternGenerator(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~FineIsotopePatternGenerator())) delete ptr; END_SECTION START_SECTION(( IsotopeDistribution run(const EmpiricalFormula&) const )) { EmpiricalFormula ef ("C6H12O6"); // simple way of getting an IsotopeDistribution IsotopeDistribution test_id = ef.getIsotopeDistribution(FineIsotopePatternGenerator(0.01, false, false)); TEST_EQUAL(test_id.size(), 3) // simple way of getting an IsotopeDistribution using absolute tol test_id = ef.getIsotopeDistribution(FineIsotopePatternGenerator(0.01, false, true)); TEST_EQUAL(test_id.size(), 3) // simple way of getting an IsotopeDistribution using total probability test_id = ef.getIsotopeDistribution(FineIsotopePatternGenerator(0.01, true, false)); TEST_EQUAL(test_id.size(), 3) { FineIsotopePatternGenerator gen(0.01, false, false); 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.922633) // 0.922119) TEST_REAL_SIMILAR(id[2].getMZ(), 182.068 ) TEST_REAL_SIMILAR(id[2].getIntensity(), 0.0113774 ) } { const double threshold = 1e-5; FineIsotopePatternGenerator gen(threshold, false, false); IsotopeDistribution id = gen.run(ef); TEST_EQUAL(id.size(), 14) TEST_REAL_SIMILAR(id[0].getMZ(), 180.063) TEST_REAL_SIMILAR(id[0].getIntensity(), 0.922633) TEST_REAL_SIMILAR(id[4].getMZ(), 182.068 ) TEST_REAL_SIMILAR(id[4].getIntensity(), 0.0113774 ) TEST_REAL_SIMILAR(id[13].getMZ(), 184.07434277234) TEST_REAL_SIMILAR(id[13].getIntensity(), 2.02975552383577e-05) } { FineIsotopePatternGenerator gen(1e-12, false, false); IsotopeDistribution id = gen.run(ef); TEST_EQUAL(id.size(), 104) gen.setThreshold(1e-25); TEST_EQUAL(gen.run(EmpiricalFormula(ef)).size(), 634) gen.setThreshold(1e-50); TEST_EQUAL(gen.run(EmpiricalFormula(ef)).size(), 1883) gen.setThreshold(1e-100); TEST_EQUAL(gen.run(EmpiricalFormula(ef)).size(), 2548) gen.setThreshold(0.0); TEST_EQUAL(gen.run(EmpiricalFormula(ef)).size(), 2548) } // For a C100 molecule { FineIsotopePatternGenerator gen(0.01, false, false); gen.setThreshold(1e-2); IsotopeDistribution id = gen.run(EmpiricalFormula("C100")); TEST_EQUAL(id.size(), 6) // for (auto i : id.getContainer()) // std::cout << i << std::endl; gen.setThreshold(1e-5); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 9) gen.setThreshold(1e-10); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 14) gen.setThreshold(1e-20); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 21) gen.setThreshold(1e-40); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 34) gen.setThreshold(1e-60); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 46) gen.setThreshold(1e-100); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 65) gen.setThreshold(1e-150); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 86) gen.setThreshold(1e-196); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 100) gen.setThreshold(1e-198); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 101) gen.setThreshold(1e-250); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 101) gen.setThreshold(0.0); TEST_EQUAL(gen.run(EmpiricalFormula("C100")).size(), 101) TEST_REAL_SIMILAR(gen.run(EmpiricalFormula("C100"))[100].getIntensity(), 8.67e-198) // note: Intensity is only float, so nothing beyond 1e-38 TEST_REAL_SIMILAR(gen.run(EmpiricalFormula("C100"))[100].getMZ(), 1300.3355000000001) } // { // std::string formula = "C100H202"; // add 202 hydrogen // FineIsotopePatternGenerator gen(0.99, true, true); // IsotopeDistribution id = gen.run(EmpiricalFormula(formula)); // TEST_EQUAL(id.size(), 9) // for (auto i : id.getContainer()) // std::cout << i << std::endl; // } { std::string formula = "C100H202"; // add 202 hydrogen FineIsotopePatternGenerator gen(0.01, false, false); gen.setThreshold(1e-2); IsotopeDistribution id = gen.run(EmpiricalFormula(formula)); TEST_EQUAL(id.size(), 9) gen.setThreshold(1e-5); TEST_EQUAL(gen.run(EmpiricalFormula(formula)).size(), 21) id = gen.run(EmpiricalFormula(formula)); gen.setThreshold(1e-10); TEST_EQUAL(gen.run(EmpiricalFormula(formula)).size(), 50) gen.setThreshold(1e-20); TEST_EQUAL(gen.run(EmpiricalFormula(formula)).size(), 131) gen.setThreshold(1e-40); TEST_EQUAL(gen.run(EmpiricalFormula(formula)).size(), 368) gen.setThreshold(1e-60); TEST_EQUAL(gen.run(EmpiricalFormula(formula)).size(), 677) gen.setThreshold(1e-100); TEST_EQUAL(gen.run(EmpiricalFormula(formula)).size(), 1474) gen.setThreshold(1e-150); TEST_EQUAL(gen.run(EmpiricalFormula(formula)).size(), 2743) gen.setThreshold(1e-250); TEST_EQUAL(gen.run(EmpiricalFormula(formula)).size(), 5726) gen.setThreshold(1e-320); TEST_EQUAL(gen.run(EmpiricalFormula(formula)).size(), 7687) gen.setThreshold(0.0); TEST_EQUAL(gen.run(EmpiricalFormula(formula)).size(), 101* 203) } // Also test a molecule with 2048 atoms (a value that does not fit into the // lookup table any more, it should still work). { FineIsotopePatternGenerator gen(0.01, false, false); gen.setThreshold(1e-2); IsotopeDistribution id = gen.run(EmpiricalFormula("C2048")); TEST_EQUAL(id.size(), 28) gen.setThreshold(1e-5); TEST_EQUAL(gen.run(EmpiricalFormula("C2048")).size(), 44) } } END_SECTION START_SECTION(( [EXTRA CH]IsotopeDistribution run(const EmpiricalFormula&) const )) { EmpiricalFormula ef ("C6H12O6"); { FineIsotopePatternGenerator gen(0.01, false, false); 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.922633) // 0.922119) TEST_REAL_SIMILAR(id[2].getMZ(), 182.068 ) TEST_REAL_SIMILAR(id[2].getIntensity(), 0.0113774 ) } ef.setCharge(2); { FineIsotopePatternGenerator gen(0.01, false, false); IsotopeDistribution id = gen.run(ef); TEST_EQUAL(id.size(), 3) TEST_REAL_SIMILAR(id[0].getMZ(), 182.0790404466) TEST_REAL_SIMILAR(id[0].getIntensity(), 0.922421) TEST_REAL_SIMILAR(id[2].getMZ(), 184.0832944466) TEST_REAL_SIMILAR(id[2].getIntensity(), 0.0113774 ) } ef.setCharge(-2); { FineIsotopePatternGenerator gen(0.01, false, false); TEST_EXCEPTION(Exception::Precondition, gen.run(ef)); // negative charge not allowed } } END_SECTION START_SECTION(( [EXTRA]IsotopeDistribution run(const EmpiricalFormula&) const )) { { // human insulin EmpiricalFormula ef ("C520H817N139O147S8"); FineIsotopePatternGenerator gen(0.01, false, false); IsotopeDistribution id = gen.run(ef); TEST_EQUAL(id.size(), 267) gen.setThreshold(1e-5); IsotopeDistribution id2 = gen.run(ef); TEST_EQUAL(id2.size(), 5513) IsotopeDistribution id3 = ef.getIsotopeDistribution(FineIsotopePatternGenerator(0.01, false, false)); TEST_EQUAL(id3.size(), 267) IsotopeDistribution id4 = ef.getIsotopeDistribution(FineIsotopePatternGenerator(1e-5, false, false)); TEST_EQUAL(id4.size(), 5513) } { EmpiricalFormula ef("C222N190O110"); FineIsotopePatternGenerator gen(0.01, false, false); gen.setThreshold(1e-3); IsotopeDistribution id = gen.run(ef); TEST_EQUAL(id.size(), 154) // int idx = 0; for (const auto ele : id ) std::cout << idx++ << " : " << ele << std::endl; TEST_REAL_SIMILAR(id[0].getMZ(), 7084.02466902) TEST_REAL_SIMILAR(id[0].getIntensity(), 0.0348636) // cmp with 0.0349429 TEST_REAL_SIMILAR(id[1].getMZ(), 7085.0217039152) TEST_REAL_SIMILAR(id[2].getMZ(), 7085.0280238552) TEST_REAL_SIMILAR(id[3].getMZ(), 7085.0288861574) TEST_REAL_SIMILAR(id[1].getIntensity() + id[2].getIntensity() + id[3].getIntensity(), 0.109638) // cmp with 0.109888 TEST_REAL_SIMILAR(id[4].getMZ(), 7086.0187388104) TEST_REAL_SIMILAR(id[9].getMZ(), 7086.0322409926) TEST_REAL_SIMILAR(id[4].getIntensity() + id[5].getIntensity() + id[6].getIntensity() + id[7].getIntensity() + id[8].getIntensity() + id[9].getIntensity(), 0.179746) // cmp with 0.180185 -- difference of 0.24% TEST_REAL_SIMILAR(id[10].getMZ(), 7087.0157737056) TEST_REAL_SIMILAR(id[19].getMZ(), 7087.0355958278) TEST_REAL_SIMILAR(id[10].getIntensity() + id[11].getIntensity() + id[12].getIntensity() + id[13].getIntensity() + id[14].getIntensity() + id[15].getIntensity() + id[16].getIntensity() + id[17].getIntensity() + id[18].getIntensity() + id[19].getIntensity(), 0.203836) // cmp with 0.204395 -- difference of 0.27% // Cmp with CoarseIsotopePatternGenerator: // 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)); } { // test gapped isotope distributions, e.g. bromide 79,81 (missing 80) EmpiricalFormula ef("CBr2"); FineIsotopePatternGenerator gen(0.01, false, false); gen.setThreshold(1e-3); IsotopeDistribution id = gen.run(ef); // int idx = 0; for (const auto ele : id ) std::cout << idx++ << " : " << ele << std::endl; TEST_REAL_SIMILAR(id[0].getMZ(), 169.8366742) TEST_REAL_SIMILAR(id[1].getMZ(), 170.8400292) IsotopeDistribution::ContainerType container; 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()) } } #if 0 // Do some stress testing of the library... // Stress test takes about 20 seconds // there is a significant drop in speed due to copying (and sorting) of data int sum = 0; for (Size k = 0; k < 2e5; k++) { EmpiricalFormula ef ("C520H817N139O147"); FineIsotopePatternGenerator gen(1e-2, false, false); IsotopeDistribution id = gen.run(ef); sum += id.size(); } TEST_EQUAL(sum, 139*2*1e5) // we use OpenMS isotopic tables, we get 139 instead of 140 int calculated_masses = 0; for (Size k = 0; k < 100; k++) { // human insulin EmpiricalFormula ef (String("C") + (520 + k) + String("H") + (817 + k) + String("N") + (139 + k) + String("O") + (147 + k) + String("S") + ( 8 + int(k/5)) ); // Sulfur is hard to do because of the abundant isotope 34 std::cout << " Working on stress test " << k << " " << ef.toString() << std::endl; { FineIsotopePatternGenerator gen(0.01, false, false); IsotopeDistribution id = gen.run(ef); calculated_masses += id.size(); gen.setThreshold(1e-5); id = gen.run(ef); calculated_masses += id.size(); } } TEST_EQUAL(calculated_masses, 1592882) for (Size k = 0; k < 100; k++) { // human insulin EmpiricalFormula ef (String("C") + (520 + k) + String("H") + (817 + k) + String("N") + (139 + k) + String("O") + (147 + k) + String("S") + ( 8 + int(k/5)) ); // Sulfur is hard to do because of the abundant isotope 34 std::cout << " Working on stress test " << k << " " << ef.toString() << std::endl; { FineIsotopePatternGenerator gen(0.01, false, false); IsotopeDistribution id = gen.run(ef); calculated_masses += id.size(); gen.setThreshold(1e-5); id = gen.run(ef); calculated_masses += id.size(); } } TEST_EQUAL(calculated_masses, 1592882*2) // repeat the test, we should get the same result #endif } END_SECTION START_SECTION(( void setAbsolute(bool absolute) )) { { FineIsotopePatternGenerator gen(0.01, false, false); gen.setAbsolute(true); TEST_EQUAL(gen.getAbsolute(), true); gen.setAbsolute(false); TEST_EQUAL(gen.getAbsolute(), false); } // human insulin EmpiricalFormula ef ("C520H817N139O147S8"); { FineIsotopePatternGenerator gen(0.01, false, false); IsotopeDistribution id = gen.run(ef); TEST_EQUAL(id.size(), 267) gen.setAbsolute(true); id = gen.run(ef); TEST_EQUAL(id.size(), 21) gen.setThreshold(1e-3); id = gen.run(ef); TEST_EQUAL(id.size(), 151) } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MultiplexFilteredMSExperiment_test.cpp
.cpp
1,892
68
// 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/MultiplexFilteredPeak.h> #include <OpenMS/FEATUREFINDER/MultiplexFilteredMSExperiment.h> using namespace OpenMS; START_TEST(MultiplexFilteredMSExperiment, "$Id$") MultiplexFilteredMSExperiment* nullPointer = nullptr; MultiplexFilteredMSExperiment* ptr; START_SECTION(MultiplexFilteredMSExperiment()) MultiplexFilteredMSExperiment exp; TEST_EQUAL(exp.size(), 0); ptr = new MultiplexFilteredMSExperiment(); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION MultiplexFilteredMSExperiment exp; MultiplexFilteredPeak peak(654.32, 2345.67, 24, 110); exp.addPeak(peak); size_t n; START_SECTION(addPeak(const MultiplexFilteredPeak& peak)) n = exp.size(); MultiplexFilteredPeak peak_temp(655.32, 2346.67, 25, 111); exp.addPeak(peak_temp); TEST_EQUAL(exp.size(), n + 1); END_SECTION START_SECTION(MultiplexFilteredPeak getPeak(size_t i)) MultiplexFilteredPeak peak = exp.getPeak(0); TEST_REAL_SIMILAR(peak.getMZ(), 654.32); END_SECTION START_SECTION(double getMZ(size_t i)) TEST_REAL_SIMILAR(exp.getMZ(0), 654.32); END_SECTION START_SECTION(std::vector<double> getMZ()) TEST_REAL_SIMILAR(exp.getMZ()[0], 654.32); END_SECTION START_SECTION(double getRT(size_t i)) TEST_REAL_SIMILAR(exp.getRT(0), 2345.67); END_SECTION START_SECTION(std::vector<double> getRT()) TEST_REAL_SIMILAR(exp.getRT()[0], 2345.67); END_SECTION START_SECTION(size_t size()) TEST_EQUAL(exp.size(), 2); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MRMFeatureSelector_test.cpp
.cpp
16,405
409
// 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, Svetlana Kutuzova $ // $Authors: Douglas McCloskey, Pasquale Domenico Colaianni, Svetlana Kutuzova $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/ANALYSIS/OPENSWATH/MRMBatchFeatureSelector.h> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureSelector.h> /////////////////////////// #define TRANSITIONTSVREADER_TESTING 1 using namespace OpenMS; using namespace std; START_TEST(MRMFeatureSelector, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// const String features_path = OPENMS_GET_TEST_DATA_PATH("MRMFeatureSelector_150601_0_BloodProject01_PLT_QC_Broth-1_1_reduced.featureXML"); const String features_path_small = OPENMS_GET_TEST_DATA_PATH("MRMFeatureSelector_100ug.featureXML"); MRMFeatureSelectorScore* ptr = nullptr; MRMFeatureSelectorScore* null_ptr = nullptr; START_SECTION(MRMFeatureSelectorScore()) { ptr = new MRMFeatureSelectorScore(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~MRMFeatureSelectorScore()) { delete ptr; } END_SECTION START_SECTION(MRMFeatureSelectorScore::selectMRMFeature()) { FeatureMap feature_map; FeatureXMLFile feature_file; feature_file.load(features_path, feature_map); TEST_EQUAL(feature_map.size(), 210); MRMFeatureSelector::SelectorParameters parameters; parameters.select_transition_group = true; parameters.segment_window_length = -1; parameters.segment_step_length = -1; parameters.variable_type = MRMFeatureSelector::VariableType::INTEGER; parameters.optimal_threshold = 0.5; parameters.score_weights = { {"sn_ratio", MRMFeatureSelector::LambdaScore::LOG}, {"peak_apices_sum", MRMFeatureSelector::LambdaScore::LOG} }; MRMFeatureSelectorScore selectorScore; FeatureMap output_selected; selectorScore.selectMRMFeature(feature_map, output_selected, parameters); TEST_EQUAL(output_selected.size(), 37); const Feature& f1 = output_selected[0].getSubordinates()[0]; TEST_REAL_SIMILAR(f1.getMetaValue("peak_apex_int"), 286.0); TEST_STRING_EQUAL(f1.getMetaValue("native_id").toString(), "23dpg.23dpg_1.Heavy"); TEST_REAL_SIMILAR(f1.getRT(), 16.7592102584839); const Feature& f2 = output_selected[9].getSubordinates()[0]; TEST_REAL_SIMILAR(f2.getMetaValue("peak_apex_int"), 8671.5); TEST_STRING_EQUAL(f2.getMetaValue("native_id").toString(), "Pool_2pg_3pg.Pool_2pg_3pg_1.Heavy"); TEST_REAL_SIMILAR(f2.getRT(), 16.1933587515513); } END_SECTION START_SECTION(removeSpaces_()) { MRMFeatureSelector_test selector; TEST_STRING_EQUAL(selector.removeSpaces_("h e ll o"), "hello"); TEST_STRING_EQUAL(selector.removeSpaces_("hello"), "hello"); TEST_STRING_EQUAL(selector.removeSpaces_(""), ""); TEST_STRING_EQUAL(selector.removeSpaces_("A B"), "AB"); } END_SECTION START_SECTION(constructTargTransList_()) { MRMFeatureSelector_test selector; FeatureMap feature_map; FeatureXMLFile feature_file; feature_file.load(features_path, feature_map); vector<pair<double, String>> time_to_name; map<String, vector<Feature>> feature_name_map; const bool select_transition_group = true; selector.constructTargTransList_(feature_map, time_to_name, feature_name_map, select_transition_group); TEST_EQUAL(time_to_name.size(), 37) TEST_EQUAL(feature_name_map.size(), 37) sort(time_to_name.begin(), time_to_name.end()); pair<double, String> *p = nullptr; p = &time_to_name.front(); TEST_REAL_SIMILAR(p->first, 0) TEST_STRING_EQUAL(p->second, "arg-L") p = &time_to_name[1]; TEST_REAL_SIMILAR(p->first, 1.314232178) TEST_STRING_EQUAL(p->second, "asn-L") p = &time_to_name[5]; TEST_REAL_SIMILAR(p->first, 1.421901525) TEST_STRING_EQUAL(p->second, "citr-L") p = &time_to_name[7]; TEST_REAL_SIMILAR(p->first, 2.667749413) TEST_STRING_EQUAL(p->second, "AICAr") p = &time_to_name.back(); TEST_REAL_SIMILAR(p->first, 99.98770892) TEST_STRING_EQUAL(p->second, "accoa") } END_SECTION START_SECTION(weightScore_()) { MRMFeatureSelector_test selector; double score; score = selector.weightScore_(3413.0, MRMFeatureSelector::LambdaScore::LINEAR); TEST_REAL_SIMILAR(score, 3413.0) score = selector.weightScore_(341.0, MRMFeatureSelector::LambdaScore::INVERSE); TEST_REAL_SIMILAR(score, 0.002932551) score = selector.weightScore_(341.0, MRMFeatureSelector::LambdaScore::LOG); TEST_REAL_SIMILAR(score, 5.831882477) score = selector.weightScore_(96640.0, MRMFeatureSelector::LambdaScore::INVERSE_LOG); TEST_REAL_SIMILAR(score, 0.087117) score = selector.weightScore_(341.0, MRMFeatureSelector::LambdaScore::INVERSE_LOG10); TEST_REAL_SIMILAR(score, 0.394827074) } END_SECTION START_SECTION(computeScore_()) { MRMFeatureSelector_test selector; double score; Feature feature; feature.setMetaValue("sn_ratio", 6.84619503982874); feature.setMetaValue("peak_apices_sum", 96640.0); score = selector.computeScore_(feature, {{"sn_ratio", MRMFeatureSelector::LambdaScore::INVERSE_LOG}}); TEST_REAL_SIMILAR(score, 0.5198334582314795) score = selector.computeScore_(feature, {{"peak_apices_sum", MRMFeatureSelector::LambdaScore::INVERSE_LOG10}}); TEST_REAL_SIMILAR(score, 0.20059549093267626) score = selector.computeScore_(feature, { {"sn_ratio", MRMFeatureSelector::LambdaScore::INVERSE_LOG}, {"peak_apices_sum", MRMFeatureSelector::LambdaScore::INVERSE_LOG10} }); TEST_REAL_SIMILAR(score, 0.10427624775717449) // Checks for bad input feature.setMetaValue("sn_ratio", 0.0); feature.setMetaValue("peak_apices_sum", 0.0); feature.setMetaValue("var_xcorr_coelution", -1.0); score = selector.computeScore_(feature, { {"sn_ratio", MRMFeatureSelector::LambdaScore::INVERSE} }); TEST_REAL_SIMILAR(score, 1.0) score = selector.computeScore_(feature, { {"peak_apices_sum", MRMFeatureSelector::LambdaScore::LOG} }); TEST_REAL_SIMILAR(score, 1.0) score = selector.computeScore_(feature, { {"var_xcorr_coelution", MRMFeatureSelector::LambdaScore::LOG} }); TEST_REAL_SIMILAR(score, 1.0) } END_SECTION START_SECTION(batchMRMFeaturesQMIP() integer) // integer variable type { FeatureMap feature_map; FeatureXMLFile feature_file; feature_file.load(features_path_small, feature_map); MRMFeatureSelector::SelectorParameters params1; params1.nn_threshold = 4; params1.locality_weight = "false"; params1.select_transition_group = "true"; params1.segment_window_length = 8; params1.segment_step_length = 4; params1.variable_type = MRMFeatureSelector::VariableType::INTEGER; params1.optimal_threshold = 0.5; params1.score_weights = { // {"sn_ratio", MRMFeatureSelector::LambdaScore::INVERSE_LOG}, // {"peak_apices_sum", MRMFeatureSelector::LambdaScore::INVERSE_LOG10} {"sn_ratio", MRMFeatureSelector::LambdaScore::LINEAR}, {"peak_apices_sum", MRMFeatureSelector::LambdaScore::LINEAR} }; MRMFeatureSelector::SelectorParameters params2 = params1; params2.segment_window_length = -1; params2.segment_step_length = -1; FeatureMap output_selected; MRMBatchFeatureSelector::batchMRMFeaturesQMIP(feature_map, output_selected, {params1, params2}); sort(output_selected.begin(), output_selected.end(), [](const Feature& a, const Feature& b){ return a.getMetaValue("PeptideRef").toString() < b.getMetaValue("PeptideRef").toString(); }); TEST_EQUAL(output_selected.size(), 8); TEST_STRING_EQUAL(output_selected[0].getMetaValue("PeptideRef"), "5-HTP"); TEST_REAL_SIMILAR(output_selected[0].getRT(), 2.03215546258545); TEST_STRING_EQUAL(output_selected[1].getMetaValue("PeptideRef"), "Acetylserotonin"); TEST_REAL_SIMILAR(output_selected[1].getRT(), 5.07082551965332); TEST_STRING_EQUAL(output_selected[2].getMetaValue("PeptideRef"), "Acetyltryptamine"); TEST_REAL_SIMILAR(output_selected[2].getRT(), 6.96528256036377); TEST_STRING_EQUAL(output_selected[3].getMetaValue("PeptideRef"), "Melatonin"); TEST_REAL_SIMILAR(output_selected[3].getRT(), 6.96528256036377); TEST_STRING_EQUAL(output_selected[4].getMetaValue("PeptideRef"), "Riboflavin"); TEST_REAL_SIMILAR(output_selected[4].getRT(), 5.07082551965332); TEST_STRING_EQUAL(output_selected[5].getMetaValue("PeptideRef"), "Serotonin"); TEST_REAL_SIMILAR(output_selected[5].getRT(), 1.78708603594971); TEST_STRING_EQUAL(output_selected[6].getMetaValue("PeptideRef"), "Tryptamine"); TEST_REAL_SIMILAR(output_selected[6].getRT(), 3.43251273956299); TEST_STRING_EQUAL(output_selected[7].getMetaValue("PeptideRef"), "Tryptophan"); TEST_REAL_SIMILAR(output_selected[7].getRT(), 3.43251273956299); // DEBUG // sort(output_selected.begin(), output_selected.end(), [](const Feature& a, const Feature& b){ return a.getRT() < b.getRT(); }); cout << "\n\nSTART DEBUG INFO" << endl; for (size_t i = 0; i < output_selected.size(); ++i) { const Feature& f = output_selected[i]; cout << "[" << i << "]\t\t" << f.getMetaValue("PeptideRef") << "\t\t" << f.getRT() << endl; for (size_t j = 0; j < f.getSubordinates().size(); ++j) { cout << "[" << i << "][" << j << "]\t\t" << f.getSubordinates()[j].getMetaValue("native_id") << "\t\t" << f.getSubordinates()[j].getMetaValue("peak_apex_int") << endl; } } cout << "END DEBUG INFO\n" << endl; } END_SECTION START_SECTION(batchMRMFeaturesQMIP() continuous) // continuous variable type { FeatureMap feature_map; FeatureXMLFile feature_file; feature_file.load(features_path, feature_map); MRMFeatureSelector::SelectorParameters params1; params1.nn_threshold = 4; params1.locality_weight = false; params1.select_transition_group = true; params1.segment_window_length = 8; params1.segment_step_length = 4; params1.variable_type = MRMFeatureSelector::VariableType::CONTINUOUS; params1.optimal_threshold = 0.5; params1.score_weights = { // {"sn_ratio", MRMFeatureSelector::LambdaScore::INVERSE_LOG}, // {"peak_apices_sum", MRMFeatureSelector::LambdaScore::INVERSE_LOG10} {"sn_ratio", MRMFeatureSelector::LambdaScore::LINEAR}, {"peak_apices_sum", MRMFeatureSelector::LambdaScore::LINEAR} }; MRMFeatureSelector::SelectorParameters params2 = params1; params2.segment_window_length = -1; params2.segment_step_length = -1; FeatureMap output_selected; MRMBatchFeatureSelector::batchMRMFeaturesQMIP(feature_map, output_selected, {params1, params2}); sort(output_selected.begin(), output_selected.end(), [](const Feature& a, const Feature& b){ return a.getMetaValue("PeptideRef").toString() < b.getMetaValue("PeptideRef").toString(); }); /// @todo WARNING: This test is flaky on clang vs gcc. Deactivated. //TEST_EQUAL(output_selected.size(), 11); const Feature* f = &output_selected[0].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 0.0); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "AICAr.AICAr_1.Heavy"); TEST_REAL_SIMILAR(f->getRT(), 1.19311977717082); f = &output_selected[1].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 0.0); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "Hexose_Pool_fru_glc-D.Hexose_Pool_fru_glc-D_1.Heavy"); TEST_REAL_SIMILAR(f->getRT(), 1.52517738800049); f = &output_selected[2].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 318.5); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "Lcystin.Lcystin_1.Heavy"); TEST_REAL_SIMILAR(f->getRT(), 0.796409679158529); /// @todo WARNING: This test is flaky on clang vs gcc. Deactivated. //f = &output_selected[10].getSubordinates()[0]; //TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 0.0); //TEST_STRING_EQUAL(f->getMetaValue("native_id"), "cytd.cytd_1.Heavy"); //TEST_REAL_SIMILAR(f->getRT(), 1.4385963780721); // // DEBUG // // sort(output_selected.begin(), output_selected.end(), [](const Feature& a, const Feature& b){ return a.getRT() < b.getRT(); }); // for (const Feature& f : output_selected) // { // cout << f.getMetaValue("PeptideRef") << "\t" << f << endl; // } } END_SECTION START_SECTION(batchMRMFeaturesQMIP() continuous but smaller experiment) // continuous variable type { FeatureMap feature_map; FeatureXMLFile feature_file; feature_file.load(features_path_small, feature_map); MRMFeatureSelector::SelectorParameters params1; params1.nn_threshold = 4; params1.locality_weight = false; params1.select_transition_group = true; params1.segment_window_length = 8; params1.segment_step_length = 4; params1.variable_type = MRMFeatureSelector::VariableType::CONTINUOUS; params1.optimal_threshold = 0.5; params1.score_weights = { // {"sn_ratio", MRMFeatureSelector::LambdaScore::INVERSE_LOG}, // {"peak_apices_sum", MRMFeatureSelector::LambdaScore::INVERSE_LOG10} {"sn_ratio", MRMFeatureSelector::LambdaScore::LINEAR}, {"peak_apices_sum", MRMFeatureSelector::LambdaScore::LINEAR} }; MRMFeatureSelector::SelectorParameters params2 = params1; params2.segment_window_length = -1; params2.segment_step_length = -1; FeatureMap output_selected; MRMBatchFeatureSelector::batchMRMFeaturesQMIP(feature_map, output_selected, {params1, params2}); sort(output_selected.begin(), output_selected.end(), [](const Feature& a, const Feature& b){ return a.getMetaValue("PeptideRef").toString() < b.getMetaValue("PeptideRef").toString(); }); TEST_EQUAL(output_selected.size(), 8); const Feature* f = &output_selected[0].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 29.5228353632885); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "5-HTP"); TEST_REAL_SIMILAR(f->getRT(), 2.03215546258545); f = &output_selected[1].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 30.7684884945637); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "Acetylserotonin"); TEST_REAL_SIMILAR(f->getRT(), 5.07082551965332); f = &output_selected[2].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 28.4325753928028); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "Acetyltryptamine"); TEST_REAL_SIMILAR(f->getRT(), 6.96528256036377); f = &output_selected[3].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 28.4325753928028); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "Melatonin"); TEST_REAL_SIMILAR(f->getRT(), 6.96528256036377); f = &output_selected[4].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 30.7684884945637); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "Riboflavin"); TEST_REAL_SIMILAR(f->getRT(), 5.07082551965332); f = &output_selected[5].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 22.6054459245013); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "Serotonin"); TEST_REAL_SIMILAR(f->getRT(), 1.78708603594971); f = &output_selected[6].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 37.9693079695627); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "Tryptamine"); TEST_REAL_SIMILAR(f->getRT(), 3.43251273956299); f = &output_selected[7].getSubordinates()[0]; TEST_REAL_SIMILAR(f->getMetaValue("peak_apex_int"), 37.9693079695627); TEST_STRING_EQUAL(f->getMetaValue("native_id"), "Tryptophan"); TEST_REAL_SIMILAR(f->getRT(), 3.43251273956299); // // DEBUG // // sort(output_selected.begin(), output_selected.end(), [](const Feature& a, const Feature& b){ return a.getRT() < b.getRT(); }); cout << "\n\nSTART DEBUG INFO" << endl; for (size_t i = 0; i < output_selected.size(); ++i) { const Feature& f = output_selected[i]; cout << "[" << i << "]\t\t" << f.getMetaValue("PeptideRef") << "\t\t" << f.getRT() << endl; for (size_t j = 0; j < f.getSubordinates().size(); ++j) { cout << "[" << i << "][" << j << "]\t\t" << f.getSubordinates()[j].getMetaValue("native_id") << "\t\t" << f.getSubordinates()[j].getMetaValue("peak_apex_int") << endl; } } cout << "END DEBUG INFO\n" << endl; } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/File_test.cpp
.cpp
16,852
431
// 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, Marc Sturm $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> ///////////////////////////////////////////////////////////// #include <OpenMS/SYSTEM/File.h> #include <OpenMS/DATASTRUCTURES/Param.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/CONCEPT/VersionInfo.h> #include <OpenMS/FORMAT/TextFile.h> #include <OpenMS/SYSTEM/File.h> #include <QDir> #include <fstream> #include <filesystem> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(TextFile, "$Id$") ///////////////////////////////////////////////////////////// START_SECTION((static String getExecutablePath())) TEST_NOT_EQUAL(File::getExecutablePath().size(), 0) END_SECTION START_SECTION((static bool exists(const String &file))) TEST_EQUAL(File::exists("does_not_exists.txt"), false) TEST_EQUAL(File::exists(""), false) TEST_EQUAL(File::exists(OPENMS_GET_TEST_DATA_PATH("File_test_text.txt")), true) END_SECTION START_SECTION((static bool empty(const String &file))) TEST_EQUAL(File::empty("does_not_exists.txt"), true) TEST_EQUAL(File::empty(OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt")), true) TEST_EQUAL(File::empty(OPENMS_GET_TEST_DATA_PATH("File_test_text.txt")), false) END_SECTION START_SECTION((static UInt64 fileSize(const String& file))) TEST_EQUAL(File::fileSize("does_not_exists.txt"), -1) TEST_EQUAL(File::fileSize(OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt")), 0) TEST_EQUAL(File::fileSize(OPENMS_GET_TEST_DATA_PATH("File_test_text.txt")), 15) END_SECTION START_SECTION((static bool remove(const String &file))) //deleting non-existing file TEST_EQUAL(File::remove("does_not_exists.txt"), true) //deleting existing file String filename; NEW_TMP_FILE(filename); ofstream os; os.open (filename.c_str(), ofstream::out); os << "File_test dummy file to delete" << endl; os.close(); TEST_EQUAL(File::remove(filename), true) END_SECTION START_SECTION((static bool readable(const String &file))) TEST_EQUAL(File::readable("does_not_exists.txt"), false) TEST_EQUAL(File::readable(OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt")), true) TEST_EQUAL(File::readable(OPENMS_GET_TEST_DATA_PATH("File_test_text.txt")), true) TEST_EQUAL(File::readable(""), false) END_SECTION START_SECTION((static bool writable(const String &file))) TEST_EQUAL(File::writable("/this/file/cannot/be/written.txt"), false) TEST_EQUAL(File::writable(OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt")), true) TEST_EQUAL(File::writable(OPENMS_GET_TEST_DATA_PATH("File_test_imaginary.txt")), true) String filename; NEW_TMP_FILE(filename); TEST_EQUAL(File::writable(filename), true) END_SECTION START_SECTION((static String find(const String &filename, StringList directories=StringList()))) TEST_EXCEPTION(Exception::FileNotFound, File::find("File.h")) String s_obo = File::find("CV/psi-ms.obo"); TEST_EQUAL(s_obo.empty(), false); TEST_EQUAL(File::find(s_obo), s_obo); // iterative finding should return the identical file TEST_EXCEPTION(Exception::FileNotFound, File::find("")) END_SECTION #ifdef ENABLE_DOCS START_SECTION((static String findDoc(const String& filename))) TEST_EXCEPTION(Exception::FileNotFound,File::findDoc("non-existing-documentation")) // should exist in every valid source tree (we cannot test for Doxyfile since doxygen might not be installed) TEST_EQUAL(File::findDoc("doxygen/Doxyfile.in").hasSuffix("Doxyfile.in"), true) // a file from the build tree TEST_EQUAL(File::findDoc("code_examples/cmake_install.cmake").hasSuffix("cmake_install.cmake"), true) END_SECTION #endif START_SECTION((static String absolutePath(const String &file))) NOT_TESTABLE END_SECTION START_SECTION((static String path(const String &file))) TEST_EQUAL(File::path("/source/config/bla/bluff.h"), "/source/config/bla"); TEST_EQUAL(File::path("c:\\config\\bla\\tuff.h"), "c:\\config\\bla"); TEST_EQUAL(File::path("filename_only.h"), "."); // useful when you want to reassemble a full path using path() + '/' + basename(), but the input is only a filename TEST_EQUAL(File::path("/path/only/"), "/path/only"); END_SECTION START_SECTION((static String basename(const String &file))) TEST_EQUAL(File::basename("/source/config/bla/bluff.h"), "bluff.h"); TEST_EQUAL(File::basename("filename_only.h"), "filename_only.h"); TEST_EQUAL(File::basename("/path/only/"), ""); END_SECTION START_SECTION((static bool fileList(const String &dir, const String &file_pattern, StringList &output, bool full_path=false))) StringList vec; TEST_EQUAL(File::fileList(OPENMS_GET_TEST_DATA_PATH(""), "*.bliblaluff", vec), false); TEST_EQUAL(File::fileList(OPENMS_GET_TEST_DATA_PATH(""), "File_test_text.txt", vec), true); TEST_EQUAL(vec[0], "File_test_text.txt"); TEST_EQUAL(File::fileList(OPENMS_GET_TEST_DATA_PATH(""), "File_test_text.txt", vec, true), true); // can't use "path + separator + filename", because sep. might be "/" or "\\" TEST_EQUAL(vec[0].hasPrefix(OPENMS_GET_TEST_DATA_PATH("")), true); TEST_EQUAL(vec[0].hasSuffix("File_test_text.txt"), true); END_SECTION START_SECTION((static String getUniqueName(bool include_hostname = true))) String unique_name = File::getUniqueName(); String unique_name_no_host = File::getUniqueName(false); TEST_EQUAL(unique_name.size() > unique_name_no_host.size(), true) // test if the string consists of four parts StringList split; unique_name.split('_', split); TEST_EQUAL(split.size() >= 4, true) // if name of machine also contains '_' ... END_SECTION START_SECTION((static String getOpenMSDataPath())) NOT_TESTABLE END_SECTION START_SECTION((static bool isDirectory(const String& path))) TEST_EQUAL(File::isDirectory(""),false) TEST_EQUAL(File::isDirectory("."),true) TEST_EQUAL(File::isDirectory(OPENMS_GET_TEST_DATA_PATH("")),true) TEST_EQUAL(File::isDirectory(OPENMS_GET_TEST_DATA_PATH("does_not_exists.txt")),false) TEST_EQUAL(File::isDirectory(OPENMS_GET_TEST_DATA_PATH("File_test_text.txt")),false) END_SECTION // make source directory and copy it to new location // check copy function and if file exists in target path START_SECTION(static bool copyDirRecursively(const QString &fromDir, const QString &toDir,File::CopyOptions option = CopyOptions::OVERWRITE)) // folder OpenMS/src/tests/class_tests/openms/data/XMassFile_test String source_name = OPENMS_GET_TEST_DATA_PATH("XMassFile_test"); String target_name = File::getTempDirectory() + "/" + File::getUniqueName() + "/"; // test canonical path TEST_EQUAL(File::copyDirRecursively(source_name.toQString(),source_name.toQString()),false) // test default TEST_EQUAL(File::copyDirRecursively(source_name.toQString(),target_name.toQString()),true) TEST_EQUAL(File::exists(target_name + "/pdata/1/proc"),true); // overwrite file content std::ofstream ow_ofs; ow_ofs.open(target_name + "/pdata/1/proc"); ow_ofs << "This line can be used to test the overwrite option"; ow_ofs.close(); // check file size std::ifstream infile; infile.open(target_name + "/pdata/1/proc"); infile.seekg(0,infile.end); long file_size = infile.tellg(); infile.close(); TEST_EQUAL(file_size,50) // test option skip TEST_EQUAL(File::copyDirRecursively(source_name.toQString(),target_name.toQString(), File::CopyOptions::SKIP),true) infile.open(target_name + "/pdata/1/proc"); infile.seekg(0,infile.end); file_size = infile.tellg(); infile.close(); TEST_EQUAL(file_size,50) // test option overwrite TEST_EQUAL(File::copyDirRecursively(source_name.toQString(),target_name.toQString(), File::CopyOptions::OVERWRITE),true) infile.open(target_name + "/pdata/1/proc"); infile.seekg(0,infile.end); file_size = infile.tellg(); infile.close(); TEST_EQUAL(file_size,3558) // test option cancel TEST_EQUAL(File::copyDirRecursively(source_name.toQString(),target_name.toQString(), File::CopyOptions::CANCEL),false) // remove temporary directory after testing File::removeDirRecursively(target_name); END_SECTION START_SECTION(static bool removeDirRecursively(const String &dir_name)) QDir d; String dirname = File::getTempDirectory() + "/" + File::getUniqueName() + "/" + File::getUniqueName() + "/"; TEST_TRUE(d.mkpath(dirname.toQString())); TextFile tf; tf.store(dirname + "test.txt"); TEST_EQUAL(File::removeDirRecursively(dirname), true) END_SECTION START_SECTION(static bool makeDir(const String& dir_name)) File::TempDir tdir; String dirname = tdir.getPath() + "/" + File::getUniqueName() + "/" + File::getUniqueName() + "/"; // absolute path TEST_FALSE(File::isDirectory(dirname)) TEST_TRUE(File::makeDir(dirname)) TEST_TRUE(File::isDirectory(dirname)) // a relative path auto current_path = std::filesystem::current_path(); // get current path filesystem::current_path(std::filesystem::path(dirname.c_str())); // set current path to dirname TEST_TRUE(File::makeDir("subdir/333")) TEST_TRUE(File::isDirectory("./subdir/333/")) // try create something which should be forbidden #if defined(OPENMS_WINDOWSPLATFORM) TEST_FALSE(File::makeDir("c:\\te:st")) // ':' is not allowed in path on Windows; Unix pretty much allows everything #endif std::filesystem::current_path(current_path); // reset current path (enable deletion of dirname) END_SECTION START_SECTION(static String getTempDirectory()) TEST_NOT_EQUAL(File::getTempDirectory(), String()) TEST_EQUAL(File::exists(File::getTempDirectory()), true) END_SECTION START_SECTION(static String getUserDirectory()) TEST_NOT_EQUAL(File::getUserDirectory(), String()) TEST_EQUAL(File::exists(File::getUserDirectory()), true) // set user directory to a path set by environmental variable and test that // it is correctly set (no changes on the file system occur) QDir d; String dirname = File::getTempDirectory() + "/" + File::getUniqueName() + "/"; TEST_EQUAL(d.mkpath(dirname.toQString()), true); #ifdef OPENMS_WINDOWSPLATFORM _putenv_s("OPENMS_HOME_PATH", dirname.c_str()); #else setenv("OPENMS_HOME_PATH", dirname.c_str(), 0); #endif TEST_EQUAL(File::getUserDirectory(), dirname) // Note: this does not guarantee any more that the user directory or an // OpenMS.ini file exists at the new location. END_SECTION START_SECTION(static Param getSystemParameters()) Param p = File::getSystemParameters(); TEST_EQUAL(!p.empty(), true) TEST_EQUAL(p.getValue("version"), VersionInfo::getVersion()) END_SECTION START_SECTION(static String findDatabase(const String &db_name)) TEST_EXCEPTION(Exception::FileNotFound, File::findDatabase("filedoesnotexists")) String db = File::findDatabase("./CV/unimod.obo"); //TEST_EQUAL(db,"wtf") TEST_EQUAL(db.hasSubstring("share/OpenMS"), true) END_SECTION START_SECTION(static bool findExecutable(OpenMS::String& exe_filename)) { //NOT_TESTABLE // since it depends on PATH // this test is somewhat brittle, but should work on most platforms (revert to NOT_TESTABLE if this does not work) #ifdef OPENMS_WINDOWSPLATFORM String find = "cmd"; TEST_EQUAL(File::findExecutable(find), true) TEST_EQUAL(find.suffix(7).toUpper(), "CMD.EXE") // should be C:\Windows\System32\cmd.exe or similar #else String find = "echo"; TEST_EQUAL(File::findExecutable(find), true) TEST_EQUAL(find.hasSuffix("echo"), true) // should be /usr/bin/echo or similar #endif } END_SECTION START_SECTION(static StringList getPathLocations(const String& path = std::getenv("PATH"))) { // set env-variables is not portable across platforms, thus we inject the PATH values #ifdef OPENMS_WINDOWSPLATFORM String test_paths=R"(C:\WINDOWS\CCM;C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps;C:\Program Files (x86)\Git\cmd)"; #else String test_paths="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"; #endif StringList l = File::getPathLocations(test_paths); #ifdef OPENMS_WINDOWSPLATFORM TEST_EQUAL(ListUtils::contains(l, "C:/Program Files (x86)/Git/cmd/"), true) #else TEST_EQUAL(ListUtils::contains(l, "/usr/bin/"), true) #endif } END_SECTION START_SECTION(static String findSiblingTOPPExecutable(const OpenMS::String& toolName)) { TEST_EXCEPTION(Exception::FileNotFound, File::findSiblingTOPPExecutable("executable_does_not_exist")) TEST_EQUAL(File::path(File::findSiblingTOPPExecutable("File_test")) + "/", File::getExecutablePath()) } END_SECTION START_SECTION(File::TempDir(bool keep_dir = false)) { File::TempDir* dir = new File::TempDir(); File::TempDir* nullPointer = nullptr; TEST_NOT_EQUAL(dir, nullPointer) TEST_EQUAL(File::exists((*dir).getPath()),1) delete dir; } END_SECTION START_SECTION(File::~TempDir()) { String path; { File::TempDir dir; path = dir.getPath(); TEST_EQUAL(File::exists(path), 1) } TEST_EQUAL(File::exists(path), 0) if (File::exists(path)) File::removeDir(path.toQString()); { File::TempDir dir2(true); path = dir2.getPath(); TEST_EQUAL(File::exists(path), 1) } TEST_EQUAL(File::exists(path), 1) if (File::exists(path)) File::removeDir(path.toQString()); } END_SECTION START_SECTION(File::download(std::string url, std::string filename)) { std::string url = R"(http://raw.githubusercontent.com/OpenMS/OpenMS/refs/heads/develop/README.md)"; std::string folder = File::getTempDirectory(); File::download(url, folder); std::string output_file_path = folder + "/README.md"; TEST_EQUAL(File::exists(output_file_path), 1); if (File::exists(output_file_path)) { File::removeDir(QString(output_file_path.c_str())); } } END_SECTION START_SECTION(static File::MatchingFileListsStatus validateMatchingFileNames(const StringList& sl1, const StringList& sl2, bool basename, bool ignore_extension)) { // Test exact match { StringList list1 = {"file1.txt", "file2.txt"}; StringList list2 = {"file1.txt", "file2.txt"}; TEST_TRUE(File::validateMatchingFileNames(list1, list2) == File::MatchingFileListsStatus::MATCH) } // Test order mismatch { StringList list1 = {"file1.txt", "file2.txt"}; StringList list2 = {"file2.txt", "file1.txt"}; TEST_TRUE(File::validateMatchingFileNames(list1, list2) == File::MatchingFileListsStatus::ORDER_MISMATCH) } // Test different sets { StringList list1 = {"file1.txt", "file2.txt"}; StringList list2 = {"file1.txt", "file3.txt"}; TEST_TRUE(File::validateMatchingFileNames(list1, list2) == File::MatchingFileListsStatus::SET_MISMATCH) } // Test different counts { StringList list1 = {"file1.txt", "file2.txt"}; StringList list2 = {"file1.txt"}; TEST_TRUE(File::validateMatchingFileNames(list1, list2) == File::MatchingFileListsStatus::SET_MISMATCH) } // Test basename comparison { StringList list1 = {"/path/to/file1.txt", "/different/path/file2.txt"}; StringList list2 = {"/other/path/file1.txt", "/somewhere/file2.txt"}; TEST_TRUE(File::validateMatchingFileNames(list1, list2, true, false) == File::MatchingFileListsStatus::MATCH) } // Test basename with order mismatch { StringList list1 = {"/path/to/file1.txt", "/different/path/file2.txt"}; StringList list2 = {"/somewhere/file2.txt", "/other/path/file1.txt"}; TEST_TRUE(File::validateMatchingFileNames(list1, list2, true, false) == File::MatchingFileListsStatus::ORDER_MISMATCH) } // Test ignore extension { StringList list1 = {"file1.txt", "file2.mzML"}; StringList list2 = {"file1.mzML", "file2.txt"}; TEST_TRUE(File::validateMatchingFileNames(list1, list2, false, true) == File::MatchingFileListsStatus::MATCH) } // Test ignore extension with different basenames { StringList list1 = {"file1.txt", "file2.mzML"}; StringList list2 = {"file1.mzML", "file3.txt"}; TEST_TRUE(File::validateMatchingFileNames(list1, list2, false, true) == File::MatchingFileListsStatus::SET_MISMATCH) } // Test with both basename and ignore extension { StringList list1 = {"/path/to/file1.txt", "/different/path/file2.mzML"}; StringList list2 = {"/other/path/file1.mzML", "/somewhere/file2.txt"}; TEST_TRUE(File::validateMatchingFileNames(list1, list2, true, true) == File::MatchingFileListsStatus::MATCH) } // Test with empty lists { StringList list1, list2; TEST_TRUE(File::validateMatchingFileNames(list1, list2) == File::MatchingFileListsStatus::MATCH) } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CalibrationData_test.cpp
.cpp
4,598
164
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/CalibrationData.h> /////////////////////////// #include <OpenMS/MATH/MathFunctions.h> using namespace OpenMS; using namespace std; START_TEST(Adduct, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CalibrationData* ptr = nullptr; CalibrationData* nullPointer = nullptr; START_SECTION(CalibrationData()) { ptr = new CalibrationData(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~CalibrationData()) { delete ptr; } END_SECTION CalibrationData cd; for (Size i = 0; i < 10; ++i) { cd.insertCalibrationPoint(100.100 + i, 200.200 + i, 128.5 + i, 200.0 + i, 1, 66); cd.insertCalibrationPoint(120.100 + i + 0.5, 400.200 + i, 128.5 + i, 200.0 + i, 1, 77); } START_SECTION(CalDataType::CoordinateType getMZ(Size i) const) TEST_REAL_SIMILAR(cd.getMZ(0), 200.200 + 0) TEST_REAL_SIMILAR(cd.getMZ(3), 400.200 + 1) END_SECTION START_SECTION(CalDataType::CoordinateType getRT(Size i) const) TEST_REAL_SIMILAR(cd.getRT(0), 100.100 + 0) TEST_REAL_SIMILAR(cd.getRT(3), 120.100 + 1 + 0.5) END_SECTION START_SECTION(CalDataType::CoordinateType getIntensity(Size i) const) TEST_REAL_SIMILAR(cd.getIntensity(0), 128.5 + 0) TEST_REAL_SIMILAR(cd.getIntensity(3), 128.5 + 1) END_SECTION START_SECTION(const_iterator begin() const) TEST_EQUAL(cd.size(), Size(cd.end() - cd.begin())) END_SECTION START_SECTION(const_iterator end() const) TEST_EQUAL(cd.size(), Size(cd.end() - cd.begin())) END_SECTION START_SECTION(Size size() const) TEST_EQUAL(cd.size(), Size(cd.end() - cd.begin())) END_SECTION START_SECTION(bool empty() const) TEST_EQUAL(cd.empty(), false) TEST_EQUAL(CalibrationData().empty(), true) END_SECTION START_SECTION(void clear()) CalibrationData cd2(cd); TEST_EQUAL(cd2.empty(), false) cd2.clear(); TEST_EQUAL(cd2.empty(), true) END_SECTION START_SECTION(void setUsePPM(bool usePPM)) cd.setUsePPM(false); TEST_EQUAL(cd.usePPM(), false) cd.setUsePPM(true); TEST_EQUAL(cd.usePPM(), true) END_SECTION START_SECTION(bool usePPM() const) NOT_TESTABLE // tested above END_SECTION START_SECTION(void insertCalibrationPoint(CalDataType::CoordinateType rt, CalDataType::CoordinateType mz_obs, CalDataType::IntensityType intensity, CalDataType::CoordinateType mz_ref, double weight, int group = -1)) NOT_TESTABLE // tested above END_SECTION START_SECTION(Size getNrOfGroups() const) TEST_EQUAL(cd.getNrOfGroups(), 2); CalibrationData cd2; TEST_EQUAL(cd2.getNrOfGroups(), 0); END_SECTION START_SECTION(CalDataType::CoordinateType getError(Size i) const) TEST_REAL_SIMILAR(cd.getError(0), Math::getPPM(200.200 + 0, 200.0)) TEST_REAL_SIMILAR(cd.getError(3), Math::getPPM(400.200 + 1, 200.0 + 1)) cd.setUsePPM(false); // use absolute error TEST_REAL_SIMILAR(cd.getError(0), (200.200 + 0 - 200.0)) TEST_REAL_SIMILAR(cd.getError(3), (400.200 + 1 - (200.0 + 1))) cd.setUsePPM(true); // reset END_SECTION START_SECTION(CalDataType::CoordinateType getRefMZ(Size i) const) TEST_REAL_SIMILAR(cd.getRefMZ(0), 200.0 + 0) TEST_REAL_SIMILAR(cd.getRefMZ(3), 200.0 + 1) END_SECTION START_SECTION(CalDataType::CoordinateType getWeight(Size i) const) TEST_REAL_SIMILAR(cd.getWeight(0), 1.0) TEST_REAL_SIMILAR(cd.getWeight(3), 1.0) END_SECTION START_SECTION(int getGroup(Size i) const) TEST_EQUAL(cd.getGroup(0), 66) TEST_EQUAL(cd.getGroup(3), 77) END_SECTION START_SECTION(static StringList getMetaValues()) TEST_EQUAL(ListUtils::concatenate(CalibrationData::getMetaValues(), ","), "mz_ref,ppm_error,weight") END_SECTION START_SECTION(CalibrationData median(double rt_left, double rt_right) const) CalibrationData m = cd.median(0, 1e6); TEST_EQUAL(m.size(), 2); // two medians (of two groups) TEST_REAL_SIMILAR(m.getMZ(0), 200.200 + 9.0/2) TEST_REAL_SIMILAR(m.getMZ(1), 400.200 + 9.0/2) END_SECTION START_SECTION(void sortByRT()) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ModificationDefinitionsSet_test.cpp
.cpp
17,935
455
// 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/ModificationDefinitionsSet.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ModificationDefinitionsSet, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ModificationDefinitionsSet* ptr = nullptr; ModificationDefinitionsSet* nullPointer = nullptr; START_SECTION(ModificationDefinitionsSet()) { ptr = new ModificationDefinitionsSet(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((ModificationDefinitionsSet(const ModificationDefinitionsSet& rhs))) { ModificationDefinitionsSet mod_set; mod_set.setMaxModifications(2); ModificationDefinition mod_def, mod_def2; mod_def.setModification("Phospho (S)"); mod_def.setFixedModification(true); mod_def2.setModification("Phospho (T)"); mod_def2.setFixedModification(false); mod_def2.setMaxOccurrences(10); ModificationDefinitionsSet mod_set2(mod_set); TEST_TRUE(mod_set == mod_set2) } END_SECTION START_SECTION((virtual ~ModificationDefinitionsSet())) { delete ptr; } END_SECTION START_SECTION((void setMaxModifications(Size max_mod))) { ModificationDefinitionsSet mod_set; mod_set.setMaxModifications(1); TEST_EQUAL(mod_set.getMaxModifications(), 1) mod_set.setMaxModifications(2); TEST_EQUAL(mod_set.getMaxModifications(), 2) } END_SECTION START_SECTION((Size getMaxModifications() const)) { // tested above NOT_TESTABLE } END_SECTION START_SECTION((Size getNumberOfModifications() const)) { ModificationDefinitionsSet mod_set(ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)"), ListUtils::create<String>("Carbamidomethyl (C)")); TEST_EQUAL(mod_set.getNumberOfModifications(), 4) ModificationDefinitionsSet mod_set2(ListUtils::create<String>(""), ListUtils::create<String>("Carbamidomethyl (C)")); TEST_EQUAL(mod_set2.getNumberOfModifications(), 1) ModificationDefinitionsSet mod_set3(ListUtils::create<String>("Phospho (S)"), ListUtils::create<String>("")); TEST_EQUAL(mod_set3.getNumberOfModifications(), 1) } END_SECTION START_SECTION((Size getNumberOfFixedModifications() const)) { ModificationDefinitionsSet mod_set(ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)"), ListUtils::create<String>("Carbamidomethyl (C)")); TEST_EQUAL(mod_set.getNumberOfFixedModifications(), 3) ModificationDefinitionsSet mod_set2(ListUtils::create<String>(""), ListUtils::create<String>("Carbamidomethyl (C)")); TEST_EQUAL(mod_set2.getNumberOfFixedModifications(), 0) ModificationDefinitionsSet mod_set3(ListUtils::create<String>("Phospho (S)"), ListUtils::create<String>("")); TEST_EQUAL(mod_set3.getNumberOfFixedModifications(), 1) } END_SECTION START_SECTION((Size getNumberOfVariableModifications() const)) { ModificationDefinitionsSet mod_set(ListUtils::create<String>("Phospho (S),Phospho (T)"), ListUtils::create<String>("Carbamidomethyl (C),Phospho (Y)")); TEST_EQUAL(mod_set.getNumberOfVariableModifications(), 2) ModificationDefinitionsSet mod_set2(ListUtils::create<String>(""), ListUtils::create<String>("Carbamidomethyl (C)")); TEST_EQUAL(mod_set2.getNumberOfVariableModifications(), 1) ModificationDefinitionsSet mod_set3(ListUtils::create<String>("Phospho (S)"), ListUtils::create<String>("")); TEST_EQUAL(mod_set3.getNumberOfVariableModifications(), 0) } END_SECTION START_SECTION((void addModification(const ModificationDefinition& mod_def))) { ModificationDefinition mod_def; mod_def.setModification("Phospho (Y)"); mod_def.setFixedModification(true); ModificationDefinitionsSet mod_set; mod_set.addModification(mod_def); ModificationDefinitionsSet mod_set2; TEST_FALSE(mod_set == mod_set2) TEST_EQUAL(mod_set.getNumberOfModifications(), 1) TEST_EQUAL(mod_set.getNumberOfFixedModifications(), 1) TEST_EQUAL(mod_set.getNumberOfVariableModifications(), 0) ModificationDefinition mod_def3; mod_def3.setModification("Phospho (T)"); mod_def3.setFixedModification(false); ModificationDefinitionsSet mod_set3; mod_set3.addModification(mod_def3); mod_set3.addModification(mod_def); TEST_EQUAL(mod_set3.getNumberOfModifications(), 2) TEST_EQUAL(mod_set3.getNumberOfFixedModifications(), 1) TEST_EQUAL(mod_set3.getNumberOfVariableModifications(), 1) } END_SECTION START_SECTION((void setModifications(const std::set<ModificationDefinition>& mod_defs))) { ModificationDefinition mod_def1, mod_def2; mod_def1.setModification("Phospho (T)"); mod_def1.setFixedModification(true); mod_def2.setModification("Phospho (S)"); mod_def2.setFixedModification(false); set<ModificationDefinition> mod_defs; mod_defs.insert(mod_def1); mod_defs.insert(mod_def2); ModificationDefinitionsSet mod_set; mod_set.setModifications(mod_defs); TEST_EQUAL(mod_set.getNumberOfModifications(), 2) TEST_EQUAL(mod_set.getNumberOfFixedModifications(), 1) TEST_EQUAL(mod_set.getNumberOfVariableModifications(), 1) } END_SECTION START_SECTION((void setModifications(const String& fixed_modifications, const String& variable_modifications))) { ModificationDefinitionsSet mod_set1(ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)"), ListUtils::create<String>("Carbamidomethyl (C)")); ModificationDefinitionsSet mod_set2; mod_set2.setModifications("Phospho (S),Phospho (T),Phospho (Y)", "Carbamidomethyl (C)"); TEST_EQUAL(mod_set1.getFixedModificationNames() == mod_set2.getFixedModificationNames(), true) TEST_EQUAL(mod_set1.getVariableModificationNames() == mod_set2.getVariableModificationNames(), true) TEST_EQUAL(mod_set1.getModificationNames() == mod_set2.getModificationNames(), true) TEST_TRUE(mod_set1 == mod_set2) mod_set1.setModifications("Phospho (S)", "Carbamidomethyl (C)"); TEST_EQUAL(mod_set1.getNumberOfModifications(), 2) TEST_EQUAL(mod_set1.getNumberOfFixedModifications(), 1) TEST_EQUAL(mod_set1.getNumberOfVariableModifications(), 1) } END_SECTION START_SECTION((std::set<ModificationDefinition> getModifications() const)) { ModificationDefinitionsSet mod_set1(ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)"), ListUtils::create<String>("Carbamidomethyl (C)")); set<String> fixed_mods, var_mods; fixed_mods.insert("Phospho (S)"); fixed_mods.insert("Phospho (T)"); fixed_mods.insert("Phospho (Y)"); var_mods.insert("Carbamidomethyl (C)"); set<ModificationDefinition> mod_defs = mod_set1.getModifications(); for (set<ModificationDefinition>::const_iterator it = mod_defs.begin(); it != mod_defs.end(); ++it) { if (it->isFixedModification()) { TEST_EQUAL(fixed_mods.find(it->getModificationName()) != fixed_mods.end(), true) } else { TEST_EQUAL(var_mods.find(it->getModificationName()) != var_mods.end(), true) } } } END_SECTION START_SECTION(const std::set<ModificationDefinition>& getFixedModifications() const) { ModificationDefinitionsSet mod_set1(ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)"), ListUtils::create<String>("Carbamidomethyl (C)")); set<String> fixed_mods; fixed_mods.insert("Phospho (S)"); fixed_mods.insert("Phospho (T)"); fixed_mods.insert("Phospho (Y)"); set<ModificationDefinition> mod_defs = mod_set1.getFixedModifications(); TEST_EQUAL(mod_defs.size(), 3) for (set<ModificationDefinition>::const_iterator it = mod_defs.begin(); it != mod_defs.end(); ++it) { TEST_EQUAL(it->isFixedModification(), true) TEST_EQUAL(fixed_mods.find(it->getModificationName()) != fixed_mods.end(), true) } } END_SECTION START_SECTION(const std::set<ModificationDefinition>& getVariableModifications() const) { ModificationDefinitionsSet mod_set1(ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)"), ListUtils::create<String>("Carbamidomethyl (C),Phospho (S)")); set<String> mods; mods.insert("Phospho (S)"); mods.insert("Carbamidomethyl (C)"); set<ModificationDefinition> mod_defs = mod_set1.getVariableModifications(); TEST_EQUAL(mod_defs.size(), 2) for (set<ModificationDefinition>::const_iterator it = mod_defs.begin(); it != mod_defs.end(); ++it) { TEST_EQUAL(it->isFixedModification(), false) TEST_EQUAL(mods.find(it->getModificationName()) != mods.end(), true) } } END_SECTION START_SECTION((std::set<String> getModificationNames() const)) { ModificationDefinitionsSet mod_set1(ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)"), ListUtils::create<String>("Carbamidomethyl (C)")); set<String> mods; mods.insert("Phospho (S)"); mods.insert("Phospho (T)"); mods.insert("Phospho (Y)"); mods.insert("Carbamidomethyl (C)"); TEST_EQUAL(mod_set1.getModificationNames() == mods, true) } END_SECTION START_SECTION((void getModificationNames(StringList& fixed_modifications, StringList& variable_modifications) const )) { StringList fixed_mods = ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)"); StringList var_mods = ListUtils::create<String>("Carbamidomethyl (C)"); ModificationDefinitionsSet mod_set(fixed_mods, var_mods); StringList fixed_mods_out, var_mods_out; mod_set.getModificationNames(fixed_mods_out, var_mods_out); TEST_STRING_EQUAL(ListUtils::concatenate<String>(fixed_mods, ","), ListUtils::concatenate<String>(fixed_mods_out, ",")); TEST_STRING_EQUAL(ListUtils::concatenate<String>(var_mods, ","), ListUtils::concatenate<String>(var_mods_out, ",")); } END_SECTION START_SECTION((std::set<String> getFixedModificationNames() const)) { ModificationDefinitionsSet mod_set1(ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)"), ListUtils::create<String>("Carbamidomethyl (C)")); set<String> mods; mods.insert("Phospho (S)"); mods.insert("Phospho (T)"); mods.insert("Phospho (Y)"); TEST_EQUAL(mod_set1.getFixedModificationNames() == mods, true) } END_SECTION START_SECTION((std::set<String> getVariableModificationNames() const)) { ModificationDefinitionsSet mod_set1(ListUtils::create<String>("Phospho (S),Phospho (T)"), ListUtils::create<String>("Phospho (Y),Carbamidomethyl (C)")); set<String> mods; mods.insert("Carbamidomethyl (C)"); mods.insert("Phospho (Y)"); TEST_EQUAL(mod_set1.getVariableModificationNames() == mods, true) } END_SECTION START_SECTION((ModificationDefinitionsSet& operator=(const ModificationDefinitionsSet& element))) { ModificationDefinitionsSet mod_set1, mod_set2; mod_set1.setModifications("Phospho (S),Phospho (T),Phospho (Y)", ""); TEST_EQUAL(mod_set1 == mod_set2, false) mod_set2 = mod_set1; TEST_TRUE(mod_set1 == mod_set2) mod_set1.setMaxModifications(3); TEST_EQUAL(mod_set1 == mod_set2, false) mod_set2 = mod_set1; TEST_TRUE(mod_set1 == mod_set2) mod_set1.setModifications("Phospho (S),Phospho (T),Phospho (Y)", "Carbamidomethyl (C)"); TEST_EQUAL(mod_set1 == mod_set2, false) mod_set2 = mod_set1; TEST_TRUE(mod_set1 == mod_set2) } END_SECTION START_SECTION((bool operator==(const ModificationDefinitionsSet& rhs) const)) { ModificationDefinitionsSet mod_set1, mod_set2; mod_set1.setModifications("Phospho (S),Phospho (T),Phospho (Y)", ""); TEST_EQUAL(mod_set1 == mod_set2, false) mod_set2 = mod_set1; TEST_TRUE(mod_set1 == mod_set2) mod_set1.setMaxModifications(3); TEST_EQUAL(mod_set1 == mod_set2, false) mod_set2 = mod_set1; TEST_TRUE(mod_set1 == mod_set2) mod_set1.setModifications("Phospho (S),Phospho (T),Phospho (Y)", "Carbamidomethyl (C)"); TEST_EQUAL(mod_set1 == mod_set2, false) mod_set2 = mod_set1; TEST_TRUE(mod_set1 == mod_set2) } END_SECTION START_SECTION((bool operator!=(const ModificationDefinitionsSet& rhs) const)) { ModificationDefinitionsSet mod_set1, mod_set2; mod_set1.setModifications("Phospho (S),Phospho (T),Phospho (Y)", ""); TEST_FALSE(mod_set1 == mod_set2) mod_set2 = mod_set1; TEST_EQUAL(mod_set1 != mod_set2, false) mod_set1.setMaxModifications(3); TEST_FALSE(mod_set1 == mod_set2) mod_set2 = mod_set1; TEST_EQUAL(mod_set1 != mod_set2, false) mod_set1.setModifications("Phospho (S),Phospho (T),Phospho (Y)", "Carbamidomethyl (C)"); TEST_FALSE(mod_set1 == mod_set2) mod_set2 = mod_set1; TEST_EQUAL(mod_set1 != mod_set2, false) } END_SECTION START_SECTION((ModificationDefinitionsSet(const StringList &fixed_modifications, const StringList &variable_modifications))) { ModificationDefinitionsSet mod_set(ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)"), ListUtils::create<String>("Carbamidomethyl (C)")); set<String> fixed_mods; fixed_mods.insert("Phospho (S)"); fixed_mods.insert("Phospho (T)"); fixed_mods.insert("Phospho (Y)"); set<String> var_mods; var_mods.insert("Carbamidomethyl (C)"); TEST_EQUAL(mod_set.getFixedModificationNames() == fixed_mods, true) TEST_EQUAL(mod_set.getVariableModificationNames() == var_mods, true) } END_SECTION START_SECTION((void setModifications(const StringList &fixed_modifications, const StringList &variable_modifications))) { ModificationDefinitionsSet mod_set; mod_set.setModifications(ListUtils::create<String>("Phospho (T)"), ListUtils::create<String>("Phospho (S)")); TEST_EQUAL(mod_set.getNumberOfModifications(), 2) TEST_EQUAL(mod_set.getNumberOfFixedModifications(), 1) TEST_EQUAL(mod_set.getNumberOfVariableModifications(), 1) } END_SECTION START_SECTION((bool isCompatible(const AASequence &peptide) const)) { ModificationDefinitionsSet mod_set(ListUtils::create<String>("Carbamidomethyl (C)"), ListUtils::create<String>("Phospho (S),Phospho (T),Phospho (Y)")); AASequence pep1 = AASequence::fromString("CCTKPESER"); AASequence pep2 = AASequence::fromString("C(Carbamidomethyl)CTKPESER"); AASequence pep3 = AASequence::fromString("C(Carbamidomethyl)C(Carbamidomethyl)TKPESER"); AASequence pep4 = AASequence::fromString("C(Carbamidomethyl)C(Carbamidomethyl)T(Phospho)TKPESER"); AASequence pep5 = AASequence::fromString("(Acetyl)CCTKPESER"); AASequence pep6 = AASequence::fromString("(Acetyl)C(Carbamidomethyl)C(Carbamidomethyl)TKPES(Phospho)ER"); AASequence pep7 = AASequence::fromString("(Acetyl)C(Carbamidomethyl)C(Carbamidomethyl)T(Phospho)KPES(Phospho)ER"); TEST_EQUAL(mod_set.isCompatible(pep1), false); TEST_EQUAL(mod_set.isCompatible(pep2), false); TEST_EQUAL(mod_set.isCompatible(pep3), true); TEST_EQUAL(mod_set.isCompatible(pep4), true); TEST_EQUAL(mod_set.isCompatible(pep5), false); TEST_EQUAL(mod_set.isCompatible(pep6), false); TEST_EQUAL(mod_set.isCompatible(pep7), false); } END_SECTION START_SECTION((void findMatches(multimap<double, ModificationDefinition>& matches, double mass, const String& residue, ResidueModification::TermSpecificity term_spec, bool consider_fixed, bool consider_variable, bool is_delta, double tolerance) const)) { ModificationDefinitionsSet mod_set; mod_set.setModifications("Gln->pyro-Glu (N-term Q)", "Glu->pyro-Glu (N-term E),Oxidation (M)"); multimap<double, ModificationDefinition> matches; // nothing to consider: TEST_EXCEPTION(Exception::IllegalArgument, mod_set.findMatches(matches, -18, "E", ResidueModification::N_TERM, false, false, true, 0.1)); // wrong term. spec.: mod_set.findMatches(matches, -18, "E", ResidueModification::ANYWHERE, true, true, true, 0.1); TEST_EQUAL(matches.empty(), true); // wrong residue: mod_set.findMatches(matches, -18, "Q", ResidueModification::N_TERM, true, true, true, 0.1); TEST_EQUAL(matches.empty(), true); // wrong fixed/variable: mod_set.findMatches(matches, -18, "E", ResidueModification::N_TERM, true, false, true, 0.1); TEST_EQUAL(matches.empty(), true); // residue, low tolerance: mod_set.findMatches(matches, -18, "E", ResidueModification::N_TERM, true, true, true, 0.1); TEST_EQUAL(matches.size(), 1); TEST_EQUAL(matches.begin()->second.getModificationName(), "Glu->pyro-Glu (N-term E)"); // no residue, low tolerance: mod_set.findMatches(matches, -18, "", ResidueModification::N_TERM, true, true, true, 0.1); TEST_EQUAL(matches.size(), 1); TEST_EQUAL(matches.begin()->second.getModificationName(), "Glu->pyro-Glu (N-term E)"); // no residue, high tolerance: mod_set.findMatches(matches, -18, "", ResidueModification::N_TERM, true, true, true, 2); TEST_EQUAL(matches.size(), 2); TEST_EQUAL(matches.begin()->second.getModificationName(), "Glu->pyro-Glu (N-term E)"); TEST_EQUAL((++matches.begin())->second.getModificationName(), "Gln->pyro-Glu (N-term Q)"); } END_SECTION START_SECTION(void inferFromPeptides(const PeptideIdentificationList& peptides)) { PeptideIdentificationList peptides(2); PeptideHit hit; hit.setSequence(AASequence::fromString("AC(Carbamidomethyl)M")); peptides[0].insertHit(hit); hit.setSequence(AASequence::fromString("(Acetyl)AEM")); peptides[0].insertHit(hit); hit.setSequence(AASequence::fromString("AC(Carbamidomethyl)M(Oxidation)")); peptides[1].insertHit(hit); ModificationDefinitionsSet mod_defs; mod_defs.inferFromPeptides(peptides); set<String> mods = mod_defs.getFixedModificationNames(); TEST_EQUAL(mods.size(), 1); set<String>::const_iterator it = mods.begin(); TEST_STRING_EQUAL(*it, "Carbamidomethyl (C)"); mods = mod_defs.getVariableModificationNames(); TEST_EQUAL(mods.size(), 2); it = mods.begin(); TEST_STRING_EQUAL(*it, "Acetyl (N-term)"); ++it; TEST_STRING_EQUAL(*it, "Oxidation (M)"); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConstRefVector_test.cpp
.cpp
36,212
1,055
// 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/KERNEL/Peak2D.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/ConstRefVector.h> /////////////////////////// #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshadow" #endif using namespace OpenMS; using namespace std; typedef std::vector< Peak1D > PeakArrayType; typedef std::vector< Peak2D > PeakArray2DType; START_TEST(ConstRefVector, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ConstRefVector<PeakArrayType>* ptr = nullptr; ConstRefVector<PeakArrayType>* nullPointer = nullptr; START_SECTION((ConstRefVector())) ptr = new ConstRefVector<PeakArrayType>(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~ConstRefVector())) delete ptr; END_SECTION START_SECTION((ConstRefVector(const ConstRefVector& p))) ConstRefVector<PeakArrayType> pl; Peak1D peak1; Peak1D peak2; peak1.setIntensity(1.0f); pl.push_back(peak1); peak2.setIntensity(2.0f); pl.push_back(peak2); ConstRefVector<PeakArrayType> pl2(pl); TEST_EQUAL(pl2.size(), 2) TEST_REAL_SIMILAR(pl2[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl2[1].getIntensity(), 2.0) END_SECTION START_SECTION((ConstRefVector& operator=(const ConstRefVector &rhs))) ConstRefVector<PeakArrayType> pl; Peak1D peak1; Peak1D peak2; peak1.setIntensity(1.0f); pl.push_back(peak1); peak2.setIntensity(2.0f); pl.push_back(peak2); ConstRefVector<PeakArrayType> pl2; pl2 = pl; TEST_EQUAL(pl2.size(), 2) TEST_REAL_SIMILAR(pl2[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl2[1].getIntensity(), 2.0) END_SECTION ConstRefVector<PeakArrayType> pl; Peak1D peak1; peak1.setPosition(2.0); peak1.setIntensity(1.0f); Peak1D peak2; peak2.setPosition(0.0); peak2.setIntensity(0.5f); Peak1D peak3; peak3.setPosition(10.5); peak3.setIntensity(0.01f); // ConstRefVectorConstIterator tests added (ek) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D>* c_ptr = nullptr; ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D>* c_nullPointer = nullptr; START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator())) c_ptr = new ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D>(); TEST_NOT_EQUAL(c_ptr, c_nullPointer) END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ~ConstRefVectorConstIterator())) delete c_ptr; END_SECTION std::vector<Peak1D*> p_vec; p_vec.push_back(&peak1); p_vec.push_back(&peak2); p_vec.push_back(&peak3); START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator(const typename std::vector< ValueType * > *vec, unsigned int position))) const std::vector<Peak1D*> p_vec_const(p_vec); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec_const, 1); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 0.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.5); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator(typename std::vector< ValueType * > *vec, unsigned int position))) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 2); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator(const ConstRefVectorConstIterator &it))) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 0); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> copy_it(tmp_c_it); TEST_REAL_SIMILAR(copy_it->getMZ(), 2.0); TEST_REAL_SIMILAR(copy_it->getIntensity(), 1.0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator& operator=(const ConstRefVectorConstIterator &rhs))) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 2); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> assign_it; assign_it = tmp_c_it; TEST_REAL_SIMILAR(assign_it->getMZ(), 10.5); TEST_REAL_SIMILAR(assign_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] bool operator<(const ConstRefVectorConstIterator &it) const)) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it1(&p_vec, 0); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it2(&p_vec, 2); TEST_EQUAL(tmp_c_it1 < tmp_c_it2, 1); TEST_EQUAL(tmp_c_it2 < tmp_c_it1, 0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] bool operator>(const ConstRefVectorConstIterator &it) const)) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it1(&p_vec, 0); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it2(&p_vec, 2); TEST_EQUAL(tmp_c_it1 > tmp_c_it2, 0); TEST_EQUAL(tmp_c_it2 > tmp_c_it1, 1); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] bool operator<=(const ConstRefVectorConstIterator &it) const)) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it1(&p_vec, 0); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it2(&p_vec, 2); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it3(&p_vec, 2); TEST_EQUAL(tmp_c_it1 <= tmp_c_it2, 1); TEST_EQUAL(tmp_c_it2 <= tmp_c_it3, 1); TEST_EQUAL(tmp_c_it2 <= tmp_c_it1, 0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] bool operator>=(const ConstRefVectorConstIterator &it) const)) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it1(&p_vec, 0); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it2(&p_vec, 2); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it3(&p_vec, 0); TEST_EQUAL(tmp_c_it1 >= tmp_c_it2, 0); TEST_EQUAL(tmp_c_it2 >= tmp_c_it1, 1); TEST_EQUAL(tmp_c_it3 >= tmp_c_it1, 1); END_SECTION std::vector<Peak1D*> p_vec2; p_vec2.push_back(&peak1); START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] bool operator==(const ConstRefVectorConstIterator &it) const)) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it1(&p_vec, 0); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it2(&p_vec, 2); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it3(&p_vec, 0); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it4(&p_vec2, 0); TEST_EQUAL(tmp_c_it1 == tmp_c_it2, 0); TEST_EQUAL(tmp_c_it2 == tmp_c_it3, 0); TEST_EQUAL(tmp_c_it3 == tmp_c_it1, 1); TEST_EQUAL(tmp_c_it4 == tmp_c_it1, 0); TEST_EQUAL(tmp_c_it4 == tmp_c_it3, 0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] bool operator!=(const ConstRefVectorConstIterator &it) const)) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it1(&p_vec, 0); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it2(&p_vec, 2); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it3(&p_vec, 0); ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it4(&p_vec2, 0); TEST_EQUAL(tmp_c_it1 != tmp_c_it2, 1); TEST_EQUAL(tmp_c_it2 != tmp_c_it3, 1); TEST_EQUAL(tmp_c_it3 != tmp_c_it1, 0); TEST_EQUAL(tmp_c_it4 != tmp_c_it1, 1); TEST_EQUAL(tmp_c_it4 != tmp_c_it3, 1); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator& operator++())) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 0); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); ++tmp_c_it; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 0.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.5); ++tmp_c_it; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator operator++(int))) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 0); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); tmp_c_it++; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 0.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.5); tmp_c_it++; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator& operator--())) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 2); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); --tmp_c_it; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 0.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.5); --tmp_c_it; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator operator--(int))) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 2); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); tmp_c_it--; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 0.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.5); tmp_c_it--; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator operator-(difference_type n) const)) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 2); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); unsigned int diff = 2; ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> result_it = tmp_c_it - diff; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); TEST_REAL_SIMILAR(result_it->getMZ(), 2.0); TEST_REAL_SIMILAR(result_it->getIntensity(), 1.0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator operator+(difference_type n) const)) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 0); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); unsigned int diff = 2; ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> result_it = tmp_c_it + diff; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); TEST_REAL_SIMILAR(result_it->getMZ(), 10.5); TEST_REAL_SIMILAR(result_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator& operator-=(difference_type n))) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 2); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); unsigned int diff = 2; tmp_c_it -= diff; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] ConstRefVectorConstIterator& operator+=(difference_type n))) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 0); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); unsigned int diff = 2; tmp_c_it += diff; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] reference operator*())) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 1); Peak1D orig_peak((*tmp_c_it)); TEST_REAL_SIMILAR(orig_peak.getMZ(), tmp_c_it->getMZ()); TEST_REAL_SIMILAR(orig_peak.getIntensity(), tmp_c_it->getIntensity()); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] pointer operator->())) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 2); double mz = tmp_c_it->getMZ(); double Int = tmp_c_it->getIntensity(); TEST_REAL_SIMILAR(mz, 10.5); TEST_REAL_SIMILAR(Int, 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorConstIterator] pointer operator->() const)) ConstRefVector<PeakArrayType>::ConstRefVectorConstIterator<Peak1D> tmp_c_it(&p_vec, 2); double mz = tmp_c_it->getMZ(); double Int = tmp_c_it->getIntensity(); TEST_REAL_SIMILAR(mz, 10.5); TEST_REAL_SIMILAR(Int, 0.01); END_SECTION /////////////////////////////////////////// // ConstRefVectorIterator tests added (ek) /////////////////////////////////////////// ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D>* m_ptr = nullptr; ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D>* m_nullPointer = nullptr; START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator())) m_ptr = new ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D>(); TEST_NOT_EQUAL(m_ptr, m_nullPointer) END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ~ConstRefVectorIterator())) delete m_ptr; END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator(typename std::vector< ValueType * > *vec, unsigned int position))) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 2); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator(const ConstRefVectorIterator< ValueType > &it))) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 0); ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> copy_it(tmp_c_it); TEST_REAL_SIMILAR(copy_it->getMZ(), 2.0); TEST_REAL_SIMILAR(copy_it->getIntensity(), 1.0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator& operator++())) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 0); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); ++tmp_c_it; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 0.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.5); ++tmp_c_it; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator operator++(int))) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 0); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); tmp_c_it++; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 0.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.5); tmp_c_it++; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator& operator--())) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 2); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); --tmp_c_it; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 0.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.5); --tmp_c_it; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator operator--(int))) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 2); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); tmp_c_it--; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 0.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.5); tmp_c_it--; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator operator-(typename ConstRefVectorIterator::difference_type n) const )) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 2); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); unsigned int diff = 2; ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> result_it = tmp_c_it - diff; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); TEST_REAL_SIMILAR(result_it->getMZ(), 2.0); TEST_REAL_SIMILAR(result_it->getIntensity(), 1.0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator operator+(typename ConstRefVectorIterator::difference_type n) const )) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 0); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); unsigned int diff = 2; ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> result_it = tmp_c_it + diff; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); TEST_REAL_SIMILAR(result_it->getMZ(), 10.5); TEST_REAL_SIMILAR(result_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator& operator-=(typename ConstRefVectorIterator::difference_type n))) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 2); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); unsigned int diff = 2; tmp_c_it -= diff; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] ConstRefVectorIterator& operator+=(typename ConstRefVectorIterator::difference_type n))) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 0); TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 2.0); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 1.0); unsigned int diff = 2; tmp_c_it += diff; TEST_REAL_SIMILAR(tmp_c_it->getMZ(), 10.5); TEST_REAL_SIMILAR(tmp_c_it->getIntensity(), 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] reference operator*())) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 1); Peak1D orig_peak((*tmp_c_it)); TEST_REAL_SIMILAR(orig_peak.getMZ(), tmp_c_it->getMZ()); TEST_REAL_SIMILAR(orig_peak.getIntensity(), tmp_c_it->getIntensity()); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] pointer operator->())) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 2); double mz = tmp_c_it->getMZ(); double Int = tmp_c_it->getIntensity(); TEST_REAL_SIMILAR(mz, 10.5); TEST_REAL_SIMILAR(Int, 0.01); END_SECTION START_SECTION(([ConstRefVector::ConstRefVectorIterator] pointer operator->() const)) ConstRefVector<PeakArrayType>::ConstRefVectorIterator<Peak1D> tmp_c_it(&p_vec, 2); double mz = tmp_c_it->getMZ(); double Int = tmp_c_it->getIntensity(); TEST_REAL_SIMILAR(mz, 10.5); TEST_REAL_SIMILAR(Int, 0.01); END_SECTION //////////////////////////////// START_SECTION((size_type size() const)) TEST_EQUAL(pl.size(), 0) pl.push_back(peak1); TEST_EQUAL(pl.size(), 1) END_SECTION START_SECTION((void push_back(const ValueType &x))) pl.push_back(peak2); TEST_EQUAL(pl.size(), 2) END_SECTION START_SECTION((size_type max_size() const)) ConstRefVector<PeakArrayType>::size_type max = pl.max_size(); pl.push_back(peak3); TEST_EQUAL(pl.max_size() == max, true) END_SECTION START_SECTION((bool empty() const)) TEST_EQUAL(pl.empty(), false) END_SECTION START_SECTION([EXTRA] ConstIterator begin() const) const ConstRefVector<PeakArrayType>& c_pl(pl); TEST_EQUAL(c_pl.size(), 3) ABORT_IF(c_pl.size() != 3) TEST_REAL_SIMILAR(c_pl.begin()->getIntensity(), peak1.getIntensity()) TEST_REAL_SIMILAR(c_pl.begin()->getPosition()[0], peak1.getPosition()[0]) END_SECTION START_SECTION([EXTRA] ConstIterator end() const) const ConstRefVector<PeakArrayType>& c_pl(pl); TEST_EQUAL(c_pl.size(), 3) ABORT_IF(c_pl.size() != 3) bool result = (c_pl.begin() == c_pl.end()); TEST_EQUAL(result, false) const ConstRefVector<PeakArrayType> empty; result = (empty.begin() == empty.end()); TEST_EQUAL(result, true) std::vector<Peak1D> v(c_pl.size()); std::copy(c_pl.begin(), c_pl.end(), v.begin()); TEST_EQUAL(v.size(), 3) ABORT_IF(v.size() != 3) TEST_REAL_SIMILAR(v[0].getIntensity(), peak1.getIntensity()) TEST_REAL_SIMILAR(v[0].getPosition()[0], peak1.getPosition()[0]) TEST_REAL_SIMILAR(v[1].getIntensity(), peak2.getIntensity()) TEST_REAL_SIMILAR(v[1].getPosition()[0], peak2.getPosition()[0]) TEST_REAL_SIMILAR(v[2].getIntensity(), peak3.getIntensity()) TEST_REAL_SIMILAR(v[2].getPosition()[0], peak3.getPosition()[0]) END_SECTION START_SECTION((void sortByIntensity(bool reverse=false))) ConstRefVector<PeakArrayType> pl2(pl); pl2.sortByIntensity(); TEST_EQUAL(pl2.size(), 3) std::vector<Peak1D> v(pl2.size()); std::copy(pl2.begin(), pl2.end(), v.begin()); TEST_EQUAL(v.size(), 3) ABORT_IF(v.size() != 3) TEST_REAL_SIMILAR(v[2].getIntensity(), peak1.getIntensity()) TEST_REAL_SIMILAR(v[2].getPosition()[0], peak1.getPosition()[0]) TEST_REAL_SIMILAR(v[1].getIntensity(), peak2.getIntensity()) TEST_REAL_SIMILAR(v[1].getPosition()[0], peak2.getPosition()[0]) TEST_REAL_SIMILAR(v[0].getIntensity(), peak3.getIntensity()) TEST_REAL_SIMILAR(v[0].getPosition()[0], peak3.getPosition()[0]) END_SECTION ConstRefVector<PeakArray2DType> pl2; Peak2D peak4; peak4.getPosition()[0] = 2.0; peak4.getPosition()[1] = 3.0; peak4.setIntensity(1.0f); pl2.push_back(peak4); Peak2D peak5; peak5.getPosition()[0] = 0.0; peak5.getPosition()[1] = 2.5; peak5.setIntensity(0.5f); pl2.push_back(peak5); Peak2D peak6; peak6.getPosition()[0] = 10.5; peak6.getPosition()[1] = 0.0; peak6.setIntensity(0.01f); pl2.push_back(peak6); START_SECTION((Iterator begin())) ConstRefVector<PeakArrayType>::Iterator it = pl.begin(); TEST_REAL_SIMILAR(it->getIntensity(), 1.0) TEST_REAL_SIMILAR(it->getPosition()[0], 2.0) END_SECTION START_SECTION((Iterator end())) ConstRefVector<PeakArrayType>::Iterator it = pl.end()-1; TEST_REAL_SIMILAR(it->getIntensity(), 0.01) TEST_REAL_SIMILAR(it->getPosition()[0], 10.5) END_SECTION START_SECTION((ConstIterator begin() const)) ConstRefVector<PeakArrayType>::ConstIterator it = pl.begin(); TEST_REAL_SIMILAR(it->getIntensity(), 1.0) TEST_REAL_SIMILAR(it->getPosition()[0], 2.0) END_SECTION START_SECTION((ConstIterator end() const)) ConstRefVector<PeakArrayType>::ConstIterator it = pl.end(); --it; TEST_REAL_SIMILAR(it->getIntensity(), 0.01) TEST_REAL_SIMILAR(it->getPosition()[0], 10.5) END_SECTION START_SECTION((ReverseIterator rbegin())) ConstRefVector<PeakArrayType>::ReverseIterator it = pl.rbegin(); TEST_REAL_SIMILAR(it->getIntensity(), 0.01) TEST_REAL_SIMILAR(it->getPosition()[0], 10.5) END_SECTION START_SECTION((ReverseIterator rend())) ConstRefVector<PeakArrayType>::ReverseIterator it = pl.rend()-1; TEST_REAL_SIMILAR(it->getIntensity(), 1.0) TEST_REAL_SIMILAR(it->getPosition()[0], 2.0) END_SECTION START_SECTION((ConstReverseIterator rbegin() const)) ConstRefVector<PeakArrayType>::ConstReverseIterator it = pl.rbegin(); TEST_REAL_SIMILAR(it->getIntensity(), 0.01) TEST_REAL_SIMILAR(it->getPosition()[0], 10.5) END_SECTION START_SECTION((ConstReverseIterator rend() const)) ConstRefVector<PeakArrayType>::ConstReverseIterator it = pl.rend()-1; TEST_REAL_SIMILAR(it->getIntensity(), 1.0) TEST_REAL_SIMILAR(it->getPosition()[0], 2.0) END_SECTION START_SECTION((size_type capacity() const)) TEST_EQUAL(pl.capacity(), 3) TEST_EQUAL(pl.size(), 3) END_SECTION Peak1D peak7; peak7.getPosition()[0] = 1.1; peak7.setIntensity(1.1f); START_SECTION((void reserve(size_type n))) pl.reserve(4); TEST_EQUAL(pl.size(), 3) TEST_EQUAL(pl.capacity(), 4) pl.push_back(peak7); TEST_EQUAL(pl.size(), 4) TEST_EQUAL(pl.capacity(), 4) END_SECTION START_SECTION((const_reference operator [](size_type n) const)) TEST_REAL_SIMILAR(pl[2].getIntensity(), 0.01) TEST_REAL_SIMILAR(pl[2].getPosition()[0], 10.5) TEST_REAL_SIMILAR(pl[3].getIntensity(), 1.1) TEST_REAL_SIMILAR(pl[3].getPosition()[0], 1.1) END_SECTION START_SECTION((ConstRefVector(size_type n))) ConstRefVector<PeakArrayType> pl2(2); TEST_EQUAL(pl2.size(), 2) END_SECTION START_SECTION((ConstRefVector(size_type n, const ValueType &element))) Peak2D peak; peak.getPosition()[0] = 1.1; peak.setIntensity(5.1f); ConstRefVector<PeakArray2DType> pl2(3, peak); TEST_EQUAL(pl2.size(), 3) TEST_REAL_SIMILAR(pl2[0].getIntensity(), 5.1) TEST_REAL_SIMILAR(pl2[1].getIntensity(), 5.1) TEST_REAL_SIMILAR(pl2[2].getIntensity(), 5.1) END_SECTION START_SECTION((const_reference front() const)) Peak1D peak; peak = pl.front(); TEST_REAL_SIMILAR(peak.getIntensity(), 1.0) TEST_REAL_SIMILAR(peak.getPosition()[0], 2) END_SECTION START_SECTION((const_reference back() const)) Peak1D peak; peak = pl.back(); TEST_REAL_SIMILAR(peak.getIntensity(), 1.1) TEST_REAL_SIMILAR(peak.getPosition()[0], 1.1) END_SECTION START_SECTION((void pop_back())) TEST_EQUAL(pl.size(), 4) pl.pop_back(); TEST_EQUAL(pl.size(), 3) TEST_REAL_SIMILAR(pl[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl[1].getIntensity(), 0.5) TEST_REAL_SIMILAR(pl[2].getIntensity(), 0.01) END_SECTION Peak1D peak8; peak8.getPosition()[0] = 2.0; peak8.setIntensity(1.0f); Peak1D peak9; peak9.getPosition()[0] = 0.0; peak9.setIntensity(2.5f); START_SECTION((void swap(ConstRefVector &array))) ConstRefVector<PeakArrayType> pl2; pl2.push_back(peak8); pl2.push_back(peak9); TEST_REAL_SIMILAR(pl2[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl2[1].getIntensity(), 2.5) TEST_EQUAL(pl2.size(), 2) TEST_EQUAL(pl.size(), 3) pl.swap(pl2); TEST_EQUAL(pl2.size(), 3) TEST_EQUAL(pl.size(), 2) TEST_REAL_SIMILAR(pl2[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl2[1].getIntensity(), 0.5) TEST_REAL_SIMILAR(pl2[2].getIntensity(), 0.01) TEST_REAL_SIMILAR(pl[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl[1].getIntensity(), 2.5) swap(pl,pl2); TEST_EQUAL(pl.size(), 3) TEST_EQUAL(pl2.size(), 2) TEST_REAL_SIMILAR(pl[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl[1].getIntensity(), 0.5) TEST_REAL_SIMILAR(pl[2].getIntensity(), 0.01) TEST_REAL_SIMILAR(pl2[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl2[1].getIntensity(), 2.5) END_SECTION Peak1D peak10; peak10.setIntensity(4712.0); START_SECTION((Iterator insert(Iterator pos, const ValueType &element))) TEST_EQUAL(pl.size(), 3) pl.insert(pl.end(),peak10); TEST_EQUAL(pl.size(), 4) TEST_REAL_SIMILAR(pl[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl[1].getIntensity(), 0.5) TEST_REAL_SIMILAR(pl[2].getIntensity(), 0.01) TEST_REAL_SIMILAR(pl[3].getIntensity(), 4712.0) END_SECTION START_SECTION((Iterator erase(Iterator pos))) TEST_EQUAL(pl.size(), 4) pl.erase(pl.end()-1); TEST_EQUAL(pl.size(), 3) TEST_REAL_SIMILAR(pl[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl[1].getIntensity(), 0.5) TEST_REAL_SIMILAR(pl[2].getIntensity(), 0.01) END_SECTION START_SECTION((void insert(Iterator pos, size_type n, const ValueType &element))) peak10.setIntensity(4714.0); TEST_EQUAL(pl.size(), 3) pl.insert(pl.begin(),3,peak10); TEST_EQUAL(pl.size(), 6) TEST_REAL_SIMILAR(pl[0].getIntensity(), 4714.0) TEST_REAL_SIMILAR(pl[1].getIntensity(), 4714.0) TEST_REAL_SIMILAR(pl[2].getIntensity(), 4714.0) TEST_REAL_SIMILAR(pl[3].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl[4].getIntensity(), 0.5) TEST_REAL_SIMILAR(pl[5].getIntensity(), 0.01) END_SECTION START_SECTION((template <class InputIterator> void insert(Iterator pos, InputIterator f, InputIterator l))) pl.erase(pl.begin(),pl.begin()+3); TEST_EQUAL(pl.size(), 3) pl.insert(pl.begin(),pl.begin()+1,pl.end()); TEST_EQUAL(pl.size(), 5) TEST_REAL_SIMILAR(pl[0].getIntensity(), 0.5) TEST_REAL_SIMILAR(pl[1].getIntensity(), 0.01) TEST_REAL_SIMILAR(pl[2].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl[3].getIntensity(), 0.5) TEST_REAL_SIMILAR(pl[4].getIntensity(), 0.01) END_SECTION START_SECTION((template <class InputIterator> ConstRefVector(InputIterator f, InputIterator l))) ConstRefVector<PeakArrayType> pl2(pl.begin()+1,pl.end()-1); TEST_EQUAL(pl2.size(), 3) TEST_REAL_SIMILAR(pl2[0].getIntensity(), 0.01) TEST_REAL_SIMILAR(pl2[1].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl2[2].getIntensity(), 0.5) END_SECTION START_SECTION((bool operator==(const ConstRefVector &array) const)) ConstRefVector<PeakArrayType> pl2(pl); TEST_EQUAL(pl.size(), pl2.size()) TEST_EQUAL(pl == pl2 , true) END_SECTION START_SECTION((bool operator!=(const ConstRefVector &array) const)) ConstRefVector<PeakArrayType> pl2(pl); TEST_EQUAL(pl.size(), pl2.size()) TEST_EQUAL(pl != pl2 , false) END_SECTION START_SECTION((bool operator<(const ConstRefVector &array) const)) ConstRefVector<PeakArrayType> pl2(pl); TEST_EQUAL(pl < pl2, false) pl2.push_back(Peak1D()); TEST_EQUAL(pl < pl2 , true) END_SECTION START_SECTION((bool operator>(const ConstRefVector &array) const)) ConstRefVector<PeakArrayType> pl2(pl); TEST_EQUAL(pl > pl2, false) pl2.erase(pl2.end()-1); TEST_EQUAL(pl > pl2 , true) END_SECTION START_SECTION((bool operator<=(const ConstRefVector &array) const)) ConstRefVector<PeakArrayType> pl2(pl); TEST_EQUAL(pl <= pl2, true) pl2.push_back(Peak1D()); TEST_EQUAL(pl <= pl2 , true) pl2.erase(pl2.begin()+1,pl2.end()-2); TEST_EQUAL(pl <= pl2 , false) END_SECTION START_SECTION((bool operator>=(const ConstRefVector &array) const)) ConstRefVector<PeakArrayType> pl2(pl); TEST_EQUAL(pl >= pl2, true) pl2.erase(pl2.end()-1); TEST_EQUAL(pl >= pl2 , true) pl2.insert(pl2.end(),2,pl2.front()); TEST_EQUAL(pl >= pl2 , false) END_SECTION START_SECTION((void clear())) pl.clear(); TEST_EQUAL(pl.size(), 0) END_SECTION Peak1D peak11; peak11.setIntensity(4713.0); START_SECTION((void resize(size_type new_size))) pl.resize(4,peak11); TEST_EQUAL(pl.size(), 4) TEST_REAL_SIMILAR(pl[2].getIntensity(), 4713.0) TEST_REAL_SIMILAR(pl[3].getIntensity(), 4713.0) END_SECTION START_SECTION((void resize(size_type new_size, const ValueType &t))) ConstRefVector<PeakArrayType> pl; Peak1D peak; peak.getPosition()[0] = 0.0; peak.setIntensity(2.5f); pl.resize(2,peak); TEST_EQUAL(pl.size(), 2) TEST_EQUAL(pl[0].getIntensity() == peak.getIntensity(),true) TEST_EQUAL(pl[0].getPosition() == peak.getPosition(),true) TEST_EQUAL(pl[1].getIntensity() == peak.getIntensity(),true) TEST_EQUAL(pl[1].getPosition() == peak.getPosition(),true) END_SECTION START_SECTION((ConstRefVector(ContainerType &p))) PeakArrayType pa(5); ConstRefVector<PeakArrayType> pl(pa); for (Size i=0; i<pa.size(); ++i) { TEST_EQUAL(pa[i]== pl[i],true) } END_SECTION START_SECTION((template <class InputIterator> void assign(InputIterator f , InputIterator l))) ConstRefVector<PeakArrayType> dpa2; dpa2.push_back(peak1); dpa2.push_back(peak2); dpa2.push_back(peak3); TEST_EQUAL(pl.size(), 4) pl.assign(dpa2.begin(),dpa2.end()); TEST_EQUAL(pl.size(), 3) TEST_REAL_SIMILAR(pl[0].getIntensity(), 1.0) TEST_REAL_SIMILAR(pl[1].getIntensity(), 0.5) TEST_REAL_SIMILAR(pl[2].getIntensity(), 0.01) END_SECTION START_SECTION((void assign(size_type n, const ValueType &x))) pl.assign(5,peak3); TEST_EQUAL(pl.size(), 5) TEST_REAL_SIMILAR(pl[0].getIntensity(), 0.01) TEST_REAL_SIMILAR(pl[1].getIntensity(), 0.01) TEST_REAL_SIMILAR(pl[2].getIntensity(), 0.01) TEST_REAL_SIMILAR(pl[3].getIntensity(), 0.01) TEST_REAL_SIMILAR(pl[4].getIntensity(), 0.01) END_SECTION START_SECTION((Iterator erase(Iterator first,Iterator last))) TEST_EQUAL(pl.size(), 5) pl.erase(pl.begin(),pl.end()); TEST_EQUAL(pl.size(), 0) END_SECTION START_SECTION((void sortByPosition())) ConstRefVector<PeakArray2DType> dpa2; Peak2D p1(peak4); p1.setIntensity(1.0f); Peak2D p2(peak5); p2.setIntensity(2.0f); Peak2D p3(peak6); p3.setIntensity(3.0f); Peak2D p4; p4.getPosition()[0]=4.3; p4.getPosition()[1]=4711; p4.setIntensity(4.0f); Peak2D p5; p5.getPosition()[1]=4711; p5.setIntensity(5.0f); Peak2D p6; p6.getPosition()[1]=4711; p6.setIntensity(6.0f); dpa2.push_back(p1); dpa2.push_back(p2); dpa2.push_back(p3); dpa2.push_back(p4); dpa2.push_back(p5); dpa2.push_back(p6); dpa2.sortByPosition(); TEST_REAL_SIMILAR(dpa2[0].getIntensity(), 2.0) TEST_REAL_SIMILAR(dpa2[1].getIntensity(), 5.0) TEST_REAL_SIMILAR(dpa2[2].getIntensity(), 6.0) TEST_REAL_SIMILAR(dpa2[3].getIntensity(), 1.0) TEST_REAL_SIMILAR(dpa2[4].getIntensity(), 4.0) TEST_REAL_SIMILAR(dpa2[5].getIntensity(), 3.0) END_SECTION START_SECTION((template <typename ComparatorType> void sortByComparator(ComparatorType const &comparator=ComparatorType()))) pl2.sortByComparator<Peak2D::PositionLess>(); TEST_EQUAL(pl2.size(), 3) TEST_REAL_SIMILAR(pl2[1].getIntensity(), peak4.getIntensity()) TEST_REAL_SIMILAR(pl2[1].getPosition()[0], peak4.getPosition()[0]) TEST_REAL_SIMILAR(pl2[1].getPosition()[1], peak4.getPosition()[1]) TEST_REAL_SIMILAR(pl2[0].getIntensity(), peak5.getIntensity()) TEST_REAL_SIMILAR(pl2[0].getPosition()[0], peak5.getPosition()[0]) TEST_REAL_SIMILAR(pl2[0].getPosition()[1], peak5.getPosition()[1]) TEST_REAL_SIMILAR(pl2[2].getIntensity(), peak6.getIntensity()) TEST_REAL_SIMILAR(pl2[2].getPosition()[0], peak6.getPosition()[0]) TEST_REAL_SIMILAR(pl2[2].getPosition()[1], peak6.getPosition()[1]) // ---------------- ConstRefVector<PeakArray2DType> dpa2; Peak2D p1(peak4); p1.setIntensity(1.0f); Peak2D p2(peak5); p2.setIntensity(2.0f); Peak2D p3(peak6); p3.setIntensity(3.0f); Peak2D p4; p4.getPosition()[0]=4.3; p4.getPosition()[1]=4711; p4.setIntensity(4.0f); Peak2D p5; p5.getPosition()[1]=4711; p5.setIntensity(5.0f); Peak2D p6; p6.getPosition()[1]=4711; p6.setIntensity(6.0f); dpa2.push_back(p1); dpa2.push_back(p2); dpa2.push_back(p3); dpa2.push_back(p4); dpa2.push_back(p5); dpa2.push_back(p6); dpa2.sortByComparator<Peak2D::MZLess >(Peak2D::MZLess()); TEST_REAL_SIMILAR(dpa2[0].getIntensity(), 3.0) TEST_REAL_SIMILAR(dpa2[1].getIntensity(), 2.0) TEST_REAL_SIMILAR(dpa2[2].getIntensity(), 1.0) TEST_REAL_SIMILAR(dpa2[3].getIntensity(), 4.0) TEST_REAL_SIMILAR(dpa2[4].getIntensity(), 5.0) TEST_REAL_SIMILAR(dpa2[5].getIntensity(), 6.0) END_SECTION START_SECTION([EXTRA] Container without special members for sorting) vector<Int> vec(5); ConstRefVector<vector<Int> > ref_vec(vec); TEST_EQUAL(ref_vec.size(),5) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST #ifdef __clang__ #pragma clang diagnostic pop #endif
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MzIdentMLFile_test.cpp
.cpp
29,246
505
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Authors: Mathias Walzer $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/MzIdentMLFile.h> #include <OpenMS/CONCEPT/FuzzyStringComparator.h> #include <OpenMS/CHEMISTRY/CrossLinksDB.h> #include <OpenMS/CONCEPT/Constants.h> using namespace OpenMS; using namespace std; START_TEST(MzIdentMLFile, "$Id") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MzIdentMLFile* ptr = nullptr; MzIdentMLFile* nullPointer = nullptr; START_SECTION((MzIdentMLFile())) { ptr = new MzIdentMLFile; TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((~MzIdentMLFile())) { delete ptr; } END_SECTION START_SECTION(void load(const String& filename, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids) ) { std::vector<ProteinIdentification> protein_ids; PeptideIdentificationList peptide_ids; std::vector<String> fm{"Carbamidomethyl (C)", "Xlink:DTSSP[88] (Protein N-term)"}; MzIdentMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzIdentMLFile_msgf_mini.mzid"), protein_ids, peptide_ids); TEST_EQUAL(protein_ids.size(),2) TEST_EQUAL(protein_ids[0].getHits().size(),2) TEST_EQUAL(protein_ids[1].getHits().size(),1) TEST_EQUAL(peptide_ids.size(),5) TEST_EQUAL(peptide_ids[0].getHits().size(),1) TEST_EQUAL(peptide_ids[1].getHits().size(),1) TEST_EQUAL(peptide_ids[2].getHits().size(),1) TEST_EQUAL(peptide_ids[3].getHits().size(),1) TEST_EQUAL(peptide_ids[4].getHits().size(),1) /////////////// protein id 1 ////////////////// TEST_EQUAL(protein_ids[0].getSearchEngine(),"MS-GF+") TEST_EQUAL(protein_ids[0].getSearchEngineVersion(),"Beta (v9979)") TEST_NOT_EQUAL(protein_ids[0].getDateTime().getDate(),"0000-00-00") TEST_NOT_EQUAL(protein_ids[0].getDateTime().getTime(),"00:00:00") TEST_EQUAL(protein_ids[0].getSearchParameters().db,"database.fasta") TEST_EQUAL(protein_ids[0].getSearchParameters().missed_cleavages, 1000) ABORT_IF(protein_ids[0].getSearchParameters().fixed_modifications.size() != fm.size()) for (size_t i = 0; i < fm.size(); ++i) { TEST_EQUAL(protein_ids[0].getSearchParameters().fixed_modifications[i], fm[i]); } TEST_REAL_SIMILAR(protein_ids[0].getSearchParameters().fragment_mass_tolerance,0) TEST_REAL_SIMILAR(protein_ids[0].getSearchParameters().precursor_mass_tolerance,20) //ProteinGroups not nupported yet, also no ProteinDetection, too few input here // TEST_EQUAL(protein_ids[0].getProteinGroups().size(), 0); // TEST_EQUAL(protein_ids[0].getIndistinguishableProteins().size(), 0); //protein hit 1 TEST_EQUAL(protein_ids[0].getHits()[0].getAccession(),"sp|P0A9K9|SLYD_ECOLI") TEST_EQUAL(protein_ids[0].getHits()[0].getSequence(),"") //protein hit 2 TEST_EQUAL(protein_ids[0].getHits()[1].getAccession(),"sp|P0A786|PYRB_ECOLI") TEST_EQUAL(protein_ids[0].getHits()[1].getSequence(),"") //peptide id s TEST_EQUAL(peptide_ids[0].getScoreType(),"MS-GF:RawScore") TEST_REAL_SIMILAR(peptide_ids[0].getHits()[0].getScore(),195) TEST_EQUAL(peptide_ids[0].getHits()[0].getSequence().toString(),"LATEFSGNVPVLNAGDGSNQHPTQTLLDLFTIQETQGR") TEST_EQUAL(peptide_ids[0].getSpectrumReference(),"controllerType=0 controllerNumber=1 scan=32805") TEST_EQUAL(peptide_ids[1].getScoreType(),"MS-GF:RawScore") TEST_REAL_SIMILAR(peptide_ids[1].getHits()[0].getScore(),182) TEST_EQUAL(peptide_ids[1].getHits()[0].getSequence().toString(),"FLAETDQGPVPVEITAVEDDHVVVDGNHMLAGQNLK") TEST_EQUAL(peptide_ids[1].getSpectrumReference(),"controllerType=0 controllerNumber=1 scan=26090") TEST_EQUAL(peptide_ids[2].getScoreType(),"MS-GF:RawScore") TEST_REAL_SIMILAR(peptide_ids[2].getHits()[0].getScore(),191) TEST_EQUAL(peptide_ids[2].getHits()[0].getSequence().toString(),"FLAETDQGPVPVEITAVEDDHVVVDGNHMLAGQNLK") TEST_EQUAL(peptide_ids[2].getSpectrumReference(),"controllerType=0 controllerNumber=1 scan=26157") TEST_EQUAL(peptide_ids[3].getScoreType(),"MS-GF:RawScore") TEST_REAL_SIMILAR(peptide_ids[3].getHits()[0].getScore(),211) TEST_EQUAL(peptide_ids[3].getHits()[0].getSequence().toString(),"VGAGPFPTELFDETGEFLC(Carbamidomethyl)K") TEST_EQUAL(peptide_ids[3].getSpectrumReference(),"controllerType=0 controllerNumber=1 scan=15094") } END_SECTION START_SECTION(void store(String filename, const std::vector<ProteinIdentification>& protein_ids, const PeptideIdentificationList& peptide_ids) ) { //store and load data from various sources, starting with idxml, contents already checked above, so checking integrity of the data over repeated r/w std::vector<ProteinIdentification> protein_ids, protein_ids2; PeptideIdentificationList peptide_ids, peptide_ids2; String input_path = OPENMS_GET_TEST_DATA_PATH("MzIdentMLFile_whole.mzid"); MzIdentMLFile().load(input_path, protein_ids2, peptide_ids2); String filename; NEW_TMP_FILE(filename) MzIdentMLFile().store(filename, protein_ids2, peptide_ids2); MzIdentMLFile().load(filename, protein_ids, peptide_ids); TEST_EQUAL(protein_ids.size(),protein_ids2.size()) TEST_EQUAL(protein_ids[0].getHits().size(),protein_ids2[0].getHits().size()) TEST_EQUAL(peptide_ids.size(),peptide_ids2.size()) TEST_EQUAL(peptide_ids[0].getHits().size(),peptide_ids2[0].getHits().size()) TEST_EQUAL(peptide_ids[1].getHits().size(),peptide_ids2[1].getHits().size()) TEST_EQUAL(peptide_ids[2].getHits().size(),peptide_ids2[2].getHits().size()) /////////////// protein id 1 ////////////////// TEST_EQUAL(protein_ids[0].getSearchEngine(),protein_ids2[0].getSearchEngine()) TEST_EQUAL(protein_ids[0].getSearchEngineVersion(),protein_ids2[0].getSearchEngineVersion()) TEST_EQUAL(protein_ids[0].getDateTime().getDate(),protein_ids2[0].getDateTime().getDate()) TEST_EQUAL(protein_ids[0].getDateTime().getTime(),protein_ids2[0].getDateTime().getTime()) TEST_EQUAL(protein_ids[0].getSearchParameters().db,protein_ids2[0].getSearchParameters().db) TEST_EQUAL(protein_ids[0].getSearchParameters().db_version,protein_ids2[0].getSearchParameters().db_version) TEST_EQUAL(protein_ids[0].getSearchParameters().digestion_enzyme.getName(),protein_ids2[0].getSearchParameters().digestion_enzyme.getName()) TEST_EQUAL(protein_ids[0].getSearchParameters().charges,protein_ids2[0].getSearchParameters().charges) TEST_EQUAL(protein_ids[0].getSearchParameters().mass_type,protein_ids2[0].getSearchParameters().mass_type) TEST_REAL_SIMILAR(protein_ids[0].getSearchParameters().fragment_mass_tolerance,protein_ids2[0].getSearchParameters().fragment_mass_tolerance) TEST_REAL_SIMILAR(protein_ids[0].getSearchParameters().precursor_mass_tolerance,protein_ids2[0].getSearchParameters().precursor_mass_tolerance) TEST_EQUAL(protein_ids[0].getSearchParameters().variable_modifications.size(),protein_ids2[0].getSearchParameters().variable_modifications.size()) for (size_t i = 0; i < protein_ids[0].getSearchParameters().variable_modifications.size(); ++i) { TEST_STRING_EQUAL(protein_ids[0].getSearchParameters().variable_modifications[i],protein_ids2[0].getSearchParameters().variable_modifications[i]) } TEST_STRING_EQUAL(protein_ids[0].getSearchParameters().variable_modifications.back(),"Acetyl (N-term)") TEST_EQUAL(protein_ids[0].getSearchParameters().fixed_modifications.size(),protein_ids2[0].getSearchParameters().fixed_modifications.size()) for (size_t i = 0; i < protein_ids[0].getSearchParameters().fixed_modifications.size(); ++i) { TEST_STRING_EQUAL(protein_ids[0].getSearchParameters().fixed_modifications[i],protein_ids2[0].getSearchParameters().fixed_modifications[i]) } //ProteinGroups not nupported yet, also no ProteinDetection, too few input here // TEST_EQUAL(protein_ids[0].getProteinGroups().size(), 0); // TEST_EQUAL(protein_ids[0].getIndistinguishableProteins().size(), 0); //protein hit 1 TEST_EQUAL(protein_ids[0].getHits()[0].getAccession(),protein_ids2[0].getHits()[0].getAccession()) TEST_EQUAL(protein_ids[0].getHits()[0].getSequence(),protein_ids2[0].getHits()[0].getSequence()) //protein hit 2 TEST_EQUAL(protein_ids[0].getHits()[1].getAccession(),protein_ids2[0].getHits()[1].getAccession()) TEST_EQUAL(protein_ids[0].getHits()[1].getSequence(),protein_ids2[0].getHits()[1].getSequence()) //peptide id 1 TEST_EQUAL(peptide_ids[0].getScoreType(),peptide_ids2[0].getScoreType()) TEST_EQUAL(peptide_ids[0].isHigherScoreBetter(),peptide_ids2[0].isHigherScoreBetter()) TEST_REAL_SIMILAR(peptide_ids[0].getMZ(),peptide_ids2[0].getMZ()) TEST_REAL_SIMILAR(peptide_ids[0].getRT(),peptide_ids2[0].getRT()) TEST_EQUAL(peptide_ids[0].getSpectrumReference(),peptide_ids2[0].getSpectrumReference()) //peptide hit 1 TEST_REAL_SIMILAR(peptide_ids[0].getHits()[0].getScore(),peptide_ids2[0].getHits()[0].getScore()) TEST_EQUAL(peptide_ids[0].getHits()[0].getSequence(),peptide_ids2[0].getHits()[0].getSequence()) TEST_EQUAL(peptide_ids[0].getHits()[0].getCharge(),peptide_ids2[0].getHits()[0].getCharge()) for (size_t i = 0; i < peptide_ids[0].getHits()[0].getPeptideEvidences().size(); ++i){ //AA before/after tested by peptide evidences vector equality check - not working if the order of proteins is pertubated //TEST_EQUAL(peptide_ids[0].getHits()[0].getPeptideEvidences()[i]==peptide_ids2[0].getHits()[0].getPeptideEvidences()[i],true) TEST_EQUAL(peptide_ids[0].getHits()[0].getPeptideEvidences()[i].getStart(),peptide_ids2[0].getHits()[0].getPeptideEvidences()[i].getStart()) TEST_EQUAL(peptide_ids[0].getHits()[0].getPeptideEvidences()[i].getEnd(),peptide_ids2[0].getHits()[0].getPeptideEvidences()[i].getEnd()) TEST_EQUAL(peptide_ids[0].getHits()[0].getPeptideEvidences()[i].getAABefore(),peptide_ids2[0].getHits()[0].getPeptideEvidences()[i].getAABefore()) TEST_EQUAL(peptide_ids[0].getHits()[0].getPeptideEvidences()[i].getAAAfter(),peptide_ids2[0].getHits()[0].getPeptideEvidences()[i].getAAAfter()) // TEST_EQUAL(peptide_ids[0].getHits()[0].getPeptideEvidences()[i].getProteinAccession(),peptide_ids2[0].getHits()[0].getPeptideEvidences()[i].getProteinAccession()) } //peptide hit 2 TEST_REAL_SIMILAR(peptide_ids[0].getHits()[1].getScore(),peptide_ids2[0].getHits()[1].getScore()) TEST_EQUAL(peptide_ids[0].getHits()[1].getSequence(),peptide_ids2[0].getHits()[1].getSequence()) TEST_EQUAL(peptide_ids[0].getHits()[1].getCharge(),peptide_ids2[0].getHits()[1].getCharge()) for (size_t i = 0; i < peptide_ids[0].getHits()[1].getPeptideEvidences().size(); ++i){ // TEST_EQUAL(peptide_ids[0].getHits()[1].getPeptideEvidences()[i]==peptide_ids2[0].getHits()[1].getPeptideEvidences()[i],true) TEST_EQUAL(peptide_ids[0].getHits()[1].getPeptideEvidences()[i].getStart(),peptide_ids2[0].getHits()[1].getPeptideEvidences()[i].getStart()) TEST_EQUAL(peptide_ids[0].getHits()[1].getPeptideEvidences()[i].getEnd(),peptide_ids2[0].getHits()[1].getPeptideEvidences()[i].getEnd()) TEST_EQUAL(peptide_ids[0].getHits()[1].getPeptideEvidences()[i].getAABefore(),peptide_ids2[0].getHits()[1].getPeptideEvidences()[i].getAABefore()) TEST_EQUAL(peptide_ids[0].getHits()[1].getPeptideEvidences()[i].getAAAfter(),peptide_ids2[0].getHits()[1].getPeptideEvidences()[i].getAAAfter()) } //peptide id 2 TEST_EQUAL(peptide_ids[1].getScoreType(),peptide_ids2[1].getScoreType()) TEST_EQUAL(peptide_ids[1].isHigherScoreBetter(),peptide_ids2[1].isHigherScoreBetter()) TEST_REAL_SIMILAR(peptide_ids[1].getMZ(),peptide_ids2[1].getMZ()) TEST_REAL_SIMILAR(peptide_ids[1].getRT(),peptide_ids2[1].getRT()) //peptide hit 1 TEST_REAL_SIMILAR(peptide_ids[1].getHits()[0].getScore(),peptide_ids2[1].getHits()[0].getScore()) TEST_EQUAL(peptide_ids[1].getHits()[0].getSequence(),peptide_ids2[1].getHits()[0].getSequence()) TEST_EQUAL(peptide_ids[1].getHits()[0].getCharge(),peptide_ids2[1].getHits()[0].getCharge()) for (size_t i = 0; i < peptide_ids[1].getHits()[0].getPeptideEvidences().size(); ++i) TEST_EQUAL(peptide_ids[1].getHits()[0].getPeptideEvidences()[i]==peptide_ids2[1].getHits()[0].getPeptideEvidences()[i],true) //peptide hit 2 TEST_REAL_SIMILAR(peptide_ids[1].getHits()[1].getScore(),peptide_ids2[1].getHits()[1].getScore()) TEST_EQUAL(peptide_ids[1].getHits()[1].getSequence(),peptide_ids2[1].getHits()[1].getSequence()) TEST_EQUAL(peptide_ids[1].getHits()[1].getCharge(),peptide_ids2[1].getHits()[1].getCharge()) for (size_t i = 0; i < peptide_ids[1].getHits()[1].getPeptideEvidences().size(); ++i) TEST_EQUAL(peptide_ids[1].getHits()[1].getPeptideEvidences()[i]==peptide_ids2[1].getHits()[1].getPeptideEvidences()[i],true) //peptide id 3 TEST_EQUAL(peptide_ids[2].getScoreType(),peptide_ids2[2].getScoreType()) TEST_EQUAL(peptide_ids[2].isHigherScoreBetter(),peptide_ids2[2].isHigherScoreBetter()) TEST_REAL_SIMILAR(peptide_ids[2].getMZ(),peptide_ids2[2].getMZ()) TEST_REAL_SIMILAR(peptide_ids[2].getRT(),peptide_ids2[2].getRT()) //peptide hit 1 TEST_REAL_SIMILAR(peptide_ids[2].getHits()[0].getScore(),peptide_ids2[2].getHits()[0].getScore()) TEST_EQUAL(peptide_ids[2].getHits()[0].getSequence(),peptide_ids2[2].getHits()[0].getSequence()) TEST_EQUAL(peptide_ids[2].getHits()[0].getCharge(),peptide_ids2[2].getHits()[0].getCharge()) for (size_t i = 0; i < peptide_ids[2].getHits()[0].getPeptideEvidences().size(); ++i) TEST_EQUAL(peptide_ids[2].getHits()[0].getPeptideEvidences()[i]==peptide_ids2[2].getHits()[0].getPeptideEvidences()[i],true) //peptide hit 2 TEST_REAL_SIMILAR(peptide_ids[1].getHits()[1].getScore(),peptide_ids2[1].getHits()[1].getScore()) TEST_EQUAL(peptide_ids[2].getHits()[1].getSequence(),peptide_ids2[2].getHits()[1].getSequence()) TEST_EQUAL(peptide_ids[2].getHits()[1].getCharge(),peptide_ids2[2].getHits()[1].getCharge()) for (size_t i = 0; i < peptide_ids[2].getHits()[1].getPeptideEvidences().size(); ++i) TEST_EQUAL(peptide_ids[2].getHits()[1].getPeptideEvidences()[i]==peptide_ids2[2].getHits()[1].getPeptideEvidences()[i],true) } END_SECTION START_SECTION(([EXTRA] multiple runs)) { std::vector<ProteinIdentification> protein_ids, protein_ids2; PeptideIdentificationList peptide_ids, peptide_ids2; String input_path = OPENMS_GET_TEST_DATA_PATH("MzIdentML_3runs.mzid"); MzIdentMLFile().load(input_path, protein_ids2, peptide_ids2); String filename; NEW_TMP_FILE(filename) MzIdentMLFile().store(filename, protein_ids2, peptide_ids2); MzIdentMLFile().load(filename, protein_ids, peptide_ids); TEST_EQUAL(protein_ids.size(),protein_ids2.size()) TEST_EQUAL(protein_ids[0].getHits().size(),protein_ids2[0].getHits().size()) TEST_EQUAL(protein_ids[1].getHits().size(),protein_ids2[1].getHits().size()) TEST_EQUAL(protein_ids[2].getHits().size(),protein_ids2[2].getHits().size()) TEST_EQUAL(protein_ids[0].getSearchParameters().precursor_mass_tolerance_ppm, true) } END_SECTION START_SECTION(([EXTRA] thresholds)) { std::vector<ProteinIdentification> protein_ids; PeptideIdentificationList peptide_ids; String input_path = OPENMS_GET_TEST_DATA_PATH("MzIdentMLFile_whole.mzid"); MzIdentMLFile().load(input_path, protein_ids, peptide_ids); TEST_EQUAL(protein_ids.size(),1) TEST_EQUAL(protein_ids[0].getSignificanceThreshold(),0.5) TEST_EQUAL(peptide_ids.size(),3) for (size_t i = 0; i < peptide_ids.size(); ++i) { if (peptide_ids[i].getSpectrumReference() == "17") { TEST_EQUAL(peptide_ids[i].getHits().size(),2) for (size_t j = 0; j < peptide_ids[i].getHits().size(); ++j) { TEST_EQUAL(peptide_ids[i].getHits()[j].getMetaValue("pass_threshold"),false) } PeptideHit x = peptide_ids[i].getHits().back(); x.removeMetaValue("pass_threshold"); x.setSequence(AASequence::fromString("TESTER")); x.setScore(0.4); peptide_ids[i].insertHit(x); } } String filename; NEW_TMP_FILE(filename) MzIdentMLFile().store(filename, protein_ids, peptide_ids); protein_ids.clear(); peptide_ids.clear(); MzIdentMLFile().load(filename, protein_ids, peptide_ids); TEST_EQUAL(peptide_ids.size(),3) for (size_t i = 0; i < peptide_ids.size(); ++i) { if (peptide_ids[i].getSpectrumReference() == "17") { TEST_EQUAL(peptide_ids[i].getHits().size(),3) for (size_t j = 0; j < peptide_ids[i].getHits().size(); ++j) { if (peptide_ids[i].getHits()[j].getScore() > protein_ids[0].getSignificanceThreshold()) { TEST_EQUAL(peptide_ids[i].getHits()[j].getMetaValue("pass_threshold"),false) } else TEST_EQUAL(peptide_ids[i].getHits()[j].getMetaValue("pass_threshold"),true) } } } } END_SECTION START_SECTION(([EXTRA] regression test for file loading on example files)) { std::vector<ProteinIdentification> protein_ids; PeptideIdentificationList peptide_ids; String input_path = OPENMS_GET_TEST_DATA_PATH("MzIdentMLFile_whole.mzid"); MzIdentMLFile().load(input_path, protein_ids, peptide_ids); // input_path = OPENMS_GET_TEST_DATA_PATH("Mascot_MSMS_example.mzid"); // MzIdentMLFile().load(input_path, protein_ids, peptide_ids); input_path = OPENMS_GET_TEST_DATA_PATH("MzIdentMLFile_msgf_mini.mzid"); MzIdentMLFile().load(input_path, protein_ids, peptide_ids); input_path = OPENMS_GET_TEST_DATA_PATH("MzIdentML_3runs.mzid"); MzIdentMLFile().load(input_path, protein_ids, peptide_ids); } END_SECTION START_SECTION(([EXTRA] compability issues)) { // MzIdentMLFile mzidfile; // vector<ProteinIdentification> protein_ids; // PeptideIdentificationList peptide_ids; // mzidfile.load(OPENMS_GET_TEST_DATA_PATH("MzIdentMLFile_no_proteinhits.mzid"), protein_ids, peptide_ids); // TEST_EQUAL(protein_ids.size(), 1) // TEST_EQUAL(protein_ids[0].getHits().size(), 0) // TEST_EQUAL(peptide_ids.size(), 10) // TEST_EQUAL(peptide_ids[0].getHits().size(), 1) // String filename; // NEW_TMP_FILE(filename) // mzidfile.store(filename , protein_ids, peptide_ids); // vector<ProteinIdentification> protein_ids2; // PeptideIdentificationList peptide_ids2; // mzidfile.load(filename, protein_ids2, peptide_ids2); // TEST_TRUE(protein_ids == protein_ids2) // TEST_TRUE(peptide_ids == peptide_ids2) // Misplaced Elements ignored in ParamGroup // Converting unknown score type to search engine specific score CV. #should not occur scoretype is whatever // PSM without peptide evidences registered in the given search database found. This will cause an invalid MzIdentML file (which OpenMS still can consume). #might occur when reading idxml. no protein reference accession // No RT #might occurr when reading idxml. no rt to peptidehit // No MZ #might occurr when reading idxml. no mz to peptidehit // PeptideEvidence without reference to the positional in originating sequence found. #will always occur when reading idxml no start end positional arguments } END_SECTION START_SECTION(([EXTRA] XLMS data labeled cross-linker)) { vector<ProteinIdentification> protein_ids; PeptideIdentificationList peptide_ids; vector<ProteinIdentification> protein_ids2; PeptideIdentificationList peptide_ids2; String input_file= OPENMS_GET_TEST_DATA_PATH("MzIdentML_XLMS_labelled.mzid"); MzIdentMLFile().load(input_file, protein_ids, peptide_ids); // TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), 3) TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), 4) TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA), "ANYWHERE") TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE), "SAVIKTSTR") TEST_EQUAL(peptide_ids[1].getHits()[0].getSequence().toString(), "FIVKASSGPR") // Reading and writing String filename; NEW_TMP_FILE(filename) MzIdentMLFile().store(filename, protein_ids, peptide_ids); MzIdentMLFile().load(filename, protein_ids2, peptide_ids2); // parameters from written and reloaded file // ProteinIdentification TEST_EQUAL(protein_ids2[0].getSearchParameters().fragment_mass_tolerance_ppm, false) TEST_EQUAL(protein_ids2[0].getSearchParameters().precursor_mass_tolerance_ppm, true) TEST_EQUAL(protein_ids2[0].getSearchParameters().getMetaValue("cross_link:residue1"), "[K, N-term]") TEST_EQUAL(protein_ids2[0].getSearchParameters().getMetaValue("cross_link:residue2"), "[K, N-term]") TEST_REAL_SIMILAR(String(protein_ids2[0].getSearchParameters().getMetaValue("cross_link:mass")).toDouble(), 138.0680796) TEST_REAL_SIMILAR(String(protein_ids2[0].getSearchParameters().getMetaValue("cross_link:mass_isoshift")).toDouble(), 12.075321) TEST_EQUAL(protein_ids2[0].getSearchParameters().getMetaValue("extra_features"), "precursor_mz_error_ppm,\ OpenPepXL:score,isotope_error,OpenPepXL:xquest_score,OpenPepXL:xcorr xlink,\ OpenPepXL:xcorr common,OpenPepXL:match-odds,OpenPepXL:intsum,OpenPepXL:wTIC,OpenPepXL:TIC,OpenPepXL:prescore,OpenPepXL:log_occupancy,\ OpenPepXL:log_occupancy_alpha,OpenPepXL:log_occupancy_beta,matched_xlink_alpha,matched_xlink_beta,matched_linear_alpha,\ matched_linear_beta,ppm_error_abs_sum_linear_alpha,ppm_error_abs_sum_linear_beta,ppm_error_abs_sum_xlinks_alpha,\ ppm_error_abs_sum_xlinks_beta,ppm_error_abs_sum_linear,ppm_error_abs_sum_xlinks,ppm_error_abs_sum_alpha,ppm_error_abs_sum_beta,\ ppm_error_abs_sum,precursor_total_intensity,precursor_target_intensity,precursor_signal_proportion,precursor_target_peak_count,\ precursor_residual_peak_count") TEST_EQUAL(protein_ids[0].getMetaValue("SpectrumIdentificationProtocol"), "MS:1002494") // crosslinking search // PeptideIdentification (Indices may change, without making the reading/writing invalid, if e.g. more is added to the test file) TEST_EQUAL(peptide_ids2.size(), 10) TEST_EQUAL(peptide_ids2[1].getRT(), peptide_ids2[2].getRT()) TEST_REAL_SIMILAR(peptide_ids2[1].getRT(), 2132.4757) TEST_REAL_SIMILAR(peptide_ids2[1].getMZ(), 721.0845) TEST_EQUAL(peptide_ids2[1].getMetaValue(Constants::UserParam::SPECTRUM_REFERENCE), "spectrum=131,spectrum=113") // PeptideHit TEST_EQUAL(peptide_ids2[0].getHits().size(), 1) TEST_EQUAL(peptide_ids2[3].getHits().size(), 1) TEST_EQUAL(peptide_ids2[1].getHits().size(), 1) TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE), "cross-link") TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_RT), 2125.5966796875) TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_MZ), 725.109252929687841) TEST_REAL_SIMILAR(peptide_ids2[1].getHits()[0].getScore(), -0.190406834856118) TEST_EQUAL(peptide_ids2[1].getHits()[0].getSequence().toString(), "FIVKASSGPR") TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE), "SAVIKTSTR") TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), 3) TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), 4) TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA), "ANYWHERE") TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA), "ANYWHERE") TEST_REAL_SIMILAR(String(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS)).toDouble(), 138.0680796) TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD), "DSS") TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[0].annotation, "[alpha|ci$b2]") TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[0].charge, 1) TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[1].annotation, "[beta|ci$y2]") TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[8].annotation, "[alpha|xi$b4]") TEST_EQUAL(peptide_ids2[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE), "mono-link") TEST_EQUAL(peptide_ids2[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), 5) TEST_EQUAL(peptide_ids2[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), "-") } END_SECTION START_SECTION(([EXTRA] XLMS data unlabeled cross-linker)) { vector<ProteinIdentification> protein_ids; PeptideIdentificationList peptide_ids; vector<ProteinIdentification> protein_ids2; PeptideIdentificationList peptide_ids2; String input_file = OPENMS_GET_TEST_DATA_PATH("MzIdentML_XLMS_unlabelled.mzid"); MzIdentMLFile().load(input_file, protein_ids, peptide_ids); // Reading and writing String filename; NEW_TMP_FILE(filename) MzIdentMLFile().store(filename, protein_ids, peptide_ids); MzIdentMLFile().load(filename, protein_ids2, peptide_ids2); // ProteinIdentification TEST_EQUAL(protein_ids2[0].getSearchParameters().fragment_mass_tolerance_ppm, true) TEST_EQUAL(protein_ids2[0].getSearchParameters().precursor_mass_tolerance_ppm, true) TEST_EQUAL(protein_ids2[0].getSearchParameters().getMetaValue("cross_link:residue1"), "[K, N-term]") TEST_EQUAL(protein_ids2[0].getSearchParameters().getMetaValue("cross_link:residue2"), "[K, N-term]") TEST_EQUAL(String(protein_ids2[0].getSearchParameters().getMetaValue("cross_link:mass")).toDouble(), 138.0680796) TEST_EQUAL(protein_ids[0].getMetaValue("SpectrumIdentificationProtocol"), "MS:1002494") // crosslinking search // PeptideIdentification (Indices may change, without making the reading/writing invalid, if e.g. more is added to the test file) TEST_EQUAL(peptide_ids2.size(), 3) TEST_REAL_SIMILAR(peptide_ids2[0].getRT(), 2175.3003) TEST_REAL_SIMILAR(peptide_ids2[0].getMZ(), 787.740356445313) TEST_EQUAL(peptide_ids2[0].getMetaValue(Constants::UserParam::SPECTRUM_REFERENCE), "controllerType=0 controllerNumber=1 scan=2395") // PeptideHit TEST_EQUAL(peptide_ids2[0].getHits().size(), 1) TEST_EQUAL(peptide_ids2[1].getHits().size(), 1) TEST_EQUAL(peptide_ids2[2].getHits().size(), 1) TEST_EQUAL(peptide_ids2[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE), "mono-link") TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE), "cross-link") TEST_EQUAL(peptide_ids2[2].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE), "mono-link") TEST_EQUAL(peptide_ids2[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), 5) TEST_EQUAL(peptide_ids2[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), "-") TEST_EQUAL(peptide_ids2[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA), "ANYWHERE") TEST_EQUAL(peptide_ids2[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA), "ANYWHERE") TEST_EQUAL(peptide_ids2[1].getHits()[0].getSequence().toString(), "KNVPIEFPVIDR") TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE), "LGCKALHVLFER") TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), 0) TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), 3) TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS), 138.0680796) TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD), "DSS") TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA), "ANYWHERE") TEST_EQUAL(peptide_ids2[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA), "ANYWHERE") TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations().size(), 5) TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[0].annotation, "[alpha|ci$y5]") TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[0].charge, 1) TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[1].annotation, "[alpha|ci$y7]") TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[2].annotation, "[beta|ci$y7]") TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[3].annotation, "[alpha|ci$y8]") TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[2].charge, 1) TEST_EQUAL(peptide_ids2[1].getHits()[0].getPeakAnnotations()[4].charge, 2) TEST_EQUAL(peptide_ids2[2].getHits()[0].getSequence().toString(), "VEPSWLGPLFPDK(Xlink:DSS[156])TSNLR") TEST_EQUAL(peptide_ids2[2].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE), "-") TEST_EQUAL(peptide_ids2[2].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), 12) TEST_EQUAL(peptide_ids2[2].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), "-") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SignalToNoiseEstimatorMedian_test.cpp
.cpp
2,866
97
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/DTAFile.h> /////////////////////////// #include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMedian.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(SignalToNoiseEstimatorMedian, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// SignalToNoiseEstimatorMedian< >* ptr = nullptr; SignalToNoiseEstimatorMedian< >* nullPointer = nullptr; START_SECTION((SignalToNoiseEstimatorMedian())) ptr = new SignalToNoiseEstimatorMedian<>; TEST_NOT_EQUAL(ptr, nullPointer) SignalToNoiseEstimatorMedian<> sne; END_SECTION START_SECTION((SignalToNoiseEstimatorMedian& operator=(const SignalToNoiseEstimatorMedian &source))) MSSpectrum raw_data; SignalToNoiseEstimatorMedian<> sne; sne.init(raw_data); SignalToNoiseEstimatorMedian<> sne2 = sne; NOT_TESTABLE END_SECTION START_SECTION((SignalToNoiseEstimatorMedian(const SignalToNoiseEstimatorMedian &source))) MSSpectrum raw_data; SignalToNoiseEstimatorMedian<> sne; sne.init(raw_data); SignalToNoiseEstimatorMedian<> sne2(sne); NOT_TESTABLE END_SECTION START_SECTION((virtual ~SignalToNoiseEstimatorMedian())) delete ptr; END_SECTION START_SECTION([EXTRA](virtual void init(const Container& c))) MSSpectrum raw_data; MSSpectrum::const_iterator it; DTAFile dta_file; dta_file.load(OPENMS_GET_TEST_DATA_PATH("SignalToNoiseEstimator_test.dta"), raw_data); SignalToNoiseEstimatorMedian< MSSpectrum > sne; Param p; p.setValue("win_len", 40.0); p.setValue("noise_for_empty_window", 2.0); p.setValue("min_required_elements", 10); sne.setParameters(p); sne.init(raw_data); MSSpectrum stn_data; dta_file.load(OPENMS_GET_TEST_DATA_PATH("SignalToNoiseEstimatorMedian_test.out"), stn_data); int i = 0; for (it=raw_data.begin();it!=raw_data.end(); ++it) { TEST_REAL_SIMILAR (stn_data[i].getIntensity(), sne.getSignalToNoise(i)); //Peak1D peak = (*it); //peak.setIntensity(sne.getSignalToNoise(it)); //stn_data.push_back(peak); ++i; } //dta_file.store("./data/SignalToNoiseEstimatorMedian_test.tmp", stn_data); //TEST_FILE_EQUAL("./data/SignalToNoiseEstimatorMedian_test.tmp", "./data/SignalToNoiseEstimatorMedian_test.out"); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Adduct_test.cpp
.cpp
4,629
200
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/Adduct.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(Adduct, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Adduct* ptr = nullptr; Adduct* nullPointer = nullptr; START_SECTION(Adduct()) { ptr = new Adduct(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~Adduct()) { delete ptr; } END_SECTION START_SECTION((Adduct(Int charge))) { Adduct a(123); TEST_EQUAL(a.getCharge(), 123); } END_SECTION START_SECTION((Adduct(Int charge, Int amount, double singleMass, String formula, double log_prob, double rt_shift, const String label=""))) { Adduct a(123, 43, 123.456f, "S", -0.3453, -10); TEST_EQUAL(a.getCharge(), 123); TEST_EQUAL(a.getAmount(), 43); TEST_REAL_SIMILAR(a.getSingleMass(), 123.456); TEST_EQUAL(a.getFormula()=="S1", true); TEST_REAL_SIMILAR(a.getLogProb(), -0.3453); TEST_REAL_SIMILAR(a.getRTShift(), -10); TEST_EQUAL(a.getLabel(), ""); Adduct a2(123, 43, 123.456f, "S", -0.3453, -10, "testlabel"); TEST_EQUAL(a2.getLabel(), "testlabel"); } END_SECTION START_SECTION([EXTRA] friend OPENMS_DLLAPI bool operator==(const Adduct& a, const Adduct& b)) { Adduct a(123, 3, 123.456f, "S", -0.3453f, 0); Adduct b(a); TEST_TRUE(a == b); a.setAmount(22); TEST_EQUAL(a==b, false); } END_SECTION START_SECTION((const Int& getCharge() const)) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setCharge(const Int &charge))) { Adduct a; a.setCharge(123); TEST_EQUAL(a.getCharge(), 123); } END_SECTION START_SECTION((const Int& getAmount() const)) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setAmount(const Int &amount))) { Adduct a; a.setAmount(43); TEST_EQUAL(a.getAmount(), 43); } END_SECTION START_SECTION((const double& getSingleMass() const)) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setSingleMass(const double &singleMass))) { Adduct a; a.setSingleMass(43.21); TEST_REAL_SIMILAR(a.getSingleMass(), 43.21); } END_SECTION START_SECTION((const double& getLogProb() const)) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setLogProb(const double &log_prob))) { Adduct a; a.setLogProb(43.21f); TEST_REAL_SIMILAR(a.getLogProb(), 43.21); } END_SECTION START_SECTION((const String& getFormula() const)) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setFormula(const String &formula))) Adduct a; a.setFormula("S"); TEST_EQUAL(a.getFormula()=="S1", true); END_SECTION START_SECTION((const double& getRTShift() const)) Adduct a(123, 43, 123.456f, "S", -0.3453, -10); TEST_REAL_SIMILAR(a.getRTShift(), -10); Adduct a1(123, 43, 123.456f, "S", -0.3453, 11); TEST_REAL_SIMILAR(a1.getRTShift(), 11); END_SECTION START_SECTION((const String& getLabel() const )) Adduct a(123, 43, 123.456f, "S", -0.3453, -10); TEST_EQUAL(a.getLabel(), ""); Adduct a1(123, 43, 123.456f, "S", -0.3453, 11, "mylabel"); TEST_EQUAL(a1.getLabel(), "mylabel"); END_SECTION START_SECTION((Adduct operator *(const Int m) const)) { Adduct a_p(123, 43, 123.456, "S", -0.3453, 0); Adduct a = a_p*4; TEST_EQUAL(a.getCharge(), 123); TEST_EQUAL(a.getAmount(), 43*4); TEST_REAL_SIMILAR(a.getSingleMass(), 123.456f); TEST_EQUAL(a.getFormula()=="S1", true); TEST_REAL_SIMILAR(a.getLogProb(), -0.3453); } END_SECTION START_SECTION((Adduct operator+(const Adduct &rhs))) { Adduct a_p(123, 43, 123.456f, "S", -0.3453f, 0); Adduct a_p2(123, 40, 123.456f, "S", -0.3453f, 0); Adduct a = a_p + a_p2; TEST_EQUAL(a.getCharge(), 123); TEST_EQUAL(a.getAmount(), 43+40); TEST_REAL_SIMILAR(a.getSingleMass(), 123.456); TEST_EQUAL(a.getFormula()=="S1", true); TEST_REAL_SIMILAR(a.getLogProb(), -0.3453); } END_SECTION START_SECTION((void operator+=(const Adduct &rhs))) { Adduct a_p(123, 43, 123.456f, "S", -0.3453f, 0); Adduct a(a_p); a.setAmount(10); a += a_p; TEST_EQUAL(a.getAmount(), 43+10); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp
.cpp
1,716
69
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: George Rosenberger $ // $Authors: George Rosenberger, Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/TraMLFile.h> #include <boost/assign/std/vector.hpp> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/TransitionPQPFile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(TransitionPQPFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TransitionPQPFile* ptr = nullptr; TransitionPQPFile* nullPointer = nullptr; START_SECTION(TransitionPQPFile()) { ptr = new TransitionPQPFile(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~TransitionPQPFile()) { delete ptr; } END_SECTION START_SECTION( void convertTargetedExperimentToPQP(const char * filename, OpenMS::TargetedExperiment & targeted_exp)) { // see TOPP tool test NOT_TESTABLE } END_SECTION START_SECTION( void convertPQPToTargetedExperiment(const char * filename, OpenMS::TargetedExperiment & targeted_exp)) { // see TOPP tool test NOT_TESTABLE } END_SECTION START_SECTION( void validateTargetedExperiment(OpenMS::TargetedExperiment & targeted_exp)) { NOT_TESTABLE } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IsobaricQuantitationMethod_test.cpp
.cpp
5,876
202
// 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/IsobaricQuantitationMethod.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/Matrix.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> using namespace OpenMS; using namespace std; class TestQuantitationMethod : public IsobaricQuantitationMethod { public: IsobaricChannelList channel_list; String name; StringList correction_list; TestQuantitationMethod() { setName("TestQuantitationMethod"); channel_list.push_back(IsobaricChannelInformation("114", 0, "", 114.1112, {-1, -1, 1, 2})); channel_list.push_back(IsobaricChannelInformation("115", 1, "", 115.1082, {-1, 0, 2, 3})); channel_list.push_back(IsobaricChannelInformation("116", 2, "", 116.1116, {0, 1, 3, -1})); channel_list.push_back(IsobaricChannelInformation("117", 3, "", 117.1149, {1, 2, -1, -1})); name = "TestQuantitationMethod"; } ~TestQuantitationMethod() override = default; const String& getMethodName() const override { return name; } const IsobaricChannelList& getChannelInformation() const override { return channel_list; } Size getNumberOfChannels() const override { return 4; } Matrix<double> getIsotopeCorrectionMatrix() const override { return stringListToIsotopeCorrectionMatrix_(correction_list); } Size getReferenceChannel() const override { return 0; } }; START_TEST(IsobaricQuantitationMethod, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// IsobaricQuantitationMethod* ptr = nullptr; IsobaricQuantitationMethod* null_ptr = nullptr; START_SECTION(IsobaricQuantitationMethod()) { ptr = new TestQuantitationMethod(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~IsobaricQuantitationMethod()) { delete ptr; } END_SECTION START_SECTION((virtual const String& getName() const =0)) { IsobaricQuantitationMethod* quant_method = new TestQuantitationMethod(); TEST_STRING_EQUAL(quant_method->getName(), "TestQuantitationMethod") delete quant_method; } END_SECTION START_SECTION((virtual const IsobaricChannelList& getChannelInformation() const =0)) { IsobaricQuantitationMethod* quant_method = new TestQuantitationMethod(); IsobaricQuantitationMethod::IsobaricChannelList cl = quant_method->getChannelInformation(); TEST_EQUAL(cl.size(), 4) ABORT_IF(cl.size() != 4) TEST_STRING_EQUAL(cl[0].description, "") TEST_EQUAL(cl[0].name, 114) TEST_EQUAL(cl[0].id, 0) TEST_EQUAL(cl[0].center, 114.1112) delete quant_method; } END_SECTION START_SECTION((virtual Size getNumberOfChannels() const =0)) { IsobaricQuantitationMethod* quant_method = new TestQuantitationMethod(); TEST_EQUAL(quant_method->getNumberOfChannels(), 4) delete quant_method; } END_SECTION START_SECTION((virtual Matrix<double> getIsotopeCorrectionMatrix() const =0 with Exception)) { auto* quant_method = new TestQuantitationMethod(); // missing entry quant_method->correction_list = ListUtils::create<String>("0.0/1.0/5.9/0.2,0.0/2.0/ 0.1,0.0/3.0/4.5/0.1,0.1/4.0/3.5/0.1"); TEST_EXCEPTION(Exception::InvalidValue, quant_method->getIsotopeCorrectionMatrix()) delete quant_method; } END_SECTION START_SECTION((virtual Matrix<double> getIsotopeCorrectionMatrix() const =0)) { auto* quant_method = new TestQuantitationMethod(); quant_method->correction_list = ListUtils::create<String>("0.0/1.0/5.9/0.2,0.0/2.0/5.6/0.1,0.0/3.0/4.5/0.1,0.1/4.0/3.5/0.1"); Matrix<double> m = quant_method->getIsotopeCorrectionMatrix(); ABORT_IF(m.rows() != 4) ABORT_IF(m.cols() != 4) 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(real_m[i][j], m(i,j)) } } quant_method->correction_list = ListUtils::create<String>("0.0/1.0/10.9/0.2,0.0/2.0/5.6/0.6,0.0/10.0/4.5/0.1,0.1/4.0/3.5/0.1"); m = quant_method->getIsotopeCorrectionMatrix(); ABORT_IF(m.rows() != 4) ABORT_IF(m.cols() != 4) double real_m2[4][4] = {{0.879, 0.02, 0, 0}, {0.109, 0.918, 0.1, 0.001}, {0.002, 0.056, 0.854, 0.04}, {0, 0.006, 0.045, 0.923}}; for(Size i = 0; i < m.rows(); ++i) { for(Size j = 0; j < m.cols(); ++j) { TEST_REAL_SIMILAR(real_m2[i][j], m(i,j)) } } delete quant_method; } END_SECTION START_SECTION((virtual Size getReferenceChannel() const =0)) { IsobaricQuantitationMethod* quant_method = new TestQuantitationMethod(); TEST_EQUAL(quant_method->getReferenceChannel(), 0) delete quant_method; } END_SECTION START_SECTION(([IsobaricQuantitationMethod::IsobaricChannelInformation] IsobaricChannelInformation(const Int name, const Int id, const String &description, const Peak2D::CoordinateType &center))) { IsobaricQuantitationMethod::IsobaricChannelInformation cI(114, 0, "", 114.1112, {-1, -1, -1, -1}); TEST_STRING_EQUAL(cI.description, "") TEST_EQUAL(cI.name, 114) TEST_EQUAL(cI.id, 0) TEST_EQUAL(cI.center, 114.1112) TEST_EQUAL(cI.affected_channels[0], -1) TEST_EQUAL(cI.affected_channels[1], -1) TEST_EQUAL(cI.affected_channels[2], -1) TEST_EQUAL(cI.affected_channels[3], -1) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/XMLHandler_test.cpp
.cpp
4,448
160
#include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <string> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> class StringManager_test : public OpenMS::Internal::StringManager { public: StringManager_test() = default; ~StringManager_test() = default; static void compress64(const XMLCh* input_it, char* output_it) { StringManager::compress64_(input_it, output_it); } }; using namespace OpenMS::Internal; START_TEST(StringManager, "$Id$") const XMLCh russianHello[] = { 0x041F, 0x0440, 0x0438, 0x0432, 0x0435, 0x0442, 0x043C, 0x0438, 0x0440,0x0000 // "Привет мир" (Hello World in Russian) }; XMLSize_t r_length = xercesc::XMLString::stringLen(russianHello); const XMLCh ascii[] = { 0x0048,0x0065,0x006C,0x006C,0x006F,0x002C,0x0057,0x006F, 0x0072,0x006C,0x0064,0x0021, 0x0000}; XMLSize_t a_length = xercesc::XMLString::stringLen(ascii); const XMLCh mixed[] = { 0x0048, 0x0065,0x0432, 0x0435, 0x0442, 0x043C, 0x006F, 0x0072,0x006C,0x0064, 0x0021, 0x0000 }; XMLSize_t m_length = xercesc::XMLString::stringLen(mixed); const XMLCh empty[] = {0}; XMLSize_t e_length = xercesc::XMLString::stringLen(empty); const XMLCh upperBoundary [] = {0x00FF,0x00FF,0x0000}; XMLSize_t u_length = xercesc::XMLString::stringLen(upperBoundary); bool isAscii = false; START_SECTION(isASCII(const XMLCh * chars, const XMLSize_t length)) isAscii = StringManager::isASCII(ascii,a_length); TEST_TRUE(isAscii) isAscii = StringManager::isASCII(russianHello,r_length); TEST_FALSE(isAscii) isAscii = StringManager::isASCII(mixed,m_length); TEST_FALSE(isAscii) isAscii = StringManager::isASCII(empty,e_length); TEST_TRUE(isAscii) isAscii = StringManager::isASCII(upperBoundary,u_length); TEST_TRUE(isAscii) END_SECTION const XMLCh eight_block_negative[] = {0x0148,0x0165,0x016C,0x016C,0x016F,0x012C,0x0157,0x016F}; const XMLCh eight_block[] = {0x0048,0x0065,0x006C,0x006C,0x006F,0x002C,0x0057,0x006F}; const XMLCh eight_block_mixed[] ={0x0042,0x0045,0x004C,0x0041,0x0142,0x0145,0x014C,0x0141}; const XMLCh eight_block_kadabra[] = { 0x004B, // K 0x0041, // A 0x0044, // D 0x0041, // A 0x0042, // B 0x0052, // R 0x0041, // A 0x0021 // ! }; START_SECTION(compress64 (const XMLCh* input_it, char* output_it)) std::string o1_str(8,'\0'); StringManager_test::compress64(eight_block,o1_str.data()); std::string res1_str = "Hello,Wo"; TEST_STRING_EQUAL(o1_str,res1_str); std::string o2_str(8,'\0'); StringManager_test::compress64(eight_block_negative,o2_str.data()); std::string res2_str = res1_str; TEST_STRING_EQUAL(o2_str, res2_str); std::string o3_str(8,'\0'); StringManager_test::compress64(eight_block_mixed,o3_str.data()); std::string res3_str = {0x42,0x45,0x4C,0x41,0x42,0x45,0x4C,0x41}; TEST_STRING_EQUAL(o3_str, res3_str); std::string o4_str(12,'\0'); o4_str [0] ='A'; o4_str [1] ='B'; o4_str [2] ='R'; o4_str [3] ='A'; StringManager_test::compress64(eight_block_kadabra,((o4_str.data())+4)); std::string res4_str = "ABRAKADABRA!"; TEST_STRING_EQUAL(o4_str, res4_str); END_SECTION //Tests Number of Chars not Dividable by 8 OpenMS::String o5_str; std::string res5_str = "Hello,World!"; //Checks how the Function handles Data thats already stored in Output string OpenMS::String o6_str = "Gruess Gott und "; std::string res6_str = "Gruess Gott und Hello,World!"; OpenMS::String o7_str; std::string res7_str = ""; START_SECTION(appendASCII(const XMLCh * chars, const XMLSize_t length, String & result)) StringManager::appendASCII(ascii,a_length,o5_str); TEST_STRING_EQUAL(o5_str, res5_str); StringManager::appendASCII(ascii,a_length,o6_str); TEST_STRING_EQUAL(o6_str, res6_str); StringManager::appendASCII(empty,e_length,o7_str); TEST_STRING_EQUAL(o7_str, res7_str); END_SECTION XMLCh* nullPointer = nullptr; START_SECTION(strLength(const XMLCh* input_ptr)) int o_length = StringManager::strLength(ascii); TEST_EQUAL(o_length, a_length); o_length = StringManager::strLength(empty); TEST_EQUAL(o_length, e_length); o_length = StringManager::strLength(upperBoundary); TEST_EQUAL(o_length, u_length); o_length = StringManager::strLength(nullPointer); TEST_EQUAL(o_length, 0); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeakWidthEstimator_test.cpp
.cpp
1,978
60
// 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/PeakWidthEstimator.h> #include <OpenMS/FORMAT/MzMLFile.h> using namespace OpenMS; START_TEST(PeakWidthEstimator, "$Id$") PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("PeakPickerHiRes_orbitrap.mzML"), exp); PeakPickerHiRes picker; Param param = picker.getParameters(); param.setValue("ms_levels", ListUtils::create<Int>("1")); param.setValue("signal_to_noise", 0.0); picker.setParameters(param); std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > boundaries_exp_s; std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > boundaries_exp_c; PeakMap exp_picked; picker.pickExperiment(exp, exp_picked, boundaries_exp_s, boundaries_exp_c); PeakWidthEstimator* nullPointer = nullptr; PeakWidthEstimator* ptr; START_SECTION(PeakWidthEstimator(const PeakMap & exp_picked, const std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > & boundaries)) { PeakWidthEstimator estimator(exp_picked, boundaries_exp_s); TEST_REAL_SIMILAR(estimator.getPeakWidth(365.3),0.00886469661896705); ptr = new PeakWidthEstimator(exp_picked, boundaries_exp_s); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; } END_SECTION PeakWidthEstimator estimator2(exp_picked, boundaries_exp_s); START_SECTION(double getPeakWidth(double mz)) { TEST_REAL_SIMILAR(estimator2.getPeakWidth(365.3),0.00886469661896705); TEST_REAL_SIMILAR(estimator2.getPeakWidth(305.1),0.00886699447290451); // outside m/z range TEST_REAL_SIMILAR(estimator2.getPeakWidth(405.1),0.01184458329884600); // outside m/z range } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/OpenSwathTestHelper.h
.h
5,501
225
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/MRMTransitionGroup.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <OpenMS/KERNEL/ChromatogramPeak.h> #include <OpenMS/ANALYSIS/MRM/ReactionMonitoringTransition.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h> namespace OpenSWATH_Test { using namespace OpenMS; typedef OpenSwath::LightTransition TransitionType; //typedef ReactionMonitoringTransition TransitionType; typedef MRMTransitionGroup<MSChromatogram, TransitionType> MRMTransitionGroupType; MRMFeature createMockFeature() { MRMFeature feature; feature.setRT(3120); feature.setIntensity(static_cast<float>(973.122)); { Feature f; static const double arr1[] = { 3103.13, 3106.56, 3109.98, 3113.41, 3116.84, 3120.26, 3123.69, 3127.11, 3130.54, 3133.97, 3137.4 }; std::vector<double> mz (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); static const double arr2[] = { 5.97544, 4.27492, 3.33018, 4.08597, 5.50307, 5.24327, 8.40812, 2.8342 , 6.94379, 7.69957, 4.08597 }; std::vector<double> intensity (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); ConvexHull2D::PointArrayType hull_points; for (Size i = 0; i < mz.size(); i++) { DPosition<2> p(mz[i],intensity[i]); hull_points.push_back(p); } ConvexHull2D hull; hull.setHullPoints(hull_points); f.getConvexHulls().push_back(hull); f.setIntensity(static_cast<float>(58.38450)); feature.addFeature(f, "tr3"); } { Feature f; static const double arr1[] = { 3103.13, 3106.56, 3109.98, 3113.41, 3116.84, 3120.26, 3123.69, 3127.11, 3130.54, 3133.97, 3137.4 }; std::vector<double> mz (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); static const double arr2[] = { 15.8951, 41.5446, 76.0746, 109.069, 111.904, 169.792, 121.044, 63.0137, 44.615 , 21.4927, 7.93576 }; std::vector<double> intensity (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); ConvexHull2D::PointArrayType hull_points; for (Size i = 0; i < mz.size(); i++) { DPosition<2> p(mz[i],intensity[i]); hull_points.push_back(p); } ConvexHull2D hull; hull.setHullPoints(hull_points); f.setIntensity(782.38073); f.getConvexHulls().push_back(hull); feature.addFeature(f, "tr1"); } { Feature f; static const double arr1[] = { 3103.13, 3106.56, 3109.98, 3113.41, 3116.84, 3120.26, 3123.69, 3127.11, 3130.54, 3133.97, 3137.4 }; std::vector<double> mz (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); static const double arr2[] = { 5.73925, 6.7076 , 2.85782, 5.0307 , 8.95135, 14.4544, 20.9731, 24.3033, 20.6897, 13.7459, 8.90411 }; std::vector<double> intensity (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); ConvexHull2D::PointArrayType hull_points; for (Size i = 0; i < mz.size(); i++) { DPosition<2> p(mz[i],intensity[i]); hull_points.push_back(p); } ConvexHull2D hull; hull.setHullPoints(hull_points); f.setIntensity(static_cast<float>(58.38450)); f.getConvexHulls().push_back(hull); feature.addFeature(f, "tr5"); } return feature; } MRMTransitionGroupType createMockTransitionGroup() { MRMTransitionGroupType transition_group; { String native_id = "tr3"; MSChromatogram chrom; chrom.setNativeID(native_id); transition_group.addChromatogram(chrom, native_id ); TransitionType tr; tr.library_intensity = 10000; tr.product_mz = 618.31; tr.fragment_charge = 1; tr.transition_name = native_id; transition_group.addTransition(tr, native_id ); } { String native_id = "tr1"; MSChromatogram chrom; chrom.setNativeID(native_id); transition_group.addChromatogram(chrom, native_id ); TransitionType tr; tr.library_intensity = 1; tr.product_mz = 628.435; tr.fragment_charge = 1; tr.transition_name = native_id; transition_group.addTransition(tr, native_id ); } { String native_id = "tr5"; MSChromatogram chrom; chrom.setNativeID(native_id); transition_group.addChromatogram(chrom, native_id ); TransitionType tr; tr.library_intensity = 2000; tr.product_mz = 628.435; tr.fragment_charge = 1; tr.transition_name = native_id; transition_group.addTransition(tr, native_id ); } return transition_group; } }
Unknown
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MetaInfo_test.cpp
.cpp
8,981
342
// 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/MetaInfo.h> /////////////////////////// START_TEST(Example, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace std; using namespace OpenMS; MetaInfo* test = nullptr; MetaInfo* nullPointer = nullptr; START_SECTION((MetaInfo())) test = new MetaInfo; TEST_NOT_EQUAL(test, nullPointer) END_SECTION START_SECTION((~MetaInfo())) delete test; END_SECTION MetaInfo mi; START_SECTION((static MetaInfoRegistry& registry())) MetaInfo mi2; mi2.registry().registerName("testname", "testdesc", "testunit"); TEST_EQUAL(mi2.registry().getIndex("testname"), 1024); TEST_EQUAL(mi.registry().getIndex("testname"), 1024); END_SECTION START_SECTION((void setValue(const String& name, const DataValue& value))) NOT_TESTABLE //tested in the get method END_SECTION START_SECTION((void setValue(UInt index, const DataValue& value))) NOT_TESTABLE //tested in the get method END_SECTION START_SECTION((const DataValue& getValue(UInt index, const DataValue& default_value = DataValue::EMPTY) const)) { string tmp; mi.setValue(1024, String("testtesttest")); tmp = String(mi.getValue(1024)); TEST_EQUAL(tmp, "testtesttest"); TEST_EQUAL(mi.getValue(1025) == DataValue::EMPTY, true); TEST_EQUAL(mi.getValue(1025, 10) == DataValue(10), true); } END_SECTION START_SECTION((const DataValue& getValue(const String& name, const DataValue& default_value = DataValue::EMPTY) const)) { string tmp; mi.setValue("testname", String("testtesttest2")); tmp = String(mi.getValue("testname")); TEST_EQUAL(tmp, "testtesttest2"); TEST_EQUAL(mi.getValue("notdefined") == DataValue::EMPTY, true); TEST_EQUAL(mi.getValue("notdefined", 10) == DataValue(10), true); } END_SECTION mi.setValue("cluster_id",4711.12f); mi.setValue(2,4712.12f); START_SECTION((bool empty() const)) MetaInfo tmp; TEST_EQUAL(tmp.empty(),true) tmp.setValue(1024,String("testtesttest")); TEST_EQUAL(tmp.empty(),false) END_SECTION START_SECTION((MetaInfo(const MetaInfo& rhs))) MetaInfo mi3(mi); TEST_REAL_SIMILAR(double(mi3.getValue("cluster_id")),double(mi.getValue("cluster_id"))) TEST_STRING_EQUAL(mi3.getValue("testname"),"testtesttest2") END_SECTION START_SECTION((MetaInfo& operator = (const MetaInfo& rhs))) MetaInfo mi3; mi3 = mi; TEST_REAL_SIMILAR(double(mi3.getValue("cluster_id")),double(mi.getValue("cluster_id"))) TEST_STRING_EQUAL(mi3.getValue("testname"),"testtesttest2") END_SECTION START_SECTION((void getKeys(std::vector<String>& keys) const)) vector<String> tmp,tmp2; tmp.push_back("cluster_id"); tmp.push_back("testname"); mi.getKeys(tmp2); TEST_EQUAL(tmp2.size(),tmp.size()) TEST_EQUAL(tmp2[0],tmp[0]) TEST_EQUAL(tmp2[1],tmp[1]) MetaInfo mi2(mi); mi2.getKeys(tmp2); TEST_EQUAL(tmp2.size(),tmp.size()) TEST_EQUAL(tmp2[0],tmp[0]) TEST_EQUAL(tmp2[1],tmp[1]) mi2.setValue("a",1); mi2.setValue("d",1); mi2.setValue("x",1); mi2.getKeys(tmp2); tmp.clear(); tmp.push_back("cluster_id"); tmp.push_back("testname"); tmp.push_back("a"); tmp.push_back("d"); tmp.push_back("x"); TEST_EQUAL(tmp2.size(),tmp.size()) TEST_EQUAL(tmp2[0],tmp[0]) TEST_EQUAL(tmp2[1],tmp[1]) TEST_EQUAL(tmp2[2],tmp[2]) TEST_EQUAL(tmp2[3],tmp[3]) TEST_EQUAL(tmp2[4],tmp[4]) END_SECTION START_SECTION((void getKeys(std::vector< UInt > &keys) const)) MetaInfo mi; mi.setValue("label",String("tag")); mi.setValue("icon",String("kreis")); vector<UInt> vec; mi.getKeys(vec); TEST_EQUAL(vec.size(),2) TEST_EQUAL(vec[0],3) TEST_EQUAL(vec[1],4) mi.setValue("a",1); mi.setValue("d",1); mi.setValue("x",1); mi.getKeys(vec); TEST_EQUAL(vec.size(),5) TEST_EQUAL(vec[0],3) TEST_EQUAL(vec[1],4) TEST_EQUAL(vec[2],1025) TEST_EQUAL(vec[3],1026) TEST_EQUAL(vec[4],1027) END_SECTION START_SECTION((bool exists(const String& name) const)) MetaInfo mi4; TEST_EQUAL(mi4.exists("cluster_id"),false) mi4.setValue("cluster_id",4712.1234); TEST_EQUAL(mi4.exists("cluster_id"),true) END_SECTION START_SECTION((bool exists(UInt index) const)) MetaInfo mi4; TEST_EQUAL(mi4.exists(2),false) mi4.setValue("cluster_id",4712.1234); TEST_EQUAL(mi4.exists(2),true) END_SECTION START_SECTION((void clear())) MetaInfo i; TEST_EQUAL(i.empty(),true) i.setValue("label",String("test")); TEST_EQUAL(i.empty(),false) i.clear(); TEST_EQUAL(i.empty(),true) END_SECTION START_SECTION((bool operator== (const MetaInfo& rhs) const)) MetaInfo i,i2; TEST_EQUAL(i==i2,true) TEST_EQUAL(i2==i,true) i.setValue("label",String("test")); TEST_EQUAL(i==i2,false) TEST_EQUAL(i2==i,false) i2.setValue("label",String("test")); TEST_EQUAL(i==i2,true) TEST_EQUAL(i2==i,true) END_SECTION START_SECTION((bool operator!= (const MetaInfo& rhs) const)) MetaInfo i,i2; TEST_EQUAL(i!=i2,false) TEST_EQUAL(i2!=i,false) i.setValue("label",String("test")); TEST_EQUAL(i!=i2,true) TEST_EQUAL(i2!=i,true) i2.setValue("label",String("test")); TEST_EQUAL(i!=i2,false) TEST_EQUAL(i2!=i,false) END_SECTION START_SECTION((MetaInfo & operator+=(const MetaInfo& rhs))) MetaInfo m_new, m_base; m_base.setValue("label", String("old")); m_base.setValue("exists_no_overwrite", 5.2); m_new.setValue("label", String("new")); // will be overwritten m_new.setValue("icon", 4.3); // will be added m_base += m_new; TEST_EQUAL(m_base.getValue("label"), String("new")); TEST_EQUAL(m_base.getValue("icon"), 4.3); TEST_EQUAL(m_base.getValue("exists_no_overwrite"), 5.2); END_SECTION START_SECTION((void removeValue(UInt index))) MetaInfo i,i2; i.setValue(1,String("bla")); TEST_EQUAL(i==i2,false) i.removeValue(1); TEST_EQUAL(i==i2,true) //try if removing a non-existing value works as well i.removeValue(1234); END_SECTION START_SECTION((void removeValue(const String& name))) MetaInfo i,i2; i.setValue("label",String("bla")); TEST_EQUAL(i==i2,false) i.removeValue("label"); TEST_EQUAL(i==i2,true) //try if removing a non-existing value works as well i.removeValue("icon"); END_SECTION START_SECTION((Size size() const)) MetaInfo mi_size; TEST_EQUAL(mi_size.size(), 0) mi_size.setValue("key1", 1); TEST_EQUAL(mi_size.size(), 1) mi_size.setValue("key2", 2); TEST_EQUAL(mi_size.size(), 2) mi_size.removeValue("key1"); TEST_EQUAL(mi_size.size(), 1) mi_size.clear(); TEST_EQUAL(mi_size.size(), 0) END_SECTION START_SECTION((const_iterator begin() const)) MetaInfo mi_iter; TEST_EQUAL(mi_iter.begin() == mi_iter.end(), true) // empty mi_iter.setValue("test_key", 42); TEST_EQUAL(mi_iter.begin() != mi_iter.end(), true) TEST_EQUAL(mi_iter.begin()->second, DataValue(42)) END_SECTION START_SECTION((const_iterator end() const)) NOT_TESTABLE // tested with begin() END_SECTION START_SECTION((const_iterator cbegin() const)) MetaInfo mi_citer; mi_citer.setValue("key", String("value")); auto it = mi_citer.cbegin(); TEST_EQUAL(it->second, DataValue(String("value"))) END_SECTION START_SECTION((const_iterator cend() const)) NOT_TESTABLE // tested with cbegin() END_SECTION START_SECTION((iterator begin())) MetaInfo mi_mut; mi_mut.setValue("mutable_key", 100); auto it = mi_mut.begin(); it->second = DataValue(200); TEST_EQUAL(mi_mut.getValue("mutable_key"), DataValue(200)) END_SECTION START_SECTION((iterator end())) NOT_TESTABLE // tested with mutable begin() END_SECTION START_SECTION([EXTRA] Range-based for loop iteration) MetaInfo mi_range; mi_range.setValue("a", 1); mi_range.setValue("b", 2); mi_range.setValue("c", 3); int count = 0; for (const auto& kv : mi_range) { ++count; TEST_EQUAL(kv.second.valueType() == DataValue::INT_VALUE, true) } TEST_EQUAL(count, 3) END_SECTION START_SECTION([EXTRA] operator+= with empty MetaInfo) MetaInfo m1, m2; m1.setValue("key", 1); // Adding empty to non-empty m1 += m2; TEST_EQUAL(m1.size(), 1) TEST_EQUAL(m1.getValue("key"), DataValue(1)) // Adding non-empty to empty MetaInfo m3; m3 += m1; TEST_EQUAL(m3.size(), 1) TEST_EQUAL(m3.getValue("key"), DataValue(1)) END_SECTION START_SECTION([EXTRA] operator+= with disjoint keys) MetaInfo m1, m2; m1.setValue("a", 1); m1.setValue("c", 3); m2.setValue("b", 2); m2.setValue("d", 4); m1 += m2; TEST_EQUAL(m1.size(), 4) TEST_EQUAL(m1.getValue("a"), DataValue(1)) TEST_EQUAL(m1.getValue("b"), DataValue(2)) TEST_EQUAL(m1.getValue("c"), DataValue(3)) TEST_EQUAL(m1.getValue("d"), DataValue(4)) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TMTSixteenPlexQuantitationMethod_test.cpp
.cpp
8,914
246
// 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/TMTSixteenPlexQuantitationMethod.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/Matrix.h> using namespace OpenMS; using namespace std; START_TEST(TMTSixteenPlexQuantitationMethod, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TMTSixteenPlexQuantitationMethod* ptr = nullptr; TMTSixteenPlexQuantitationMethod* null_ptr = nullptr; START_SECTION(TMTSixteenPlexQuantitationMethod()) { ptr = new TMTSixteenPlexQuantitationMethod(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~TMTSixteenPlexQuantitationMethod()) { delete ptr; } END_SECTION START_SECTION((const String& getMethodName() const )) { TMTSixteenPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getMethodName(), "tmt16plex") } END_SECTION START_SECTION((const IsobaricChannelList& getChannelInformation() const )) { TMTSixteenPlexQuantitationMethod quant_meth; IsobaricQuantitationMethod::IsobaricChannelList channel_list = quant_meth.getChannelInformation(); TEST_EQUAL(channel_list.size(), 16) ABORT_IF(channel_list.size() != 16) // 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, "") TEST_STRING_EQUAL(channel_list[4].description, "") TEST_STRING_EQUAL(channel_list[5].description, "") TEST_STRING_EQUAL(channel_list[6].description, "") TEST_STRING_EQUAL(channel_list[7].description, "") TEST_STRING_EQUAL(channel_list[8].description, "") TEST_STRING_EQUAL(channel_list[9].description, "") TEST_STRING_EQUAL(channel_list[10].description, "") TEST_STRING_EQUAL(channel_list[11].description, "") TEST_STRING_EQUAL(channel_list[12].description, "") TEST_STRING_EQUAL(channel_list[13].description, "") TEST_STRING_EQUAL(channel_list[14].description, "") TEST_STRING_EQUAL(channel_list[15].description, "") // check masses&co TEST_EQUAL(channel_list[0].name, "126") TEST_EQUAL(channel_list[0].id, 0) TEST_EQUAL(channel_list[0].center, 126.127726) TEST_EQUAL(channel_list[1].name, "127N") TEST_EQUAL(channel_list[1].id, 1) TEST_EQUAL(channel_list[1].center, 127.124761) TEST_EQUAL(channel_list[2].name, "127C") TEST_EQUAL(channel_list[2].id, 2) TEST_EQUAL(channel_list[2].center, 127.131081) TEST_EQUAL(channel_list[3].name, "128N") TEST_EQUAL(channel_list[3].id, 3) TEST_EQUAL(channel_list[3].center, 128.128116) TEST_EQUAL(channel_list[4].name, "128C") TEST_EQUAL(channel_list[4].id, 4) TEST_EQUAL(channel_list[4].center, 128.134436) TEST_EQUAL(channel_list[5].name, "129N") TEST_EQUAL(channel_list[5].id, 5) TEST_EQUAL(channel_list[5].center, 129.131471) TEST_EQUAL(channel_list[6].name, "129C") TEST_EQUAL(channel_list[6].id, 6) TEST_EQUAL(channel_list[6].center, 129.137790) TEST_EQUAL(channel_list[7].name, "130N") TEST_EQUAL(channel_list[7].id, 7) TEST_EQUAL(channel_list[7].center, 130.134825) TEST_EQUAL(channel_list[8].name, "130C") TEST_EQUAL(channel_list[8].id, 8) TEST_EQUAL(channel_list[8].center, 130.141145) TEST_EQUAL(channel_list[9].name, "131N") TEST_EQUAL(channel_list[9].id, 9) TEST_EQUAL(channel_list[9].center, 131.138180) TEST_EQUAL(channel_list[10].name, "131C") TEST_EQUAL(channel_list[10].id, 10) TEST_EQUAL(channel_list[10].center, 131.144500) TEST_EQUAL(channel_list[11].name, "132N") TEST_EQUAL(channel_list[11].id, 11) TEST_EQUAL(channel_list[11].center, 132.141535) TEST_EQUAL(channel_list[12].name, "132C") TEST_EQUAL(channel_list[12].id, 12) TEST_EQUAL(channel_list[12].center, 132.147855) TEST_EQUAL(channel_list[13].name, "133N") TEST_EQUAL(channel_list[13].id, 13) TEST_EQUAL(channel_list[13].center, 133.144890) TEST_EQUAL(channel_list[14].name, "133C") TEST_EQUAL(channel_list[14].id, 14) TEST_EQUAL(channel_list[14].center, 133.151210) TEST_EQUAL(channel_list[15].name, "134N") TEST_EQUAL(channel_list[15].id, 15) TEST_EQUAL(channel_list[15].center, 134.148245) for (const auto& channel : channel_list) { TEST_EQUAL(channel.affected_channels.size(), 8) } } END_SECTION START_SECTION((Size getNumberOfChannels() const )) { TMTSixteenPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getNumberOfChannels(), 16) } END_SECTION START_SECTION((virtual Matrix<double> getIsotopeCorrectionMatrix() const )) { double test_matrix[16][16] = {{0.9026, 0.0078, 0.0093, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, {0.0031, 0.8948, 0, 0.0082, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, {0.0909, 0, 0.8981, 0.0065, 0.0147, 0, 0.0013, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, {0.0002, 0.0941, 0.0035, 0.9014, 0, 0.0146, 0, 0.0013, 0, 0, 0, 0, 0, 0, 0, 0, }, {0.0032, 0, 0.0863, 0, 0.9113, 0.0128, 0.0259, 0, 0.0004, 0, 0, 0, 0, 0, 0, 0, }, {0, 0.0033, 0.0001, 0.0813, 0.0034, 0.9025, 0, 0.0241, 0, 0.0003, 0, 0, 0, 0, 0, 0, }, {0, 0, 0.0027, 0, 0.0691, 0, 0.907, 0.0027, 0.031, 0, 0.0008, 0, 0, 0, 0, 0, }, {0, 0, 0, 0.0026, 0, 0.0686, 0.0032, 0.9151, 0, 0.0278, 0, 0.0015, 0, 0, 0, 0, }, {0, 0, 0, 0, 0.0015, 0, 0.0607, 0, 0.9154, 0.0063, 0.039, 0.0001, 0.0011, 0, 0, 0, }, {0, 0, 0, 0, 0, 0.0015, 0.001, 0.0558, 0.0042, 0.9187, 0, 0.0358, 0, 0.0007, 0, 0, }, {0, 0, 0, 0, 0, 0, 0.0009, 0, 0.0482, 0, 0.9194, 0.0072, 0.0455, 0.0001, 0.0022, 0, }, {0, 0, 0, 0, 0, 0, 0, 0.001, 0.0002, 0.0457, 0.0047, 0.9374, 0, 0.0314, 0, 0.003, }, {0, 0, 0, 0, 0, 0, 0, 0, 0.0006, 0, 0.0357, 0, 0.9305, 0.0073, 0.0496, 0.0003, }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0012, 0, 0.018, 0.0043, 0.9262, 0, 0.0549, }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0004, 0, 0.0186, 0, 0.9345, 0.0062, }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.034, 0.0034, 0.9242, } }; Matrix<double> test_Matrix; test_Matrix.setMatrix<double, 16, 16>(test_matrix); TMTSixteenPlexQuantitationMethod quant_meth; // we only check the default matrix here which is an identity matrix // for tmt16plex Matrix<double> m = quant_meth.getIsotopeCorrectionMatrix(); TEST_EQUAL(m.rows(), 16) TEST_EQUAL(m.cols(), 16) ABORT_IF(m.rows() != 16) ABORT_IF(m.cols() != 16) for (Size i = 0; i < m.rows(); ++i) { for (Size j = 0; j < m.cols(); ++j) { TEST_REAL_SIMILAR(m(i,j), test_Matrix(i,j)) } } } END_SECTION START_SECTION((Size getReferenceChannel() const )) { TMTSixteenPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getReferenceChannel(), 0) Param p; p.setValue("reference_channel","128N"); quant_meth.setParameters(p); TEST_EQUAL(quant_meth.getReferenceChannel(), 3) } END_SECTION START_SECTION((TMTSixteenPlexQuantitationMethod(const TMTSixteenPlexQuantitationMethod &other))) { TMTSixteenPlexQuantitationMethod qm; Param p = qm.getParameters(); p.setValue("channel_127N_description", "new_description"); p.setValue("reference_channel", "129C"); qm.setParameters(p); TMTSixteenPlexQuantitationMethod qm2(qm); IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation(); TEST_STRING_EQUAL(channel_list[1].description, "new_description") TEST_EQUAL(qm2.getReferenceChannel(), 6) } END_SECTION START_SECTION((TMTSixteenPlexQuantitationMethod& operator=(const TMTSixteenPlexQuantitationMethod &rhs))) { TMTSixteenPlexQuantitationMethod qm; Param p = qm.getParameters(); p.setValue("channel_127N_description", "new_description"); p.setValue("reference_channel", "130C"); qm.setParameters(p); TMTSixteenPlexQuantitationMethod qm2 = qm; IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation(); TEST_STRING_EQUAL(channel_list[1].description, "new_description") TEST_EQUAL(qm2.getReferenceChannel(), 8) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeakPickerHiRes_test.cpp
.cpp
18,650
553
// 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/CONCEPT/Constants.h> #include <OpenMS/FORMAT/MzMLFile.h> /////////////////////////// #include <OpenMS/PROCESSING/CENTROIDING/PeakPickerHiRes.h> /////////////////////////// using namespace OpenMS; using namespace std; //uncomment if the reference files should be re-written //(only do this if you are sure that the PeakPickerHiRes is working correctly) //#define WRITE_REF_FILES START_TEST(PeakPickerHiRes, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeakPickerHiRes* ptr = nullptr; PeakPickerHiRes* nullPointer = nullptr; START_SECTION((PeakPickerHiRes())) ptr = new PeakPickerHiRes(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~PeakPickerHiRes())) delete ptr; END_SECTION PeakPickerHiRes pp_hires; Param param; PeakMap input, output; ///////////////////////// // ORBITRAP data tests // ///////////////////////// // load Orbitrap input data MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("PeakPickerHiRes_orbitrap.mzML"),input); ///////////////////////////////////////// // ORBITRAP test 1 (signal-to-noise 1) // ///////////////////////////////////////// MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("PeakPickerHiRes_orbitrap_sn1_out.mzML"),output); //set data type (this is not stored correctly in mzData) for (Size scan_idx = 0; scan_idx < output.size(); ++scan_idx) { output[scan_idx].setType(SpectrumSettings::SpectrumType::CENTROID); } // PeakPickerHiRes config param.setValue("signal_to_noise", 1.0); pp_hires.setParameters(param); START_SECTION((template <typename PeakType> void pick(const MSSpectrum& input, MSSpectrum& output) const)) { // test on dummy spectrum { PeakPickerHiRes pp_hires; Param param; param.setValue("signal_to_noise", 0.0); pp_hires.setParameters(param); MSSpectrum input, output; input.emplace_back(100.0, 200); input.emplace_back(100.01, 250); input.emplace_back(100.02, 450); input.emplace_back(100.03, 250); input.emplace_back(100.04, 200); pp_hires.pick(input, output); TEST_EQUAL(output.size(), 1) TEST_REAL_SIMILAR(output[0].getIntensity(), 450) TEST_REAL_SIMILAR(output[0].getMZ(), 100.02) } // test on dummy ion mobility spectrum { PeakPickerHiRes pp_hires; Param param; param.setValue("signal_to_noise", 0.0); pp_hires.setParameters(param); MSSpectrum input, output; input.emplace_back(100.0, 200); input.emplace_back(100.01, 250); input.emplace_back(100.02, 450); input.emplace_back(100.03, 250); input.emplace_back(100.04, 200); input.getFloatDataArrays().resize(1); input.getFloatDataArrays()[0].setName(Constants::UserParam::ION_MOBILITY); input.getFloatDataArrays()[0].push_back(100.0); input.getFloatDataArrays()[0].push_back(150.0); input.getFloatDataArrays()[0].push_back(150.0); input.getFloatDataArrays()[0].push_back(150.0); input.getFloatDataArrays()[0].push_back(100.0); pp_hires.pick(input, output); TEST_EQUAL(output.size(), 1) TEST_REAL_SIMILAR(output[0].getIntensity(), 450) TEST_REAL_SIMILAR(output[0].getMZ(), 100.02) TEST_EQUAL(output.getFloatDataArrays().size(), 1) TEST_EQUAL(output.getFloatDataArrays()[0].getName(), "Ion Mobility") TEST_REAL_SIMILAR(output.getFloatDataArrays()[0][0], 135.1852) // weighted average // TEST_REAL_SIMILAR(output.getFloatDataArrays()[0][0], (100*200 + 250*150 + 450*150 + 250*150 + 100*200) / (200 + 250 + 450 + 250 + 200) ) // different im array name input.getFloatDataArrays()[0].setName("raw inverse reduced ion mobility array"); pp_hires.pick(input, output); TEST_EQUAL(output.size(), 1) TEST_EQUAL(output.getFloatDataArrays().size(), 1) TEST_EQUAL(output.getFloatDataArrays()[0].getName(), "raw inverse reduced ion mobility array") TEST_REAL_SIMILAR(output.getFloatDataArrays()[0][0], 135.1852) } // Test on real data { MSSpectrum tmp_spec; pp_hires.pick(input[0], tmp_spec); #ifdef WRITE_REF_FILES PeakMap tmp_exp = input; for (Size scan_idx = 0; scan_idx < tmp_exp.size(); ++scan_idx) { pp_hires.pick(input[scan_idx],tmp_spec); tmp_exp[scan_idx] = tmp_spec; } MzMLFile().store("./PeakPickerHiRes_orbitrap_sn1_out.mzML", tmp_exp); #endif for (Size peak_idx = 0; peak_idx < tmp_spec.size(); ++peak_idx) { TEST_REAL_SIMILAR(tmp_spec[peak_idx].getMZ(), output[0][peak_idx].getMZ()) TEST_REAL_SIMILAR(tmp_spec[peak_idx].getIntensity(), output[0][peak_idx].getIntensity()) } } } END_SECTION START_SECTION((template <typename PeakType> void pick(const MSSpectrum& input, MSSpectrum& output, std::vector<PeakBoundary>& boundaries, bool check_spacings = true) const)) { MSSpectrum tmp_spec; std::vector<PeakPickerHiRes::PeakBoundary> tmp_boundaries; pp_hires.pick(input[0], tmp_spec, tmp_boundaries); #ifdef WRITE_REF_FILES PeakMap tmp_exp = input; for (Size scan_idx = 0; scan_idx < tmp_exp.size(); ++scan_idx) { pp_hires.pick(input[scan_idx],tmp_spec); tmp_exp[scan_idx] = tmp_spec; } MzMLFile().store("./PeakPickerHiRes_orbitrap_sn1_out.mzML", tmp_exp); #endif for (Size peak_idx = 0; peak_idx < tmp_spec.size(); ++peak_idx) { TEST_REAL_SIMILAR(tmp_spec[peak_idx].getMZ(), output[0][peak_idx].getMZ()) TEST_REAL_SIMILAR(tmp_spec[peak_idx].getIntensity(), output[0][peak_idx].getIntensity()) } TEST_REAL_SIMILAR(tmp_boundaries[25].mz_min, 359.728698730469) TEST_REAL_SIMILAR(tmp_boundaries[25].mz_max, 359.736419677734) TEST_REAL_SIMILAR(tmp_boundaries[26].mz_min, 360.155609130859) TEST_REAL_SIMILAR(tmp_boundaries[26].mz_max, 360.173675537109) } END_SECTION START_SECTION([EXTRA](template <typename PeakType> void pickExperiment(const MSExperiment<PeakType>& input, MSExperiment<PeakType>& output))) // does the same as pick method for spectra NOT_TESTABLE END_SECTION START_SECTION([EXTRA](template <typename PeakType> void pickExperiment(const MSExperiment<PeakType>& input, MSExperiment<PeakType>& output, std::vector<std::vector<PeakBoundary> >& boundaries_spec, std::vector<std::vector<PeakBoundary> >& boundaries_chrom))) // does the same as pick method for spectra NOT_TESTABLE END_SECTION START_SECTION((template <typename PeakType, typename ChromatogramPeakT> void pickExperiment(const MSExperiment<PeakType, ChromatogramPeakT>& input, MSExperiment<PeakType, ChromatogramPeakT>& output) const)) { PeakMap tmp_exp; pp_hires.pickExperiment(input,tmp_exp); for (Size scan_idx = 0; scan_idx < tmp_exp.size(); ++scan_idx) { for (Size peak_idx = 0; peak_idx < tmp_exp[scan_idx].size(); ++peak_idx) { TEST_REAL_SIMILAR(tmp_exp[scan_idx][peak_idx].getMZ(), output[scan_idx][peak_idx].getMZ()) TEST_REAL_SIMILAR(tmp_exp[scan_idx][peak_idx].getIntensity(), output[scan_idx][peak_idx].getIntensity()) } } } END_SECTION output.clear(true); /////////////////////////////////////////// //// ORBITRAP test 2 (signal-to-noise 4) // /////////////////////////////////////////// MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("PeakPickerHiRes_orbitrap_sn4_out.mzML"),output); //set data type (this is not stored correctly in mzData) for (Size scan_idx = 0; scan_idx < output.size(); ++scan_idx) { output[scan_idx].setType(SpectrumSettings::SpectrumType::CENTROID); } //set up PeakPicker param.setValue("signal_to_noise", 4.0); pp_hires.setParameters(param); START_SECTION([EXTRA](template <typename PeakType> void pick(const MSSpectrum& input, MSSpectrum& output))) { MSSpectrum tmp_spec; pp_hires.pick(input[0],tmp_spec); #ifdef WRITE_REF_FILES PeakMap tmp_exp = input; for (Size scan_idx = 0; scan_idx < tmp_exp.size(); ++scan_idx) { pp_hires.pick(input[scan_idx],tmp_spec); tmp_exp[scan_idx] = tmp_spec; } MzMLFile().store("./PeakPickerHiRes_orbitrap_sn4_out.mzML", tmp_exp); #endif for (Size peak_idx = 0; peak_idx < tmp_spec.size(); ++peak_idx) { TEST_REAL_SIMILAR(tmp_spec[peak_idx].getMZ(), output[0][peak_idx].getMZ()) TEST_REAL_SIMILAR(tmp_spec[peak_idx].getIntensity(), output[0][peak_idx].getIntensity()) } } END_SECTION START_SECTION([EXTRA](template <typename PeakType> void pickExperiment(const MSExperiment<PeakType>& input, MSExperiment<PeakType>& output))) { PeakMap tmp_exp; pp_hires.pickExperiment(input,tmp_exp); for (Size scan_idx = 0; scan_idx < tmp_exp.size(); ++scan_idx) { for (Size peak_idx = 0; peak_idx < tmp_exp[scan_idx].size(); ++peak_idx) { TEST_REAL_SIMILAR(tmp_exp[scan_idx][peak_idx].getMZ(), output[scan_idx][peak_idx].getMZ()) TEST_REAL_SIMILAR(tmp_exp[scan_idx][peak_idx].getIntensity(), output[scan_idx][peak_idx].getIntensity()) } } } END_SECTION output.clear(true); input.clear(true); // /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////// ///////////////////////// // FTICR-MS data tests // ///////////////////////// // load FTMS input data MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("PeakPickerHiRes_ftms.mzML"),input); //////////////////////////////////////////////// //// FTICR-MS test 1 (signal-to-noise 1) // //////////////////////////////////////////////// MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("PeakPickerHiRes_ftms_sn1_out.mzML"),output); //set data type (this is not stored correctly in mzML) for (Size scan_idx = 0; scan_idx < output.size(); ++scan_idx) { output[scan_idx].setType(SpectrumSettings::SpectrumType::CENTROID); } // PeakPickerHiRes config param.setValue("signal_to_noise", 1.0); pp_hires.setParameters(param); START_SECTION([EXTRA](template <typename PeakType> void pick(const MSSpectrum& input, MSSpectrum& output))) { MSSpectrum tmp_spec; pp_hires.pick(input[0],tmp_spec); #ifdef WRITE_REF_FILES PeakMap tmp_exp = input; for (Size scan_idx = 0; scan_idx < tmp_exp.size(); ++scan_idx) { pp_hires.pick(input[scan_idx],tmp_spec); tmp_exp[scan_idx] = tmp_spec; } MzMLFile().store("./PeakPickerHiRes_ftms_sn1_out.mzML", tmp_exp); #endif for (Size peak_idx = 0; peak_idx < tmp_spec.size(); ++peak_idx) { TEST_REAL_SIMILAR(tmp_spec[peak_idx].getMZ(), output[0][peak_idx].getMZ()) TEST_REAL_SIMILAR(tmp_spec[peak_idx].getIntensity(), output[0][peak_idx].getIntensity()) } } END_SECTION output.clear(true); ///////////////////////////////////////// // FTICR-MS test 2 (signal-to-noise 4) // ///////////////////////////////////////// MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("PeakPickerHiRes_ftms_sn4_out.mzML"),output); //set data type (this is not stored correctly in mzML) for (Size scan_idx = 0; scan_idx < output.size(); ++scan_idx) { output[scan_idx].setType(SpectrumSettings::SpectrumType::CENTROID); } //set up PeakPicker param.setValue("signal_to_noise", 4.0); pp_hires.setParameters(param); START_SECTION([EXTRA](template <typename PeakType> void pick(const MSSpectrum& input, MSSpectrum& output))) { MSSpectrum tmp_spec; pp_hires.pick(input[0],tmp_spec); #ifdef WRITE_REF_FILES PeakMap tmp_exp = input; for (Size scan_idx = 0; scan_idx < tmp_exp.size(); ++scan_idx) { pp_hires.pick(input[scan_idx],tmp_spec); tmp_exp[scan_idx] = tmp_spec; } MzMLFile().store("./PeakPickerHiRes_ftms_sn4_out.mzML", tmp_exp); #endif for (Size peak_idx = 0; peak_idx < tmp_spec.size(); ++peak_idx) { TEST_REAL_SIMILAR(tmp_spec[peak_idx].getMZ(), output[0][peak_idx].getMZ()) TEST_REAL_SIMILAR(tmp_spec[peak_idx].getIntensity(), output[0][peak_idx].getIntensity()) } } END_SECTION START_SECTION([EXTRA](template <typename PeakType> void pickExperiment(const MSExperiment<PeakType>& input, MSExperiment<PeakType>& output))) { PeakMap tmp_exp; pp_hires.pickExperiment(input,tmp_exp); for (Size scan_idx = 0; scan_idx < tmp_exp.size(); ++scan_idx) { for (Size peak_idx = 0; peak_idx < tmp_exp[scan_idx].size(); ++peak_idx) { TEST_REAL_SIMILAR(tmp_exp[scan_idx][peak_idx].getMZ(), output[scan_idx][peak_idx].getMZ()) TEST_REAL_SIMILAR(tmp_exp[scan_idx][peak_idx].getIntensity(), output[scan_idx][peak_idx].getIntensity()) } } } END_SECTION output.clear(true); ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION([EXTRA] test spectrum level selection) { PeakMap inSpecSelection; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("PeakPickerHiRes_spectrum_selection.mzML"), inSpecSelection); Param pp_hires_param; PeakPickerHiRes pp_spec_select; // pick only ms2 PeakMap outMs2Only; pp_hires_param.setValue("ms_levels", ListUtils::create<Int>("2")); pp_spec_select.setParameters(pp_hires_param); pp_spec_select.pickExperiment(inSpecSelection, outMs2Only); ABORT_IF(inSpecSelection.size() != outMs2Only.size()) for(Size i = 0; i < outMs2Only.size(); ++i) { if (outMs2Only[i].getMSLevel() == 2) { TEST_NOT_EQUAL(inSpecSelection[i], outMs2Only[i]) } else { TEST_EQUAL(inSpecSelection[i], outMs2Only[i]) } } // pick only ms1 PeakMap outMs1Only; pp_hires_param.setValue("ms_levels", ListUtils::create<Int>("1")); pp_spec_select.setParameters(pp_hires_param); pp_spec_select.pickExperiment(inSpecSelection, outMs1Only); ABORT_IF(inSpecSelection.size() != outMs1Only.size()) for(Size i = 0; i < outMs2Only.size(); ++i) { if (outMs2Only[i].getMSLevel() == 1) { TEST_NOT_EQUAL(inSpecSelection[i], outMs1Only[i]) } else { TEST_EQUAL(inSpecSelection[i], outMs1Only[i]) } } // pick ms1 and ms2 PeakMap outMs1And2; pp_hires_param.setValue("ms_levels", ListUtils::create<Int>("1,2")); pp_spec_select.setParameters(pp_hires_param); pp_spec_select.pickExperiment(inSpecSelection, outMs1And2); ABORT_IF(inSpecSelection.size() != outMs2Only.size()) for(Size i = 0; i < outMs2Only.size(); ++i) { if (outMs1And2[i].getMSLevel() == 2 || outMs1And2[i].getMSLevel() == 1) { TEST_NOT_EQUAL(inSpecSelection[i], outMs1And2[i]) } } } END_SECTION ////////////////////////////////////////////// // check peak boundaries on simulation data // ////////////////////////////////////////////// // load input data MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("PeakPickerHiRes_simulation.mzML"),input); //set params param.setValue("signal_to_noise", 0.0); param.setValue("missing", 1); param.setValue("spacing_difference_gap", 4.0); pp_hires.setParameters(param); START_SECTION(void pick(const MSSpectrum& input, MSSpectrum& output, std::vector<PeakBoundary>& boundaries, bool check_spacings = true) const) { PeakMap tmp_picked; std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > tmp_boundaries_s; // peak boundaries for spectra std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > tmp_boundaries_c; // peak boundaries for chromatograms pp_hires.pickExperiment(input, tmp_picked, tmp_boundaries_s, tmp_boundaries_c); TEST_EQUAL(tmp_picked[0].size(), 167); MSSpectrum::Iterator it_mz = tmp_picked.begin()->begin(); vector<PeakPickerHiRes::PeakBoundary>::const_iterator it_mz_boundary = tmp_boundaries_s.begin()->begin(); it_mz += 146; it_mz_boundary += 146; TEST_REAL_SIMILAR(it_mz->getMZ(),1141.57188829383); TEST_REAL_SIMILAR((*it_mz_boundary).mz_min,1141.51216791402); TEST_REAL_SIMILAR((*it_mz_boundary).mz_max,1141.63481354941); it_mz += 2; it_mz_boundary += 2; TEST_REAL_SIMILAR(it_mz->getMZ(),1142.57196823237); TEST_REAL_SIMILAR((*it_mz_boundary).mz_min,1142.50968574851); TEST_REAL_SIMILAR((*it_mz_boundary).mz_max,1142.6323313839); it_mz += 10; it_mz_boundary += 10; TEST_REAL_SIMILAR(it_mz->getMZ(),1178.08692219102); TEST_REAL_SIMILAR((*it_mz_boundary).mz_min,1178.02013862689); TEST_REAL_SIMILAR((*it_mz_boundary).mz_max,1178.14847787348); it_mz += 1; it_mz_boundary += 1; TEST_REAL_SIMILAR(it_mz->getMZ(),1178.58906411531); TEST_REAL_SIMILAR((*it_mz_boundary).mz_min,1178.5249396635); TEST_REAL_SIMILAR((*it_mz_boundary).mz_max,1178.6532789101); } END_SECTION input.clear(true); output.clear(true); //////////////////////////////////////////// // check peak boundaries on orbitrap data // //////////////////////////////////////////// // load input data MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("PeakPickerHiRes_orbitrap.mzML"),input); //set params param.setValue("signal_to_noise", 0.0); param.setValue("missing", 1); param.setValue("spacing_difference_gap", 4.0); pp_hires.setParameters(param); START_SECTION(void pick(const MSSpectrum& input, MSSpectrum& output, std::vector<PeakBoundary>& boundaries, bool check_spacings = true) const) { PeakMap tmp_picked; std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > tmp_boundaries_s; // peak boundaries for spectra std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > tmp_boundaries_c; // peak boundaries for chromatograms pp_hires.pickExperiment(input, tmp_picked, tmp_boundaries_s, tmp_boundaries_c); TEST_EQUAL(tmp_picked[0].size(), 82); MSSpectrum::Iterator it_mz = tmp_picked.begin()->begin(); vector<PeakPickerHiRes::PeakBoundary>::const_iterator it_mz_boundary = tmp_boundaries_s.begin()->begin(); it_mz += 14; it_mz_boundary += 14; TEST_REAL_SIMILAR(it_mz->getMZ(),355.070081088692); TEST_REAL_SIMILAR((*it_mz_boundary).mz_min,355.064544677734); TEST_REAL_SIMILAR((*it_mz_boundary).mz_max,355.078430175781); it_mz += 23; it_mz_boundary += 23; TEST_REAL_SIMILAR(it_mz->getMZ(),362.848715607077); TEST_REAL_SIMILAR((*it_mz_boundary).mz_min,362.844085693359); TEST_REAL_SIMILAR((*it_mz_boundary).mz_max,362.851928710938); it_mz += 17; it_mz_boundary += 17; TEST_REAL_SIMILAR(it_mz->getMZ(),370.210756298155); TEST_REAL_SIMILAR((*it_mz_boundary).mz_min,370.205871582031); TEST_REAL_SIMILAR((*it_mz_boundary).mz_max,370.215301513672); // Same as min of next peak. it_mz += 1; it_mz_boundary += 1; TEST_REAL_SIMILAR(it_mz->getMZ(),370.219596356153); TEST_REAL_SIMILAR((*it_mz_boundary).mz_min,370.215301513672); // Same as max of previous peak. TEST_REAL_SIMILAR((*it_mz_boundary).mz_max,370.223358154297); } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PoseClusteringAffineSuperimposer_test.cpp
.cpp
9,706
304
// 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, Clemens Groepl $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/KERNEL/StandardTypes.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/PoseClusteringAffineSuperimposer.h> /////////////////////////// #include <OpenMS/KERNEL/Feature.h> using namespace OpenMS; using namespace std; typedef DPosition <2> PositionType; START_TEST(PoseClusteringAffineSuperimposer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PoseClusteringAffineSuperimposer* ptr = nullptr; PoseClusteringAffineSuperimposer* nullPointer = nullptr; START_SECTION((PoseClusteringAffineSuperimposer())) { ptr = new PoseClusteringAffineSuperimposer(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((virtual ~PoseClusteringAffineSuperimposer())) { 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(1.4,1.02); PositionType pos4(5.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)); Param parameters; parameters.setValue(String("scaling_bucket_size"), 0.01); parameters.setValue(String("shift_bucket_size"), 0.1); // If hashing goes wrong, get debug output with the following: // parameters.setValue(String("dump_buckets"),"pcast_buckets"); // parameters.setValue(String("dump_pairs"),"pcast_pairs"); TransformationDescription transformation; PoseClusteringAffineSuperimposer pcat; pcat.setParameters(parameters); // That's a precondition for run()! Now even documented :-) input[0].updateRanges(); input[1].updateRanges(); pcat.run(input[0], input[1], transformation); TEST_STRING_EQUAL(transformation.getModelType(), "linear") parameters = transformation.getModelParameters(); TEST_EQUAL(parameters.size(), 2) TEST_REAL_SIMILAR(parameters.getValue("slope"), 1.0) TEST_REAL_SIMILAR(parameters.getValue("intercept"), -0.4) } END_SECTION START_SECTION((virtual void run(const std::vector<Peak2D> & map_model, const std::vector<Peak2D> & map_scene, TransformationDescription& transformation))) { std::vector<Peak2D> map_model, map_scene; Peak2D p1; p1.setRT(1); p1.setMZ(1); p1.setIntensity(100.0f); Peak2D p2; p2.setRT(5); p2.setMZ(5); p2.setIntensity(100.0f); map_model.push_back(p1); map_model.push_back(p2); Peak2D p3; p3.setRT(1.4); p3.setMZ(1.02); p3.setIntensity(100.0f); Peak2D p4; p4.setRT(5.4); p4.setMZ(5.02); p4.setIntensity(100.0f); map_scene.push_back(p3); map_scene.push_back(p4); Param parameters; parameters.setValue(String("scaling_bucket_size"), 0.01); parameters.setValue(String("shift_bucket_size"), 0.1); // If hashing goes wrong, get debug output with the following: // parameters.setValue(String("dump_buckets"),"pcast_buckets"); // parameters.setValue(String("dump_pairs"),"pcast_pairs"); TransformationDescription transformation; PoseClusteringAffineSuperimposer pcat; pcat.setParameters(parameters); pcat.run(map_model, map_scene, transformation); TEST_STRING_EQUAL(transformation.getModelType(), "linear") parameters = transformation.getModelParameters(); TEST_EQUAL(parameters.size(), 2) TEST_REAL_SIMILAR(parameters.getValue("slope"), 1.0) TEST_REAL_SIMILAR(parameters.getValue("intercept"), -0.4) } END_SECTION START_SECTION(([EXTRA]virtual void run(const std::vector<Peak2D> & map_model, const std::vector<Peak2D> & map_scene, TransformationDescription& transformation))) { std::vector<Peak2D> map_model, map_scene; // map1_rt = double map1_rt[] = {1.0, 5.0}; double map2_rt[] = {1.4, 5.4}; double map1_mz[] = {1.0 , 5.0 }; double map2_mz[] = {1.02, 5.02}; double map1_int[] = {100, 100}; double map2_int[] = {100, 100}; for (Size i = 0; i < 2; i++) { Peak2D p; p.setRT(map1_rt[i]); p.setMZ(map1_mz[i]); p.setIntensity(map1_int[i]); map_model.push_back(p); } for (Size i = 0; i < 2; i++) { Peak2D p; p.setRT(map2_rt[i]); p.setMZ(map2_mz[i]); p.setIntensity(map2_int[i]); map_scene.push_back(p); } Param parameters; parameters.setValue(String("scaling_bucket_size"), 0.01); parameters.setValue(String("shift_bucket_size"), 0.1); // If hashing goes wrong, get debug output with the following: // parameters.setValue(String("dump_buckets"),"pcast_buckets"); // parameters.setValue(String("dump_pairs"),"pcast_pairs"); TransformationDescription transformation; PoseClusteringAffineSuperimposer pcat; pcat.setParameters(parameters); pcat.run(map_model, map_scene, transformation); TEST_STRING_EQUAL(transformation.getModelType(), "linear") parameters = transformation.getModelParameters(); TEST_EQUAL(parameters.size(), 2) TEST_REAL_SIMILAR(parameters.getValue("slope"), 1.0) TEST_REAL_SIMILAR(parameters.getValue("intercept"), -0.4) } END_SECTION START_SECTION(([EXTRA]virtual void run(const std::vector<Peak2D> & map_model, const std::vector<Peak2D> & map_scene, TransformationDescription& transformation))) { std::vector<Peak2D> map_model, map_scene; // add another point at 5.2 -> 5.8 RT (and add some chaff in the middle) double map1_rt[] = {1.0, 5.0, 1.3, 2.2, 5.2}; double map2_rt[] = {1.4, 5.4, 4.4, 4.4, 5.8}; double map1_mz[] = {1.0 , 5.0 , 800, 900, 5.0 }; double map2_mz[] = {1.02, 5.02, 800, 900, 5.02}; double map1_int[] = {100, 100, 41, 20, 50}; double map2_int[] = {100, 100, 40, 20, 50}; for (Size i = 0; i < 5; i++) { Peak2D p; p.setRT(map1_rt[i]); p.setMZ(map1_mz[i]); p.setIntensity(map1_int[i]); map_model.push_back(p); } for (Size i = 0; i < 5; i++) { Peak2D p; p.setRT(map2_rt[i]); p.setMZ(map2_mz[i]); p.setIntensity(map2_int[i]); map_scene.push_back(p); } // make sure vector is not really sorted std::reverse(map_model.begin(), map_model.end() ); std::reverse(map_scene.begin(), map_scene.end() ); // using 2 points { Param parameters; parameters.setValue(String("scaling_bucket_size"), 0.01); parameters.setValue(String("shift_bucket_size"), 0.1); parameters.setValue(String("num_used_points"), 2); // only use first two points -> same results as before expected TransformationDescription transformation; PoseClusteringAffineSuperimposer pcat; pcat.setParameters(parameters); pcat.run(map_model, map_scene, transformation); TEST_STRING_EQUAL(transformation.getModelType(), "linear") parameters = transformation.getModelParameters(); TEST_EQUAL(parameters.size(), 2) TEST_REAL_SIMILAR(parameters.getValue("slope"), 1.0) TEST_REAL_SIMILAR(parameters.getValue("intercept"), -0.4) } // using 3 points { Param parameters; parameters.setValue(String("scaling_bucket_size"), 0.01); parameters.setValue(String("shift_bucket_size"), 0.1); parameters.setValue(String("num_used_points"), 3); // only use first three points -> different results as before expected TransformationDescription transformation; PoseClusteringAffineSuperimposer pcat; pcat.setParameters(parameters); pcat.run(map_model, map_scene, transformation); TEST_STRING_EQUAL(transformation.getModelType(), "linear") parameters = transformation.getModelParameters(); TEST_EQUAL(parameters.size(), 2) TEST_REAL_SIMILAR(parameters.getValue("slope"), 0.977273) // slope should be less than before TEST_REAL_SIMILAR(parameters.getValue("intercept"), -0.368182) // intercept should be higher than before } // what happens if we set the wrong parameters? { Param parameters; parameters.setValue(String("scaling_bucket_size"), 0.01); parameters.setValue(String("shift_bucket_size"), 0.1); parameters.setValue(String("num_used_points"), 3); // only use first three points -> different results as before expected parameters.setValue(String("max_shift"), 0.2); parameters.setValue(String("max_scaling"), 1.001); TransformationDescription transformation; PoseClusteringAffineSuperimposer pcat; pcat.setParameters(parameters); pcat.run(map_model, map_scene, transformation); // quite easy: we get the wrong results! // TODO: don't let this happen, so easy to prevent! TEST_STRING_EQUAL(transformation.getModelType(), "linear") parameters = transformation.getModelParameters(); TEST_EQUAL(parameters.size(), 2) TEST_REAL_SIMILAR(parameters.getValue("slope"), 1.0) // TODO this is completely wrong TEST_REAL_SIMILAR(parameters.getValue("intercept"), -0.4) // TODO this is completely wrong } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/OMSFile_test.cpp
.cpp
7,898
226
// 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/CONCEPT/FuzzyStringComparator.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/METADATA/ID/IdentificationDataConverter.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/FORMAT/OMSFile.h> #include <OpenMS/SYSTEM/File.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(OMSFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// String oms_tmp; IdentificationData ids; START_SECTION(void store(const String& filename, const IdentificationData& id_data)) { vector<ProteinIdentification> proteins_in; PeptideIdentificationList peptides_in; IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IdXMLFile_whole.idXML"), proteins_in, peptides_in); // IdentificationData doesn't allow score types with the same name, but different orientations: peptides_in[0].setHigherScoreBetter(true); IdentificationDataConverter::importIDs(ids, proteins_in, peptides_in); // add an adduct (not supported by idXML): AdductInfo adduct("Cl-", EmpiricalFormula("Cl"), -1); auto adduct_ref = ids.registerAdduct(adduct); IdentificationData::ObservationMatch match = *ids.getObservationMatches().begin(); match.adduct_opt = adduct_ref; ids.registerObservationMatch(match); NEW_TMP_FILE(oms_tmp); OMSFile().store(oms_tmp, ids); TEST_EQUAL(File::empty(oms_tmp), false); } END_SECTION START_SECTION(void load(const String& filename, IdentificationData& id_data)) { IdentificationData out; OMSFile().load(oms_tmp, out); TEST_EQUAL(ids.getInputFiles().size(), out.getInputFiles().size()); TEST_EQUAL(ids.getScoreTypes().size(), out.getScoreTypes().size()); TEST_EQUAL(ids.getProcessingSoftwares().size(), out.getProcessingSoftwares().size()); TEST_EQUAL(ids.getDBSearchParams().size(), out.getDBSearchParams().size()); TEST_EQUAL(ids.getProcessingSteps().size(), out.getProcessingSteps().size()); TEST_EQUAL(ids.getObservations().size(), out.getObservations().size()); TEST_EQUAL(ids.getParentSequences().size(), out.getParentSequences().size()); TEST_EQUAL(ids.getParentGroupSets().size(), out.getParentGroupSets().size()); TEST_EQUAL(ids.getIdentifiedPeptides().size(), out.getIdentifiedPeptides().size()); TEST_EQUAL(ids.getIdentifiedOligos().size(), out.getIdentifiedOligos().size()); TEST_EQUAL(ids.getIdentifiedCompounds().size(), out.getIdentifiedCompounds().size()); TEST_EQUAL(ids.getAdducts().size(), out.getAdducts().size()); TEST_EQUAL(ids.getObservationMatches().size(), out.getObservationMatches().size()); auto it1 = ids.getObservationMatches().begin(); auto it2 = out.getObservationMatches().begin(); auto adduct_it = out.getObservationMatches().end(); for (; (it1 != ids.getObservationMatches().end()) && (it2 != out.getObservationMatches().end()); ++it1, ++it2) { TEST_EQUAL(it1->steps_and_scores.size(), it2->steps_and_scores.size()); if (it2->adduct_opt) adduct_it = it2; // found PSM with adduct } // check PSM with adduct: TEST_EQUAL(adduct_it != out.getObservationMatches().end(), true); ABORT_IF(adduct_it == out.getObservationMatches().end()); TEST_EQUAL(adduct_it->observation_ref->data_id, ids.getObservationMatches().begin()->observation_ref->data_id); TEST_EQUAL(adduct_it->identified_molecule_var.toString(), ids.getObservationMatches().begin()->identified_molecule_var.toString()); TEST_EQUAL((*adduct_it->adduct_opt)->getName(), "Cl-"); } END_SECTION START_SECTION(void store(const String& filename, const FeatureMap& features)) { FeatureMap features; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFileOMStest_1.featureXML"), features); // protein and peptide IDs use same score type (name) with different orientations; // IdentificationData doesn't allow this, so change it here: for (auto& run : features.getProteinIdentifications()) { run.setScoreType(run.getScoreType() + "_protein"); } IdentificationDataConverter::importFeatureIDs(features); NEW_TMP_FILE(oms_tmp); OMSFile().store(oms_tmp, features); TEST_EQUAL(File::empty(oms_tmp), false); } END_SECTION START_SECTION(void load(const String& filename, FeatureMap& features)) { FeatureMap features; OMSFile().load(oms_tmp, features); TEST_EQUAL(features.size(), 2); TEST_EQUAL(features.at(0).getSubordinates().size(), 2); IdentificationDataConverter::exportFeatureIDs(features); // sort for reproducibility auto& proteins = features.getProteinIdentifications(); for (auto& protein : proteins) { protein.sort(); } auto& un_peptides = features.getUnassignedPeptideIdentifications(); for (auto& un_pep : un_peptides) { un_pep.sort(); } //features.setProteinIdentifications(proteins); //features.setUnassignedPeptideIdentifications(un_peptides); features.sortByPosition(); String fxml_tmp; NEW_TMP_FILE(fxml_tmp); FeatureXMLFile().store(fxml_tmp, features); FuzzyStringComparator fsc; fsc.setAcceptableRelative(1.001); fsc.setAcceptableAbsolute(1); StringList sl; sl.push_back("xml-stylesheet"); sl.push_back("UnassignedPeptideIdentification"); fsc.setWhitelist(sl); TEST_EQUAL(fsc.compareFiles(fxml_tmp, OPENMS_GET_TEST_DATA_PATH("OMSFile_test_2.featureXML")), true); } END_SECTION START_SECTION(void store(const String& filename, const ConsensusMap& consensus)) { ConsensusMap consensus; ConsensusXMLFile().load(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_1.consensusXML"), consensus); // protein and peptide IDs use same score type (name) with different orientations; // IdentificationData doesn't allow this, so change it here: for (auto& run : consensus.getProteinIdentifications()) { run.setScoreType(run.getScoreType() + "_protein"); } IdentificationDataConverter::importConsensusIDs(consensus); NEW_TMP_FILE(oms_tmp); OMSFile().store(oms_tmp, consensus); TEST_EQUAL(File::empty(oms_tmp), false); } END_SECTION START_SECTION(void load(const String& filename, ConsensusMap& consensus)) { ConsensusMap consensus; OMSFile().load(oms_tmp, consensus); TEST_EQUAL(consensus.size(), 6); TEST_EQUAL(consensus.at(0).getFeatures().size(), 1); TEST_EQUAL(consensus.at(1).getFeatures().size(), 2); IdentificationDataConverter::exportConsensusIDs(consensus); // sort for reproducibility auto& proteins = consensus.getProteinIdentifications(); for (auto& protein : proteins) { protein.sort(); } auto& un_peptides = consensus.getUnassignedPeptideIdentifications(); for (auto& un_pep : un_peptides) { un_pep.sort(); } consensus.sortByPosition(); String cxml_tmp; NEW_TMP_FILE(cxml_tmp); ConsensusXMLFile().store(cxml_tmp, consensus); TEST_EQUAL(File::empty(cxml_tmp), false); /* FuzzyStringComparator fsc; fsc.setAcceptableRelative(1.001); fsc.setAcceptableAbsolute(1); StringList sl; sl.push_back("xml-stylesheet"); sl.push_back("UnassignedPeptideIdentification"); fsc.setWhitelist(sl); TEST_EQUAL(fsc.compareFiles(cxml_tmp, OPENMS_GET_TEST_DATA_PATH("OMSFile_test_2.consensusXML")), true); */ } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/HashGrid_test.cpp
.cpp
7,069
248
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Lars Nilse $ // $Authors: Bastian Blank $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/ML/CLUSTERING/HashGrid.h> #include <limits> #include <iostream> using namespace OpenMS; struct Value { }; typedef OpenMS::HashGrid<Value> TestGrid; const TestGrid::ClusterCenter cell_dimension(1, 1); START_TEST(HashGrid, "$Id$") START_SECTION(HashGrid(const ClusterCenter &cell_dimension)) { TestGrid t(cell_dimension); TEST_EQUAL(t.cell_dimension, cell_dimension); TEST_EQUAL(t.grid_dimension[0], 0); TEST_EQUAL(t.grid_dimension[1], 0); } END_SECTION START_SECTION(cell_iterator insert(const value_type &v)) { TestGrid::cell_iterator it; TestGrid t(cell_dimension); const TestGrid::ClusterCenter key1(1, 2); it = t.insert(std::make_pair(key1, TestGrid::mapped_type())); TEST_EQUAL(t.grid_dimension[0], key1[0]); TEST_EQUAL(t.grid_dimension[1], key1[1]); TEST_EQUAL(it->first[0], key1[0]); TEST_EQUAL(it->first[1], key1[1]); const TestGrid::ClusterCenter key2(2, 3); it = t.insert(std::make_pair(key2, TestGrid::mapped_type())); TEST_EQUAL(t.grid_dimension[0], key2[0]); TEST_EQUAL(t.grid_dimension[1], key2[1]); TEST_EQUAL(it->first[0], key2[0]); TEST_EQUAL(it->first[1], key2[1]); { const TestGrid::ClusterCenter key(0, (double)std::numeric_limits<Int64>::min() - 1e5); TEST_EXCEPTION(Exception::OutOfRange, t.insert(std::make_pair(key, TestGrid::mapped_type()))); } { const TestGrid::ClusterCenter key(0, (double)std::numeric_limits<Int64>::max() + 1e5); TEST_EXCEPTION(Exception::OutOfRange, t.insert(std::make_pair(key, TestGrid::mapped_type()))); } } END_SECTION START_SECTION(void erase(iterator pos)) TestGrid t(cell_dimension); t.insert(std::make_pair(TestGrid::ClusterCenter(0, 0), TestGrid::mapped_type())); TEST_EQUAL(t.size(), 1); TestGrid::iterator it = t.begin(); t.erase(it); TEST_EQUAL(t.size(), 0); END_SECTION START_SECTION(size_type erase(const key_type& key)) { TestGrid t(cell_dimension); const TestGrid::ClusterCenter key(1, 2); t.insert(std::make_pair(key, TestGrid::mapped_type())); TEST_EQUAL(t.erase(key), 1); t.insert(std::make_pair(key, TestGrid::mapped_type())); t.insert(std::make_pair(key, TestGrid::mapped_type())); TEST_EQUAL(t.erase(key), 2); } END_SECTION START_SECTION(void clear()) { TestGrid t(cell_dimension); t.insert(std::make_pair(TestGrid::ClusterCenter(1, 2), TestGrid::mapped_type())); TEST_EQUAL(t.empty(), false); t.clear(); TEST_EQUAL(t.empty(), true); } END_SECTION START_SECTION(iterator begin()) { TestGrid t(cell_dimension); t.insert(std::make_pair(TestGrid::ClusterCenter(0, 0), TestGrid::mapped_type())); t.insert(std::make_pair(TestGrid::ClusterCenter(1, 0), TestGrid::mapped_type())); t.insert(std::make_pair(TestGrid::ClusterCenter(2, 0), TestGrid::mapped_type())); TestGrid::iterator it = t.begin(); TEST_EQUAL(it->first[0] <= 2, true); TEST_EQUAL(it->first[1], 0); it++; TEST_EQUAL(it->first[0] <= 2, true); TEST_EQUAL(it->first[1], 0); it++; TEST_EQUAL(it->first[0] <= 2, true); TEST_EQUAL(it->first[1], 0); it++; TEST_EQUAL(it == t.end(), true); } END_SECTION START_SECTION(const_iterator begin() const) { TestGrid t(cell_dimension); const TestGrid &ct(t); t.insert(std::make_pair(TestGrid::ClusterCenter(0, 0), TestGrid::mapped_type())); t.insert(std::make_pair(TestGrid::ClusterCenter(1, 0), TestGrid::mapped_type())); t.insert(std::make_pair(TestGrid::ClusterCenter(2, 0), TestGrid::mapped_type())); TestGrid::const_iterator it = ct.begin(); TEST_EQUAL(it->first[0] <= 2, true); TEST_EQUAL(it->first[1], 0); it++; TEST_EQUAL(it->first[0] <= 2, true); TEST_EQUAL(it->first[1], 0); it++; TEST_EQUAL(it->first[0] <= 2, true); TEST_EQUAL(it->first[1], 0); it++; TEST_EQUAL(it == ct.end(), true); } END_SECTION START_SECTION(iterator end()) { TestGrid t(cell_dimension); TestGrid::iterator it = t.begin(); TEST_EQUAL(it == t.end(), true); } END_SECTION START_SECTION(const_iterator end() const) { const TestGrid ct(cell_dimension); TestGrid::const_iterator it = ct.begin(); TEST_EQUAL(it == ct.end(), true); } END_SECTION START_SECTION(bool empty() const) TestGrid t(cell_dimension); TEST_EQUAL(t.empty(), true); t.insert(std::make_pair(TestGrid::ClusterCenter(0, 0), TestGrid::mapped_type())); TEST_EQUAL(t.empty(), false); t.insert(std::make_pair(TestGrid::ClusterCenter(0, 0), TestGrid::mapped_type())); TEST_EQUAL(t.empty(), false); END_SECTION START_SECTION(size_type size() const) TestGrid t(cell_dimension); TEST_EQUAL(t.size(), 0); t.insert(std::make_pair(TestGrid::ClusterCenter(0, 0), TestGrid::mapped_type())); TEST_EQUAL(t.size(), 1); t.insert(std::make_pair(TestGrid::ClusterCenter(0, 0), TestGrid::mapped_type())); TEST_EQUAL(t.size(), 2); t.insert(std::make_pair(TestGrid::ClusterCenter(1, 0), TestGrid::mapped_type())); TEST_EQUAL(t.size(), 3); END_SECTION START_SECTION(const_grid_iterator grid_begin() const) { TestGrid t(cell_dimension); t.insert(std::make_pair(TestGrid::ClusterCenter(1, 2), TestGrid::mapped_type())); const TestGrid &ct(t); TEST_EQUAL(ct.grid_begin()->second.size(), 1); } END_SECTION START_SECTION(grid_iterator grid_begin()) { TestGrid t(cell_dimension); t.insert(std::make_pair(TestGrid::ClusterCenter(1, 2), TestGrid::mapped_type())); TEST_EQUAL(t.grid_begin()->second.size(), 1); } END_SECTION START_SECTION(const_grid_iterator grid_end() const) { const TestGrid t(cell_dimension); TEST_EQUAL(t.grid_begin() == t.grid_end(), true); } END_SECTION START_SECTION(grid_iterator grid_end()) { TestGrid t(cell_dimension); TEST_EQUAL(t.grid_begin() == t.grid_end(), true); } END_SECTION START_SECTION(const Grid::mapped_type& grid_at(const CellIndex &x) const) { const TestGrid t(cell_dimension); const TestGrid::CellIndex i(0, 0); TEST_EXCEPTION(std::out_of_range, t.grid_at(i)); } END_SECTION START_SECTION(Grid::mapped_type& grid_at(const CellIndex &x)) { TestGrid t(cell_dimension); const TestGrid::CellIndex i(0, 0); TEST_EXCEPTION(std::out_of_range, t.grid_at(i)); } END_SECTION START_SECTION([EXTRA] std::size_t hash_value(const DPosition<N, T> &b)) { const DPosition<1, UInt> c1(1); const DPosition<1, UInt> c2(2); TEST_EQUAL(hash_value(c1), hash_value(c1)); TEST_NOT_EQUAL(hash_value(c1), hash_value(c2)); } { const DPosition<2, UInt> c1(1, 1); const DPosition<2, UInt> c2(1, 2); const DPosition<2, UInt> c3(2, 2); TEST_EQUAL(hash_value(c1), hash_value(c1)); TEST_NOT_EQUAL(hash_value(c1), hash_value(c2)); // Disabled: DPosition hash function is broken for this case //TEST_NOT_EQUAL(hash_value(c1), hash_value(c3)); } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CVReference_test.cpp
.cpp
3,409
144
// 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/CVReference.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(CVReference, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CVReference* ptr = nullptr; CVReference* nullPointer = nullptr; START_SECTION(CVReference()) { ptr = new CVReference(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~CVReference()) { delete ptr; } END_SECTION ptr = new CVReference(); START_SECTION((CVReference(const CVReference &rhs))) { CVReference cvr; TEST_STRING_EQUAL(CVReference(cvr).getName(), cvr.getName()) TEST_STRING_EQUAL(CVReference(cvr).getIdentifier(), cvr.getIdentifier()) cvr.setName("my_test_name"); TEST_STRING_EQUAL(CVReference(cvr).getName(), "my_test_name") cvr.setIdentifier("my_test_identifier"); TEST_STRING_EQUAL(CVReference(cvr).getIdentifier(), "my_test_identifier") } END_SECTION START_SECTION((CVReference& operator=(const CVReference &rhs))) { CVReference cvr, cvr_copy; cvr_copy = cvr; TEST_STRING_EQUAL(cvr_copy.getName(), "") TEST_STRING_EQUAL(cvr_copy.getIdentifier(), "") cvr.setName("my_test_name"); cvr_copy = cvr; TEST_STRING_EQUAL(cvr_copy.getName(), "my_test_name") cvr.setIdentifier("my_test_identifier"); cvr_copy = cvr; TEST_STRING_EQUAL(cvr_copy.getIdentifier(), "my_test_identifier") } END_SECTION START_SECTION((bool operator == (const CVReference& rhs) const)) { CVReference cvr, cvr_copy; TEST_TRUE(cvr == cvr_copy) cvr_copy = cvr; TEST_TRUE(cvr == cvr_copy) cvr.setName("my_test_name"); TEST_EQUAL(cvr == cvr_copy, false) cvr_copy = cvr; TEST_TRUE(cvr == cvr_copy) cvr.setIdentifier("my_test_identifier"); TEST_EQUAL(cvr == cvr_copy, false) cvr_copy = cvr; TEST_TRUE(cvr == cvr_copy) } END_SECTION START_SECTION((bool operator != (const CVReference& rhs) const)) { CVReference cvr, cvr_copy; TEST_EQUAL(cvr != cvr_copy, false) cvr_copy = cvr; TEST_EQUAL(cvr != cvr_copy, false) cvr.setName("my_test_name"); TEST_FALSE(cvr == cvr_copy) cvr_copy = cvr; TEST_EQUAL(cvr != cvr_copy, false) cvr.setIdentifier("my_test_identifier"); TEST_FALSE(cvr == cvr_copy) cvr_copy = cvr; TEST_EQUAL(cvr != cvr_copy, false) } END_SECTION START_SECTION((void setName(const String &name))) { ptr->setName("my_test_name"); TEST_STRING_EQUAL(ptr->getName(), "my_test_name") } END_SECTION START_SECTION((const String& getName() const )) { NOT_TESTABLE } END_SECTION START_SECTION((void setIdentifier(const String &identifier))) { ptr->setIdentifier("my_test_identifier"); TEST_STRING_EQUAL(ptr->getIdentifier(), "my_test_identifier") } END_SECTION START_SECTION((const String& getIdentifier() const )) { NOT_TESTABLE } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ExperimentalSettings_test.cpp
.cpp
10,318
359
// 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/ExperimentalSettings.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ExperimentalSettings, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ExperimentalSettings* ptr = nullptr; ExperimentalSettings* nullPointer = nullptr; START_SECTION((ExperimentalSettings())) ptr = new ExperimentalSettings(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~ExperimentalSettings())) delete ptr; END_SECTION START_SECTION((const DateTime& getDateTime() const)) ExperimentalSettings tmp; TEST_EQUAL(tmp.getDateTime().get(),"0000-00-00 00:00:00"); END_SECTION START_SECTION((const HPLC& getHPLC() const)) ExperimentalSettings tmp; TEST_EQUAL(tmp.getHPLC()==HPLC(),true); END_SECTION START_SECTION((const Instrument& getInstrument() const)) ExperimentalSettings tmp; TEST_EQUAL(tmp.getInstrument()==Instrument(),true); END_SECTION START_SECTION((const Sample& getSample() const)) ExperimentalSettings tmp; TEST_EQUAL(tmp.getSample()==Sample(),true); END_SECTION START_SECTION((const std::vector<SourceFile>& getSourceFiles() const)) ExperimentalSettings tmp; TEST_EQUAL(tmp.getSourceFiles().size(),0); END_SECTION START_SECTION((const String& getComment() const)) ExperimentalSettings tmp; TEST_EQUAL(tmp.getComment(), ""); END_SECTION START_SECTION((void setComment(const String& comment))) ExperimentalSettings tmp; tmp.setComment("bla"); TEST_EQUAL(tmp.getComment(), "bla"); END_SECTION START_SECTION((const String& getFractionIdentifier() const)) ExperimentalSettings tmp; TEST_EQUAL(tmp.getFractionIdentifier(), ""); END_SECTION START_SECTION((void setFractionIdentifier(const String& fraction_identifier))) ExperimentalSettings tmp; tmp.setFractionIdentifier("bla"); TEST_EQUAL(tmp.getFractionIdentifier(), "bla"); END_SECTION START_SECTION((void setContacts(const std::vector<ContactPerson>& contacts))) ExperimentalSettings tmp; std::vector<ContactPerson> dummy; ContactPerson c; c.setFirstName("bla17"); c.setLastName("blubb17"); dummy.push_back(c); c.setFirstName("bla18"); c.setLastName("blubb18"); dummy.push_back(c); tmp.setContacts(dummy); TEST_EQUAL(tmp.getContacts().size(),2); TEST_EQUAL(tmp.getContacts()[0].getFirstName(),"bla17"); TEST_EQUAL(tmp.getContacts()[1].getFirstName(),"bla18"); TEST_EQUAL(tmp.getContacts()[0].getLastName(),"blubb17"); TEST_EQUAL(tmp.getContacts()[1].getLastName(),"blubb18"); END_SECTION START_SECTION((void setDateTime(const DateTime &date))) ExperimentalSettings tmp; DateTime dummy; dummy.set("02/07/2006 01:02:03"); tmp.setDateTime(dummy); TEST_EQUAL(tmp.getDateTime().get(),"2006-02-07 01:02:03"); END_SECTION START_SECTION((void setHPLC(const HPLC& hplc))) ExperimentalSettings tmp; HPLC dummy; dummy.setFlux(5); tmp.setHPLC(dummy); TEST_EQUAL(tmp.getHPLC().getFlux(),5); END_SECTION START_SECTION((void setInstrument(const Instrument& instrument))) ExperimentalSettings tmp; Instrument dummy; dummy.setName("bla"); tmp.setInstrument(dummy); TEST_EQUAL(tmp.getInstrument().getName(),"bla"); END_SECTION START_SECTION((void setSample(const Sample& sample))) ExperimentalSettings tmp; Sample dummy; dummy.setName("bla3"); tmp.setSample(dummy); TEST_EQUAL(tmp.getSample().getName(),"bla3"); END_SECTION START_SECTION((void setSourceFiles(const std::vector< SourceFile > &source_files))) ExperimentalSettings tmp; vector<SourceFile> dummy; dummy.resize(1); tmp.setSourceFiles(dummy); TEST_EQUAL(tmp.getSourceFiles().size(),1); END_SECTION START_SECTION((HPLC& getHPLC())) ExperimentalSettings tmp; tmp.getHPLC().setFlux(5); TEST_EQUAL(tmp.getHPLC().getFlux(),5); END_SECTION START_SECTION((Instrument& getInstrument())) ExperimentalSettings tmp; tmp.getInstrument().setName("bla55"); TEST_EQUAL(tmp.getInstrument().getName(),"bla55"); END_SECTION START_SECTION((Sample& getSample())) ExperimentalSettings tmp; tmp.getSample().setName("bla2"); TEST_EQUAL(tmp.getSample().getName(),"bla2"); END_SECTION START_SECTION((std::vector<SourceFile>& getSourceFiles())) ExperimentalSettings tmp; tmp.getSourceFiles().resize(1); TEST_EQUAL(tmp.getSourceFiles().size(),1) END_SECTION START_SECTION((const std::vector<ContactPerson>& getContacts() const)) ExperimentalSettings tmp; TEST_EQUAL(tmp.getContacts().size(),0); END_SECTION START_SECTION((std::vector<ContactPerson>& getContacts())) ExperimentalSettings tmp; ContactPerson c; c.setFirstName("bla17"); tmp.getContacts().push_back(c); c.setFirstName("bla18"); tmp.getContacts().push_back(c); TEST_EQUAL(tmp.getContacts().size(),2); TEST_EQUAL(tmp.getContacts()[0].getFirstName(),"bla17"); TEST_EQUAL(tmp.getContacts()[1].getFirstName(),"bla18"); END_SECTION START_SECTION((ExperimentalSettings(const ExperimentalSettings& source))) ExperimentalSettings tmp; ProteinIdentification id; ProteinHit protein_hit; float protein_significance_threshold = 63.2f; id.setDateTime(DateTime::now()); id.setSignificanceThreshold(protein_significance_threshold); id.insertHit(protein_hit); tmp.getHPLC().setFlux(5); tmp.setComment("bla"); tmp.setFractionIdentifier("bla2"); tmp.setIdentifier("lsid"); tmp.getInstrument().setName("bla"); tmp.getSample().setName("bla2"); tmp.getSourceFiles().resize(1); tmp.getContacts().resize(1); tmp.setMetaValue("label",String("label")); ExperimentalSettings tmp2(tmp); TEST_EQUAL(tmp2.getComment(),"bla"); TEST_EQUAL(tmp2.getFractionIdentifier(),"bla2"); TEST_EQUAL(tmp2.getIdentifier(),"lsid"); TEST_EQUAL(tmp2.getHPLC().getFlux(),5); TEST_EQUAL(tmp2.getInstrument().getName(),"bla"); TEST_EQUAL(tmp2.getSample().getName(),"bla2"); TEST_EQUAL(tmp2.getSourceFiles().size(),1); TEST_EQUAL(tmp2.getContacts().size(),1); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); END_SECTION START_SECTION((ExperimentalSettings& operator= (const ExperimentalSettings& source))) ExperimentalSettings tmp; ProteinIdentification id; ProteinHit protein_hit; float protein_significance_threshold = 63.2f; id.setDateTime(DateTime::now()); id.setSignificanceThreshold(protein_significance_threshold); id.insertHit(protein_hit); tmp.getHPLC().setFlux(5); tmp.setComment("bla"); tmp.setFractionIdentifier("bla2"); tmp.setIdentifier("lsid"); tmp.getInstrument().setName("bla"); tmp.getSample().setName("bla2"); tmp.getSourceFiles().resize(1); tmp.getContacts().resize(1); tmp.setMetaValue("label",String("label")); ExperimentalSettings tmp2; tmp2 = tmp; TEST_EQUAL(tmp2.getHPLC().getFlux(),5); TEST_EQUAL(tmp2.getInstrument().getName(),"bla"); TEST_EQUAL(tmp2.getComment(),"bla"); TEST_EQUAL(tmp2.getFractionIdentifier(),"bla2"); TEST_EQUAL(tmp2.getIdentifier(),"lsid"); TEST_EQUAL(tmp2.getSample().getName(),"bla2"); TEST_EQUAL(tmp2.getSourceFiles().size(),1); TEST_EQUAL(tmp2.getContacts().size(),1); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); tmp2 = ExperimentalSettings(); TEST_EQUAL(tmp2.getHPLC().getFlux(),0); TEST_EQUAL(tmp2.getInstrument().getName(),""); TEST_EQUAL(tmp2.getComment(),""); TEST_EQUAL(tmp2.getFractionIdentifier(),""); TEST_EQUAL(tmp2.getIdentifier(),""); TEST_EQUAL(tmp2.getSample().getName(),""); TEST_EQUAL(tmp2.getSourceFiles().size(),0); TEST_EQUAL(tmp2.getContacts().size(),0); TEST_EQUAL(tmp2.getMetaValue("label").isEmpty(), true); END_SECTION START_SECTION((bool operator== (const ExperimentalSettings& rhs) const)) ExperimentalSettings edit, empty; ProteinIdentification id; ProteinHit protein_hit; float protein_significance_threshold = 63.2f; id.setDateTime(DateTime::now()); id.setSignificanceThreshold(protein_significance_threshold); id.insertHit(protein_hit); TEST_EQUAL(edit==empty,true); edit.getHPLC().setFlux(5); TEST_EQUAL(edit==empty,false); edit = empty; edit.getInstrument().setName("bla"); TEST_EQUAL(edit==empty,false); edit = empty; edit.getSample().setName("bla2"); TEST_EQUAL(edit==empty,false); edit = empty; edit.getSourceFiles().resize(1); TEST_EQUAL(edit==empty,false); edit = empty; edit.getContacts().resize(1); TEST_EQUAL(edit==empty,false); edit = empty; edit.setComment("bla"); TEST_EQUAL(edit==empty, false); edit = empty; edit.setFractionIdentifier("bla"); TEST_EQUAL(edit==empty, false); edit = empty; edit.setIdentifier("bla"); TEST_EQUAL(edit==empty, false); edit = empty; edit.setMetaValue("label",String("label")); TEST_EQUAL(edit==empty,false); END_SECTION START_SECTION((bool operator!= (const ExperimentalSettings& rhs) const)) ExperimentalSettings edit, empty; ProteinIdentification id; ProteinHit protein_hit; float protein_significance_threshold = 63.2f; id.setDateTime(DateTime::now()); id.setSignificanceThreshold(protein_significance_threshold); id.insertHit(protein_hit); TEST_EQUAL(edit!=empty,false); edit.getHPLC().setFlux(5); TEST_EQUAL(edit!=empty,true); edit = empty; edit.getInstrument().setName("bla"); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setComment("bla"); TEST_FALSE(edit == empty); edit = empty; edit.setFractionIdentifier("bla2"); TEST_FALSE(edit == empty); edit = empty; edit.getSample().setName("bla2"); TEST_EQUAL(edit!=empty,true); edit = empty; edit.getSourceFiles().resize(1); TEST_EQUAL(edit!=empty,true); edit = empty; edit.getContacts().resize(1); 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/TheoreticalSpectrumGeneratorXLMS_test.cpp
.cpp
27,944
790
// 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/TheoreticalSpectrumGeneratorXLMS.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/SpectrumHelper.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/CONCEPT/Constants.h> #include <OpenMS/ANALYSIS/XLMS/OPXLDataStructs.h> #include <iostream> START_TEST(TheoreticalSpectrumGeneratorXLMS, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; TheoreticalSpectrumGeneratorXLMS* ptr = nullptr; TheoreticalSpectrumGeneratorXLMS* nullPointer = nullptr; /// mostly copied from TheoreticalSpectrumGenerator_test ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// START_SECTION(TheoreticalSpectrumGeneratorXLMS()) ptr = new TheoreticalSpectrumGeneratorXLMS(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(TheoreticalSpectrumGeneratorXLMS(const TheoreticalSpectrumGeneratorXLMS& source)) TheoreticalSpectrumGeneratorXLMS copy(*ptr); TEST_EQUAL(copy.getParameters(), ptr->getParameters()) END_SECTION START_SECTION(~TheoreticalSpectrumGeneratorXLMS()) delete ptr; END_SECTION ptr = new TheoreticalSpectrumGeneratorXLMS(); AASequence peptide = AASequence::fromString("IFSQVGK"); START_SECTION(TheoreticalSpectrumGeneratorXLMS& operator = (const TheoreticalSpectrumGeneratorXLMS& tsg)) TheoreticalSpectrumGeneratorXLMS copy; copy = *ptr; TEST_EQUAL(copy.getParameters(), ptr->getParameters()) END_SECTION ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// START_SECTION(virtual void getLinearIonSpectrum(PeakSpectrum & spectrum, AASequence & peptide, Size link_pos, bool frag_alpha, int charge = 1, Size link_pos_2 = 0)) PeakSpectrum spec; ptr->getLinearIonSpectrum(spec, peptide, 3, true, 2); TEST_EQUAL(spec.size(), 18) TOLERANCE_ABSOLUTE(0.001) double result[] = {43.55185, 57.54930, 74.06004, 86.09642, 102.57077, 114.09134, 117.08605, 131.08351, 147.11280, 152.10497, 160.60207, 174.59953, 204.13426, 233.16484, 261.15975, 303.20268, 320.19686, 348.19178}; for (Size i = 0; i != spec.size(); ++i) { TEST_REAL_SIMILAR(spec[i].getPosition()[0], result[i]) } spec.clear(true); ptr->getLinearIonSpectrum(spec, peptide, 3, true, 3); TEST_EQUAL(spec.size(), 27) spec.clear(true); Param param(ptr->getParameters()); param.setValue("add_a_ions", "true"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "true"); param.setValue("add_x_ions", "true"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "true"); param.setValue("add_metainfo", "false"); ptr->setParameters(param); ptr->getLinearIonSpectrum(spec, peptide, 3, true, 3); TEST_EQUAL(spec.size(), 54) // // test annotation spec.clear(true); param = ptr->getParameters(); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "false"); param.setValue("add_x_ions", "true"); param.setValue("add_y_ions", "false"); param.setValue("add_z_ions", "false"); param.setValue("add_metainfo", "true"); param.setValue("add_losses", "true"); ptr->setParameters(param); ptr->getLinearIonSpectrum(spec, peptide, 3, true, 3); // 6 ion types with 3 charges each are expected TEST_EQUAL(spec.size(), 30) set<String> ion_names; ion_names.insert("[alpha|ci$b1]"); ion_names.insert("[alpha|ci$b2]"); ion_names.insert("[alpha|ci$b2-H2O1]"); ion_names.insert("[alpha|ci$b3]"); ion_names.insert("[alpha|ci$b3-H2O1]"); ion_names.insert("[alpha|ci$b3-H3N1]"); ion_names.insert("[alpha|ci$x1]"); ion_names.insert("[alpha|ci$x2]"); ion_names.insert("[alpha|ci$x3]"); ion_names.insert("[alpha|ci$x1-H3N1]"); ion_names.insert("[alpha|ci$x2-H3N1]"); ion_names.insert("[alpha|ci$x3-H3N1]"); PeakSpectrum::StringDataArray string_array = spec.getStringDataArrays().at(0); // check if all ion names have been annotated for (Size i = 0; i != spec.size(); ++i) { String name = string_array[i]; TEST_EQUAL(ion_names.find(name) != ion_names.end(), true) } // beta annotations spec.clear(true); ptr->getLinearIonSpectrum(spec, peptide, 3, false, 3); ion_names.clear(); ion_names.insert("[beta|ci$b1]"); ion_names.insert("[beta|ci$b2]"); ion_names.insert("[beta|ci$b2-H2O1]"); ion_names.insert("[beta|ci$b3]"); ion_names.insert("[beta|ci$b3-H2O1]"); ion_names.insert("[beta|ci$b3-H3N1]"); ion_names.insert("[beta|ci$x1]"); ion_names.insert("[beta|ci$x2]"); ion_names.insert("[beta|ci$x3]"); ion_names.insert("[beta|ci$x1-H3N1]"); ion_names.insert("[beta|ci$x2-H3N1]"); ion_names.insert("[beta|ci$x3-H3N1]"); string_array = spec.getStringDataArrays().at(0); for (Size i = 0; i != spec.size(); ++i) { String name = string_array[i]; TEST_EQUAL(ion_names.find(name) != ion_names.end(), true) } // test for charges stored in IntegerDataArray PeakSpectrum::IntegerDataArray charge_array = spec.getIntegerDataArrays().at(0); int charge_counts[3] = {0, 0, 0}; for (Size i = 0; i != spec.size(); ++i) { charge_counts[charge_array[i]-1]++; } TEST_EQUAL(charge_counts[0], 10) TEST_EQUAL(charge_counts[1], 10) TEST_EQUAL(charge_counts[2], 10) param = ptr->getParameters(); param.setValue("add_losses", "false"); ptr->setParameters(param); // the smallest examples, that make sense for cross-linking spec.clear(true); AASequence testseq = AASequence::fromString("HA"); ptr->getLinearIonSpectrum(spec, testseq, 0, true, 1); TEST_EQUAL(spec.size(), 1) spec.clear(true); ptr->getLinearIonSpectrum(spec, testseq, 1, true, 1); TEST_EQUAL(spec.size(), 1) // loop link spec.clear(true); testseq = AASequence::fromString("PEPTIDESAREWEIRD"); ptr->getLinearIonSpectrum(spec, testseq, 1, true, 1, 14); TEST_EQUAL(spec.size(), 2) spec.clear(true); ptr->getLinearIonSpectrum(spec, testseq, 2, false, 1, 14); TEST_EQUAL(spec.size(), 3) // test isotopic peaks spec.clear(true); param = ptr->getParameters(); param.setValue("add_isotopes", "true"); param.setValue("max_isotope", 1); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "false"); param.setValue("add_x_ions", "false"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "false"); param.setValue("add_metainfo", "false"); ptr->setParameters(param); ptr->getLinearIonSpectrum(spec, peptide, 3, true, 3); // 6 ion types with 3 charges each are expected TEST_EQUAL(spec.size(), 18) spec.clear(true); param.setValue("add_isotopes", "true"); param.setValue("max_isotope", 2); // param.setValue("add_losses", "true"); ptr->setParameters(param); ptr->getLinearIonSpectrum(spec, peptide, 3, true, 3); // 6 ion types with 3 charges each are expected, each with a second isotopic peak // + a few losses TEST_EQUAL(spec.size(), 48) spec.clear(true); param.setValue("add_isotopes", "true"); param.setValue("max_isotope", 3); // not supported yet, but it should at least run (with the maximal possible number of peaks) ptr->setParameters(param); ptr->getLinearIonSpectrum(spec, peptide, 3, true, 3); // 6 ion types with 3 charges each are expected, each with a second isotopic peak // should be the same result as above for now TEST_EQUAL(spec.size(), 48) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // for quick benchmarking of implementation chances // param = ptr->getParameters(); // param.setValue("add_a_ions", "true"); // param.setValue("add_b_ions", "true"); // param.setValue("add_c_ions", "true"); // param.setValue("add_x_ions", "true"); // param.setValue("add_y_ions", "true"); // param.setValue("add_z_ions", "true"); // param.setValue("add_metainfo", "true"); // param.setValue("add_losses", "true"); // ptr->setParameters(param); // AASequence tmp_peptide = AASequence::fromString("PEPTIDEPEPTIDEPEPTIDE"); // for (Size i = 0; i != 1e4; ++i) // { // PeakSpectrum spec; // ptr->getLinearIonSpectrum(spec, tmp_peptide, 9, true, 5); // } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// END_SECTION START_SECTION(virtual void getXLinkIonSpectrum(PeakSpectrum & spectrum, AASequence & peptide, Size link_pos, double precursor_mass, bool frag_alpha, int mincharge, int maxcharge, Size link_pos_2 = 0)) // reinitialize TSG to standard parameters Param param(ptr->getParameters()); param.setValue("add_isotopes", "false"); param.setValue("max_isotope", 2); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "false"); param.setValue("add_x_ions", "false"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "false"); param.setValue("add_losses", "false"); param.setValue("add_metainfo", "false"); ptr->setParameters(param); PeakSpectrum spec; ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 3); TEST_EQUAL(spec.size(), 17) param.setValue("add_metainfo", "true"); ptr->setParameters(param); spec.clear(true); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 3); TEST_EQUAL(spec.size(), 17) param.setValue("add_metainfo", "false"); param.setValue("add_losses", "true"); ptr->setParameters(param); spec.clear(true); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 3); TEST_EQUAL(spec.size(), 39) param.setValue("add_metainfo", "true"); ptr->setParameters(param); spec.clear(true); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 3); TEST_EQUAL(spec.size(), 39) TOLERANCE_ABSOLUTE(0.001) param.setValue("add_losses", "false"); param.setValue("add_metainfo", "false"); ptr->setParameters(param); spec.clear(true); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 3); double result[] = {442.55421, 551.94577, 566.94214, 580.95645, 599.96494, 618.97210, 629.97925, 661.67042, 661.99842, 663.32768, 667.67394, 827.41502, 849.90957, 870.93103, 899.44378, 927.95451, 944.46524}; for (Size i = 0; i != spec.size(); ++i) { TEST_REAL_SIMILAR(spec[i].getPosition()[0], result[i]) } spec.clear(true); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 4); TEST_EQUAL(spec.size(), 24) spec.clear(true); param.setValue("add_a_ions", "true"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "true"); param.setValue("add_x_ions", "true"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "true"); param.setValue("add_metainfo", "false"); ptr->setParameters(param); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 4); TEST_EQUAL(spec.size(), 60) // test annotation spec.clear(true); param = ptr->getParameters(); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "false"); param.setValue("add_x_ions", "true"); param.setValue("add_y_ions", "false"); param.setValue("add_z_ions", "false"); param.setValue("add_losses", "true"); param.setValue("add_metainfo", "true"); ptr->setParameters(param); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 5); // 6 ion types with 4 charges each are expected // + KLinked ions and precursors TEST_EQUAL(spec.size(), 75) set<String> ion_names; ion_names.insert("[alpha|xi$b4]"); ion_names.insert("[alpha|xi$b5]"); ion_names.insert("[alpha|xi$b6]"); ion_names.insert("[alpha|xi$x4]"); ion_names.insert("[alpha|xi$x5]"); ion_names.insert("[alpha|xi$x6]"); ion_names.insert("[Q-linked-beta]"); ion_names.insert("[M+H]"); ion_names.insert("[M+H]-H2O"); ion_names.insert("[M+H]-NH3"); ion_names.insert("[alpha|xi$x4-H3N1]"); ion_names.insert("[alpha|xi$b4-H2O1]"); ion_names.insert("[alpha|xi$b4-H3N1]"); ion_names.insert("[alpha|xi$x5-H2O1]"); ion_names.insert("[alpha|xi$x5-H3N1]"); ion_names.insert("[alpha|xi$b5-H2O1]"); ion_names.insert("[alpha|xi$b5-H3N1]"); ion_names.insert("[alpha|xi$b6-H3N1]"); ion_names.insert("[alpha|xi$b6-H2O1]"); ion_names.insert("[alpha|xi$x6-H3N1]"); ion_names.insert("[alpha|xi$x6-H2O1]"); PeakSpectrum::StringDataArray string_array = spec.getStringDataArrays().at(0); // check if all ion names have been annotated for (Size i = 0; i != spec.size(); ++i) { String name = string_array[i]; TEST_EQUAL(ion_names.find(name) != ion_names.end(), true) } // beta annotations spec.clear(true); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, false, 2, 4); ion_names.clear(); ion_names.insert("[beta|xi$b4]"); ion_names.insert("[beta|xi$b5]"); ion_names.insert("[beta|xi$b6]"); ion_names.insert("[beta|xi$x4]"); ion_names.insert("[beta|xi$x5]"); ion_names.insert("[beta|xi$x6]"); ion_names.insert("[Q-linked-alpha]"); ion_names.insert("[M+H]"); ion_names.insert("[M+H]-H2O"); ion_names.insert("[M+H]-NH3"); ion_names.insert("[beta|xi$b6-H2O1]"); ion_names.insert("[beta|xi$b6-H3N1]"); ion_names.insert("[beta|xi$x6-H2O1]"); ion_names.insert("[beta|xi$x6-H3N1]"); ion_names.insert("[beta|xi$x4-H3N1]"); ion_names.insert("[beta|xi$b4-H2O1]"); ion_names.insert("[beta|xi$b4-H3N1]"); ion_names.insert("[beta|xi$x5-H2O1]"); ion_names.insert("[beta|xi$x5-H3N1]"); ion_names.insert("[beta|xi$b5-H2O1]"); ion_names.insert("[beta|xi$b5-H3N1]"); string_array = spec.getStringDataArrays().at(0); for (Size i = 0; i != spec.size(); ++i) { String name = string_array[i]; TEST_EQUAL(ion_names.find(name) != ion_names.end(), true) } // test for charges stored in IntegerDataArray PeakSpectrum::IntegerDataArray charge_array = spec.getIntegerDataArrays().at(0); int charge_counts[5] = {0, 0, 0, 0, 0}; for (Size i = 0; i != spec.size(); ++i) { charge_counts[charge_array[i]-1]++; } TEST_EQUAL(charge_counts[0], 0) TEST_EQUAL(charge_counts[1], 18) TEST_EQUAL(charge_counts[2], 18) TEST_EQUAL(charge_counts[3], 21) TEST_EQUAL(charge_counts[4], 0) param = ptr->getParameters(); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "false"); param.setValue("add_x_ions", "false"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "false"); param.setValue("add_metainfo", "true"); param.setValue("add_losses", "false"); param.setValue("add_precursor_peaks", "false"); param.setValue("add_k_linked_ions", "false"); ptr->setParameters(param); // the smallest examples, that make sense for cross-linking spec.clear(true); AASequence testseq = AASequence::fromString("HA"); ptr->getXLinkIonSpectrum(spec, testseq, 0, 2000.0, true, 1, 1); TEST_EQUAL(spec.size(), 1) spec.clear(true); ptr->getXLinkIonSpectrum(spec, testseq, 1, 2000.0, true, 1, 1); TEST_EQUAL(spec.size(), 1) // loop link spec.clear(true); testseq = AASequence::fromString("PEPTIDESAREWEIRD"); ptr->getXLinkIonSpectrum(spec, testseq, 1, 2000.0, true, 1, 1, 14); TEST_EQUAL(spec.size(), 2) spec.clear(true); ptr->getXLinkIonSpectrum(spec, testseq, 2, 2000.0, false, 1, 1, 14); TEST_EQUAL(spec.size(), 3) spec.clear(true); ptr->getXLinkIonSpectrum(spec, testseq, 2, 2000.0, false, 1, 1, 13); TEST_EQUAL(spec.size(), 4) // test isotopic peaks spec.clear(true); param = ptr->getParameters(); param.setValue("add_isotopes", "true"); param.setValue("max_isotope", 1); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "false"); param.setValue("add_x_ions", "false"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "false"); param.setValue("add_metainfo", "false"); ptr->setParameters(param); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 5); // 6 ion types with 4 charges each are expected TEST_EQUAL(spec.size(), 24) spec.clear(true); param.setValue("add_isotopes", "true"); param.setValue("max_isotope", 2); // ptr->setParameters(param); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 5); // 6 ion types with 4 charges each are expected, each with a second isotopic peak TEST_EQUAL(spec.size(), 48) spec.clear(true); param.setValue("add_isotopes", "true"); param.setValue("max_isotope", 3); // not supported yet, but it should at least run (with the maximal possible number of peaks) ptr->setParameters(param); ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, true, 2, 5); // 6 ion types with 4 charges each are expected, each with a second isotopic peak TEST_EQUAL(spec.size(), 48) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // for quick benchmarking of implementation chances // param = ptr->getParameters(); // param.setValue("add_a_ions", "true"); // param.setValue("add_b_ions", "true"); // param.setValue("add_c_ions", "true"); // param.setValue("add_x_ions", "true"); // param.setValue("add_y_ions", "true"); // param.setValue("add_z_ions", "true"); // param.setValue("add_metainfo", "true"); // param.setValue("add_losses", "false"); // ptr->setParameters(param); // AASequence tmp_peptide = AASequence::fromString("PEPTIDEPEPTIDEPEPTIDE"); // for (Size i = 0; i != 1e3; ++i) // { // PeakSpectrum spec; // ptr->getXLinkIonSpectrum(spec, tmp_peptide, 9, 2000.0, false, 2, 5); // } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// END_SECTION START_SECTION(virtual void getXLinkIonSpectrum(PeakSpectrum & spectrum, OPXLDataStructs::ProteinProteinCrossLink & crosslink, bool frag_alpha, int mincharge, int maxcharge)) // reinitialize TSG to standard parameters Param param(ptr->getParameters()); param.setValue("add_isotopes", "false"); param.setValue("max_isotope", 2); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "false"); param.setValue("add_x_ions", "false"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "false"); param.setValue("add_losses", "false"); param.setValue("add_metainfo", "false"); param.setValue("add_precursor_peaks", "true"); param.setValue("add_k_linked_ions", "true"); ptr->setParameters(param); OPXLDataStructs::ProteinProteinCrossLink test_link; test_link.alpha = &peptide; AASequence beta = AASequence::fromString("TESTPEP"); test_link.beta = &beta; test_link.cross_link_position = std::make_pair<SignedSize, SignedSize> (3, 4); test_link.cross_linker_mass = 150.0; PeakSpectrum spec; ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 3); TEST_EQUAL(spec.size(), 17) param.setValue("add_metainfo", "true"); ptr->setParameters(param); spec.clear(true); ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 3); TEST_EQUAL(spec.size(), 17) param.setValue("add_metainfo", "false"); param.setValue("add_losses", "true"); ptr->setParameters(param); spec.clear(true); ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 3); TEST_EQUAL(spec.size(), 41) param.setValue("add_metainfo", "true"); ptr->setParameters(param); spec.clear(true); ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 3); TEST_EQUAL(spec.size(), 41) TOLERANCE_ABSOLUTE(0.001) param.setValue("add_losses", "false"); param.setValue("add_metainfo", "false"); ptr->setParameters(param); spec.clear(true); ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 3); // Example calculation for Residue-Linked Peptide (full peptide with one y/a fragmented residue cross-linked to it) // cross-link (with linker mass 150 Da): // IFSQVGK // | // TESTPEP // left over ion: // yQa // | // TESTPEP // alpha (M+2H)2+ = 389.72656 // beta (M+2H)2+ = 380.67165 // linker 2+ = 75 // = 845.39821 - 1 (remove 2/2 to reduce charges from +4 to +2) // precursor mz with charge 2+ = 844.39821 // IFS b3(2+) without charge protons = 173.59957 // VGK x3(2+) without charge protons = 164.09466 // 844.39821 - 173.59957 - 164.09466 =~ 506.70398 (with lazy proton masses) // corresponds to 6th ion: 506.71126 double result[] = {338.14327, 447.53482, 462.53119, 476.54550, 495.55399, 506.71126, 514.56115, 525.56830, 557.25947, 557.58748, 563.26299, 670.79860, 693.29315, 714.31461, 742.82736, 771.33809, 787.84882}; for (Size i = 0; i != spec.size(); ++i) { TEST_REAL_SIMILAR(spec[i].getPosition()[0], result[i]) } spec.clear(true); ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 4); TEST_EQUAL(spec.size(), 24) spec.clear(true); param.setValue("add_a_ions", "true"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "true"); param.setValue("add_x_ions", "true"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "true"); param.setValue("add_metainfo", "false"); ptr->setParameters(param); ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 4); TEST_EQUAL(spec.size(), 60) // test annotation spec.clear(true); param = ptr->getParameters(); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "false"); param.setValue("add_x_ions", "true"); param.setValue("add_y_ions", "false"); param.setValue("add_z_ions", "false"); param.setValue("add_losses", "true"); param.setValue("add_metainfo", "true"); ptr->setParameters(param); ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 5); // 6 ion types with 4 charges each are expected // + KLinked ions and precursors TEST_EQUAL(spec.size(), 79) set<String> ion_names; ion_names.insert("[alpha|xi$b4]"); ion_names.insert("[alpha|xi$b5]"); ion_names.insert("[alpha|xi$b6]"); ion_names.insert("[alpha|xi$x4]"); ion_names.insert("[alpha|xi$x5]"); ion_names.insert("[alpha|xi$x6]"); ion_names.insert("[Q-linked-beta]"); ion_names.insert("[M+H]"); ion_names.insert("[M+H]-H2O"); ion_names.insert("[M+H]-NH3"); ion_names.insert("[alpha|xi$x4-H3N1]"); ion_names.insert("[alpha|xi$x4-H2O1]"); ion_names.insert("[alpha|xi$b4-H2O1]"); ion_names.insert("[alpha|xi$b4-H3N1]"); ion_names.insert("[alpha|xi$x5-H2O1]"); ion_names.insert("[alpha|xi$x5-H3N1]"); ion_names.insert("[alpha|xi$b5-H2O1]"); ion_names.insert("[alpha|xi$b5-H3N1]"); ion_names.insert("[alpha|xi$b6-H3N1]"); ion_names.insert("[alpha|xi$b6-H2O1]"); ion_names.insert("[alpha|xi$x6-H3N1]"); ion_names.insert("[alpha|xi$x6-H2O1]"); PeakSpectrum::StringDataArray string_array = spec.getStringDataArrays().at(0); // check if all ion names have been annotated for (Size i = 0; i != spec.size(); ++i) { String name = string_array[i]; // TEST_EQUAL(name, "TESTSTRING") TEST_EQUAL(ion_names.find(name) != ion_names.end(), true) } // beta annotations spec.clear(true); ptr->getXLinkIonSpectrum(spec, test_link, false, 2, 4); ion_names.clear(); ion_names.insert("[beta|xi$b4]"); ion_names.insert("[beta|xi$b5]"); ion_names.insert("[beta|xi$b6]"); ion_names.insert("[beta|xi$x3]"); ion_names.insert("[beta|xi$x4]"); ion_names.insert("[beta|xi$x5]"); ion_names.insert("[beta|xi$x6]"); ion_names.insert("[P-linked-alpha]"); ion_names.insert("[M+H]"); ion_names.insert("[M+H]-H2O"); ion_names.insert("[M+H]-NH3"); ion_names.insert("[beta|xi$x3-H3N1]"); ion_names.insert("[beta|xi$x3-H2O1]"); ion_names.insert("[beta|xi$b6-H2O1]"); ion_names.insert("[beta|xi$b6-H3N1]"); ion_names.insert("[beta|xi$x6-H2O1]"); ion_names.insert("[beta|xi$x6-H3N1]"); ion_names.insert("[beta|xi$x4-H3N1]"); ion_names.insert("[beta|xi$x4-H2O1]"); ion_names.insert("[beta|xi$b4-H2O1]"); ion_names.insert("[beta|xi$b4-H3N1]"); ion_names.insert("[beta|xi$x5-H2O1]"); ion_names.insert("[beta|xi$x5-H3N1]"); ion_names.insert("[beta|xi$b5-H2O1]"); ion_names.insert("[beta|xi$b5-H3N1]"); string_array = spec.getStringDataArrays().at(0); for (Size i = 0; i != spec.size(); ++i) { String name = string_array[i]; // TEST_EQUAL(name, "TESTSTRING") TEST_EQUAL(ion_names.find(name) != ion_names.end(), true) } // test for charges stored in IntegerDataArray PeakSpectrum::IntegerDataArray charge_array = spec.getIntegerDataArrays().at(0); int charge_counts[5] = {0, 0, 0, 0, 0}; for (Size i = 0; i != spec.size(); ++i) { charge_counts[charge_array[i]-1]++; } TEST_EQUAL(charge_counts[0], 0) TEST_EQUAL(charge_counts[1], 19) TEST_EQUAL(charge_counts[2], 19) TEST_EQUAL(charge_counts[3], 22) TEST_EQUAL(charge_counts[4], 0) param = ptr->getParameters(); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "false"); param.setValue("add_x_ions", "false"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "false"); param.setValue("add_metainfo", "true"); param.setValue("add_losses", "false"); param.setValue("add_precursor_peaks", "false"); param.setValue("add_k_linked_ions", "false"); ptr->setParameters(param); // the smallest examples, that make sense for cross-linking spec.clear(true); AASequence testseq = AASequence::fromString("HA"); OPXLDataStructs::ProteinProteinCrossLink test_link_short; test_link_short.alpha = &testseq; test_link_short.beta = &beta; test_link_short.cross_link_position = std::make_pair<SignedSize, SignedSize> (1, 4); test_link_short.cross_linker_mass = 150.0; ptr->getXLinkIonSpectrum(spec, test_link_short, true, 1, 1); TEST_EQUAL(spec.size(), 1) spec.clear(true); ptr->getXLinkIonSpectrum(spec, test_link_short, true, 1, 1); TEST_EQUAL(spec.size(), 1) // test isotopic peaks spec.clear(true); param = ptr->getParameters(); param.setValue("add_isotopes", "true"); param.setValue("max_isotope", 1); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "true"); param.setValue("add_c_ions", "false"); param.setValue("add_x_ions", "false"); param.setValue("add_y_ions", "true"); param.setValue("add_z_ions", "false"); param.setValue("add_metainfo", "false"); ptr->setParameters(param); ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 5); // 6 ion types with 4 charges each are expected TEST_EQUAL(spec.size(), 24) spec.clear(true); param.setValue("add_isotopes", "true"); param.setValue("max_isotope", 2); // ptr->setParameters(param); ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 5); // 6 ion types with 4 charges each are expected, each with a second isotopic peak TEST_EQUAL(spec.size(), 48) spec.clear(true); param.setValue("add_isotopes", "true"); param.setValue("max_isotope", 3); // not supported yet, but it should at least run (with the maximal possible number of peaks) ptr->setParameters(param); ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 5); // 6 ion types with 4 charges each are expected, each with a second isotopic peak TEST_EQUAL(spec.size(), 48) END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/LPWrapper_test.cpp
.cpp
12,740
476
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Alexandra Zerck $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/LPWrapper.h> #ifdef OPENMS_HAS_COINOR #ifdef OPENMS_HAS_COIN_INCLUDE_SUBDIR_IS_COIN #include "coin/CoinModel.hpp" #else #include "coin-or/CoinModel.hpp" #endif #endif /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(LPWrapper, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// LPWrapper* ptr = nullptr; LPWrapper* null_ptr = nullptr; START_SECTION(LPWrapper()) { ptr = new LPWrapper(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~LPWrapper()) { delete ptr; } END_SECTION LPWrapper lp; std::vector<double> values(2,0.5); std::vector<Int> indices; indices.push_back(0); indices.push_back(1); START_SECTION((Int addColumn())) { lp.addColumn(); TEST_EQUAL(lp.getNumberOfColumns(),1); } END_SECTION START_SECTION((Int addRow(fewer args))) { lp.addColumn(); lp.addRow(indices,values,String("row1")); TEST_EQUAL(lp.getNumberOfRows(),1); TEST_EQUAL(lp.getRowName(0),"row1"); } END_SECTION START_SECTION((Int addColumn(std::vector< Int > column_indices, std::vector< double > column_values, const String &name))) { lp.addRow(indices,values,String("row2")); lp.addColumn(indices,values,String("col3")); TEST_EQUAL(lp.getNumberOfColumns(),3); TEST_EQUAL(lp.getColumnName(2),"col3"); } END_SECTION START_SECTION((Int addRow(all args))) { lp.addRow(indices,values,String("row3"),0.2,1.2,LPWrapper::DOUBLE_BOUNDED); TEST_EQUAL(lp.getNumberOfRows(),3); TEST_EQUAL(lp.getRowName(2),"row3"); } END_SECTION START_SECTION((Int addColumn(std::vector< Int > &column_indices, std::vector< double > &column_values, const String &name, double lower_bound, double upper_bound, Type type))) { lp.addColumn(indices,values,String("col4"),0.2,1.2,LPWrapper::DOUBLE_BOUNDED); TEST_EQUAL(lp.getNumberOfColumns(),4); TEST_EQUAL(lp.getColumnName(3),"col4"); } END_SECTION START_SECTION((void setColumnName(Int index, const String &name))) { lp.setColumnName(0,"col1"); TEST_EQUAL(lp.getColumnName(0),"col1"); } END_SECTION START_SECTION((String getColumnName(Int index))) { TEST_EQUAL(lp.getColumnName(0),"col1"); } END_SECTION START_SECTION((String getRowName(Int index))) { TEST_EQUAL(lp.getRowName(0),"row1"); } END_SECTION START_SECTION((Int getRowIndex(const String &name))) { TEST_EQUAL(lp.getRowIndex("row1"),0); } END_SECTION START_SECTION((Int getColumnIndex(const String &name))) { TEST_EQUAL(lp.getColumnIndex("col1"),0); } END_SECTION START_SECTION((void setRowName(Int index, const String &name))) { lp.setRowName(0,"new_row1"); TEST_EQUAL(lp.getRowName(0),"new_row1"); } END_SECTION START_SECTION((void setColumnBounds(Int index, double lower_bound, double upper_bound, Type type))) { lp.setColumnBounds(0,0.3,1.0,LPWrapper::DOUBLE_BOUNDED); TEST_EQUAL(lp.getColumnUpperBound(0),1.0); TEST_EQUAL(lp.getColumnLowerBound(0),0.3); } END_SECTION START_SECTION((void setRowBounds(Int index, double lower_bound, double upper_bound, Type type))) { lp.setRowBounds(0,-0.3,1.0,LPWrapper::DOUBLE_BOUNDED); TEST_EQUAL(lp.getRowUpperBound(0),1.0); TEST_EQUAL(lp.getRowLowerBound(0),-0.3); } END_SECTION START_SECTION((void setColumnType(Int index, VariableType type))) { lp.setColumnType(0,LPWrapper::INTEGER); TEST_EQUAL(lp.getColumnType(0),LPWrapper::INTEGER); } END_SECTION START_SECTION((VariableType getColumnType(Int index))) { lp.setColumnType(1,LPWrapper::BINARY); if (lp.getSolver()==LPWrapper::SOLVER_GLPK) TEST_EQUAL(lp.getColumnType(1),LPWrapper::BINARY) else TEST_EQUAL(lp.getColumnType(1),LPWrapper::INTEGER) } END_SECTION START_SECTION((void setObjective(Int index, double obj_value))) { lp.setObjective(0,3.5); TEST_EQUAL(lp.getObjective(0),3.5); } END_SECTION START_SECTION((double getObjective(Int index))) { lp.setObjective(1,2.5); TEST_EQUAL(lp.getObjective(1),2.5); } END_SECTION START_SECTION((void setObjectiveSense(Sense sense))) { lp.setObjectiveSense(LPWrapper::MIN); TEST_EQUAL(lp.getObjectiveSense(),LPWrapper::MIN) } END_SECTION START_SECTION((Sense getObjectiveSense())) { lp.setObjectiveSense(LPWrapper::MAX); TEST_EQUAL(lp.getObjectiveSense(),LPWrapper::MAX) } END_SECTION START_SECTION((Int getNumberOfColumns())) { TEST_EQUAL(lp.getNumberOfColumns(),4) } END_SECTION START_SECTION((Int getNumberOfRows())) { TEST_EQUAL(lp.getNumberOfRows(),3) } END_SECTION START_SECTION((double getColumnUpperBound(Int index))) { TEST_REAL_SIMILAR(lp.getColumnUpperBound(0),1.0) } END_SECTION START_SECTION((void deleteRow(Int index))) { lp.deleteRow(2); if(lp.getSolver() == LPWrapper::SOLVER_GLPK) { TEST_EQUAL(lp.getNumberOfRows(),2) } #ifdef OPENMS_HAS_COINOR else { // CoinOr doesn't delete the column, but sets all entries to zero and deletes the bounds, names, objective coeff etc. TEST_REAL_SIMILAR(lp.getObjective(2),0.) TEST_REAL_SIMILAR(lp.getColumnLowerBound(2),-COIN_DBL_MAX) TEST_REAL_SIMILAR(lp.getColumnUpperBound(2),COIN_DBL_MAX) } #endif } END_SECTION START_SECTION((double getColumnLowerBound(Int index))) { TEST_REAL_SIMILAR(lp.getColumnLowerBound(0),0.3) } END_SECTION START_SECTION((double getRowUpperBound(Int index))) { TEST_REAL_SIMILAR(lp.getRowUpperBound(0),1.0) } END_SECTION START_SECTION((double getRowLowerBound(Int index))) { TEST_REAL_SIMILAR(lp.getRowLowerBound(0),-0.3) } END_SECTION START_SECTION((void setElement(Int row_index, Int column_index, double value))) { lp.setElement(1,2,0.5); TEST_REAL_SIMILAR(lp.getElement(1,2),0.5) } END_SECTION START_SECTION((double getElement(Int row_index, Int column_index))) { lp.setElement(0,2,0.1); TEST_REAL_SIMILAR(lp.getElement(0,2),0.1) } END_SECTION START_SECTION((void readProblem(String filename, String format))) { if(lp.getSolver() == LPWrapper::SOLVER_GLPK) { lp.readProblem(OPENMS_GET_TEST_DATA_PATH("LPWrapper_test.lp"),"LP"); TEST_EQUAL(lp.getNumberOfColumns(),2) TEST_EQUAL(lp.getNumberOfRows(),3) TEST_EQUAL(lp.getColumnType(0),LPWrapper::INTEGER) TEST_EQUAL(lp.getColumnType(1),LPWrapper::INTEGER) TEST_EQUAL(lp.getObjective(0),1) TEST_EQUAL(lp.getObjective(1),0) TEST_EQUAL(lp.getRowUpperBound(0),0) TEST_EQUAL(lp.getRowUpperBound(1),12) TEST_EQUAL(lp.getRowUpperBound(2),12) TEST_EQUAL(lp.getElement(0,0),1) TEST_EQUAL(lp.getElement(0,1),-1) TEST_EQUAL(lp.getElement(1,0),2) TEST_EQUAL(lp.getElement(1,1),3) TEST_EQUAL(lp.getElement(2,0),3) TEST_EQUAL(lp.getElement(2,1),2) } #ifdef OPENMS_HAS_COINOR else if (lp.getSolver()==LPWrapper::SOLVER_COINOR) { lp.readProblem(OPENMS_GET_TEST_DATA_PATH("LPWrapper_test.mps"),"MPS"); TEST_EQUAL(lp.getNumberOfColumns(),2) TEST_EQUAL(lp.getNumberOfRows(),3) TEST_EQUAL(lp.getColumnType(0),LPWrapper::INTEGER) TEST_EQUAL(lp.getColumnType(1),LPWrapper::INTEGER) TEST_EQUAL(lp.getObjective(0),1) TEST_EQUAL(lp.getObjective(1),0) TEST_EQUAL(lp.getRowUpperBound(0),0) TEST_EQUAL(lp.getRowUpperBound(1),12) TEST_EQUAL(lp.getRowUpperBound(2),12) TEST_EQUAL(lp.getElement(0,0),1) TEST_EQUAL(lp.getElement(0,1),-1) TEST_EQUAL(lp.getElement(1,0),2) TEST_EQUAL(lp.getElement(1,1),3) TEST_EQUAL(lp.getElement(2,0),3) TEST_EQUAL(lp.getElement(2,1),2) } #endif } END_SECTION START_SECTION((void writeProblem(const String &filename, const WriteFormat format) const )) { #ifdef OPENMS_HAS_COINOR String tmp_filename; NEW_TMP_FILE(tmp_filename); lp.writeProblem(tmp_filename,LPWrapper::FORMAT_MPS); LPWrapper lp2; lp2.readProblem(tmp_filename,"MPS"); TEST_EQUAL(lp2.getNumberOfColumns(),2) TEST_EQUAL(lp2.getNumberOfRows(),3) TEST_EQUAL(lp2.getColumnType(0),LPWrapper::INTEGER) TEST_EQUAL(lp2.getColumnType(1),LPWrapper::INTEGER) TEST_EQUAL(lp2.getObjective(0),1) TEST_EQUAL(lp2.getObjective(1),0) TEST_EQUAL(lp2.getRowUpperBound(0),0) TEST_EQUAL(lp2.getRowUpperBound(1),12) TEST_EQUAL(lp2.getRowUpperBound(2),12) TEST_EQUAL(lp2.getElement(0,0),1) TEST_EQUAL(lp2.getElement(0,1),-1) TEST_EQUAL(lp2.getElement(1,0),2) TEST_EQUAL(lp2.getElement(1,1),3) TEST_EQUAL(lp2.getElement(2,0),3) TEST_EQUAL(lp2.getElement(2,1),2) #else String tmp_filename; NEW_TMP_FILE(tmp_filename); lp.writeProblem(tmp_filename, LPWrapper::FORMAT_LP); LPWrapper lp2; lp2.readProblem(tmp_filename, "LP"); TEST_EQUAL(lp2.getNumberOfColumns(), 2) TEST_EQUAL(lp2.getNumberOfRows(), 3) TEST_EQUAL(lp2.getColumnType(0), LPWrapper::INTEGER) TEST_EQUAL(lp2.getColumnType(1), LPWrapper::INTEGER) TEST_EQUAL(lp2.getObjective(0), 1) TEST_EQUAL(lp2.getObjective(1), 0) TEST_EQUAL(lp2.getRowUpperBound(0), 0) TEST_EQUAL(lp2.getRowUpperBound(1), 12) TEST_EQUAL(lp2.getRowUpperBound(2), 12) TEST_EQUAL(lp2.getElement(0, 0), 1) TEST_EQUAL(lp2.getElement(0, 1), -1) TEST_EQUAL(lp2.getElement(1, 0), 2) TEST_EQUAL(lp2.getElement(1, 1), 3) TEST_EQUAL(lp2.getElement(2, 0), 3) TEST_EQUAL(lp2.getElement(2, 1), 2) #endif } END_SECTION START_SECTION((Int solve(SolverParam &solver_param, const Size verbose_level=0))) { LPWrapper lp2; lp2.readProblem(OPENMS_GET_TEST_DATA_PATH("LPWrapper_test.mps"),"MPS"); lp2.setObjectiveSense(LPWrapper::MAX); LPWrapper::SolverParam param2; lp2.solve(param2); TEST_EQUAL(lp2.getColumnValue(0),1) TEST_EQUAL(lp2.getColumnValue(1),1) // Test an integer problem LPWrapper lp3; lp3.readProblem(OPENMS_GET_TEST_DATA_PATH("LPWrapper_test_integer.mps"),"MPS"); lp3.setObjectiveSense(LPWrapper::MAX); LPWrapper::SolverParam param3; lp3.solve(param3); TEST_EQUAL(lp3.getColumnValue(0),2) TEST_EQUAL(lp3.getColumnValue(1),2) } END_SECTION // Test an integer problem LPWrapper lp4; lp4.readProblem(OPENMS_GET_TEST_DATA_PATH("LPWrapper_test_integer.mps"),"MPS"); lp4.setObjectiveSense(LPWrapper::MAX); LPWrapper::SolverParam param4; lp4.solve(param4); START_SECTION((SolverStatus getStatus())) { if(lp4.getSolver() == LPWrapper::SOLVER_GLPK) { TEST_EQUAL(lp4.getStatus(),LPWrapper::OPTIMAL) } #ifdef OPENMS_HAS_COINOR else { TEST_EQUAL(lp4.getStatus(),LPWrapper::UNDEFINED) } #endif } END_SECTION START_SECTION((double getObjectiveValue())) { TEST_REAL_SIMILAR(lp4.getObjectiveValue(),2) } END_SECTION START_SECTION((double getColumnValue(Int index))) { TEST_REAL_SIMILAR(lp4.getColumnValue(0),2) TEST_REAL_SIMILAR(lp4.getColumnValue(1),2) } END_SECTION START_SECTION((Int getNumberOfNonZeroEntriesInRow(Int idx))) { TEST_EQUAL(lp4.getNumberOfNonZeroEntriesInRow(0),2) } END_SECTION START_SECTION((void getMatrixRow(Int idx,std::vector<Int>& indexes))) { std::vector<Int> idxs,idxs2; idxs.push_back(0); idxs.push_back(1); lp4.getMatrixRow(0,idxs2); TEST_EQUAL(idxs2.size(),idxs.size()) for(Size i = 0; i < idxs2.size();++i) { TEST_EQUAL(idxs2[i],idxs[i]) } } END_SECTION START_SECTION((SOLVER getSolver() const )) { #ifdef OPENMS_HAS_COINOR TEST_EQUAL(lp4.getSolver(),LPWrapper::SOLVER_COINOR) #else TEST_EQUAL(lp4.getSolver(), LPWrapper::SOLVER_GLPK) #endif } END_SECTION START_SECTION(([LPWrapper::SolverParam] SolverParam())) { LPWrapper::SolverParam* sptr = new LPWrapper::SolverParam(); LPWrapper::SolverParam* snull_ptr = nullptr; TEST_NOT_EQUAL(sptr, snull_ptr) TEST_EQUAL(sptr->message_level,3) TEST_EQUAL(sptr->branching_tech,4) TEST_EQUAL(sptr->backtrack_tech,3) TEST_EQUAL(sptr->preprocessing_tech,2) TEST_EQUAL(sptr->enable_feas_pump_heuristic,true) TEST_EQUAL(sptr->enable_gmi_cuts,true) TEST_EQUAL(sptr->enable_mir_cuts,true) TEST_EQUAL(sptr->enable_cov_cuts,true) TEST_EQUAL(sptr->enable_clq_cuts,true) TEST_EQUAL(sptr->mip_gap,0.0) TEST_EQUAL(sptr->output_freq,5000) TEST_EQUAL(sptr->output_delay,10000) TEST_EQUAL(sptr->enable_presolve,true) TEST_EQUAL(sptr->enable_binarization,true) delete sptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MapAlignerBase_test.cpp
.cpp
1,037
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/APPLICATIONS/MapAlignerBase.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MapAlignerBase, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MapAlignerBase* ptr = 0; MapAlignerBase* null_ptr = 0; START_SECTION(MapAlignerBase()) { ptr = new MapAlignerBase(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~MapAlignerBase()) { delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MzXMLFile_test.cpp
.cpp
24,415
649
// 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/FORMAT/MzXMLFile.h> #include <OpenMS/FORMAT/FileTypes.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/StandardTypes.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); } class TICConsumer : public Interfaces::IMSDataConsumer { typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; public: double TIC; int nr_spectra; long int nr_peaks; // Create new consumer, set TIC to zero TICConsumer() : TIC(0.0), nr_spectra(0.0), nr_peaks(0) {} void consumeSpectrum(SpectrumType & s) override { for (Size i = 0; i < s.size(); i++) { TIC += s[i].getIntensity(); } nr_peaks += s.size(); nr_spectra++; } void consumeChromatogram(ChromatogramType& /* c */) override {} void setExpectedSize(Size /* expectedSpectra */, Size /* expectedChromatograms */) override {} void setExperimentalSettings(const ExperimentalSettings& /* exp */) override {} }; /////////////////////////// START_TEST(MzXMLFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MzXMLFile* ptr = nullptr; MzXMLFile* nullPointer = nullptr; START_SECTION((MzXMLFile())) { ptr = new MzXMLFile; TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((~MzXMLFile())) { delete ptr; } END_SECTION START_SECTION(const PeakFileOptions& getOptions() const) { MzXMLFile file; TEST_EQUAL(file.getOptions().hasMSLevels(),false) } END_SECTION START_SECTION(PeakFileOptions& getOptions()) { MzXMLFile file; file.getOptions().addMSLevel(1); TEST_EQUAL(file.getOptions().hasMSLevels(),true); } END_SECTION START_SECTION((template<typename MapType> void load(const String& filename, MapType& map) )) { TOLERANCE_ABSOLUTE(0.01) MzXMLFile file; //exception PeakMap e; TEST_EXCEPTION( Exception::FileNotFound , file.load("dummy/dummy.mzXML",e) ) //real test file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"),e); //test DocumentIdentifier addition TEST_STRING_EQUAL(e.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML")); TEST_STRING_EQUAL(FileTypes::typeToName(e.getLoadedFileType()),"mzXML"); //--------------------------------------------------------------------------- // actual peak data // 60 : (120,100) // 120: (110,100) (120,200) (130,100) // 180: (100,100) (110,200) (120,300) (130,200) (140,100) //--------------------------------------------------------------------------- TEST_EQUAL(e.size(), 4) TEST_EQUAL(e[0].getMSLevel(), 1) TEST_EQUAL(e[1].getMSLevel(), 1) TEST_EQUAL(e[2].getMSLevel(), 1) TEST_EQUAL(e[3].getMSLevel(), 2) TEST_EQUAL(e[0].size(), 1) TEST_EQUAL(e[1].size(), 3) TEST_EQUAL(e[2].size(), 5) TEST_EQUAL(e[3].size(), 5) TEST_STRING_EQUAL(e[0].getNativeID(),"scan=10") TEST_STRING_EQUAL(e[1].getNativeID(),"scan=11") TEST_STRING_EQUAL(e[2].getNativeID(),"scan=12") TEST_STRING_EQUAL(e[3].getNativeID(),"scan=13") TEST_REAL_SIMILAR(e[0][0].getPosition()[0], 120) TEST_REAL_SIMILAR(e[0][0].getIntensity(), 100) TEST_REAL_SIMILAR(e[1][0].getPosition()[0], 110) TEST_REAL_SIMILAR(e[1][0].getIntensity(), 100) TEST_REAL_SIMILAR(e[1][1].getPosition()[0], 120) TEST_REAL_SIMILAR(e[1][1].getIntensity(), 200) TEST_REAL_SIMILAR(e[1][2].getPosition()[0], 130) TEST_REAL_SIMILAR(e[1][2].getIntensity(), 100) TEST_REAL_SIMILAR(e[2][0].getPosition()[0], 100) TEST_REAL_SIMILAR(e[2][0].getIntensity(), 100) TEST_REAL_SIMILAR(e[2][1].getPosition()[0], 110) TEST_REAL_SIMILAR(e[2][1].getIntensity(), 200) TEST_REAL_SIMILAR(e[2][2].getPosition()[0], 120) TEST_REAL_SIMILAR(e[2][2].getIntensity(), 300) TEST_REAL_SIMILAR(e[2][3].getPosition()[0], 130) TEST_REAL_SIMILAR(e[2][3].getIntensity(), 200) TEST_REAL_SIMILAR(e[2][4].getPosition()[0], 140) TEST_REAL_SIMILAR(e[2][4].getIntensity(), 100) TEST_EQUAL(e[0].getMetaValue("URL1"), "www.open-ms.de") TEST_EQUAL(e[0].getMetaValue("URL2"), "www.uni-tuebingen.de") TEST_EQUAL(e[0].getComment(), "Scan Comment") //--------------------------------------------------------------------------- // source file //--------------------------------------------------------------------------- TEST_EQUAL(e.getSourceFiles().size(),2) TEST_STRING_EQUAL(e.getSourceFiles()[0].getNameOfFile(), "File_test_1.raw"); TEST_STRING_EQUAL(e.getSourceFiles()[0].getPathToFile(), ""); TEST_STRING_EQUAL(e.getSourceFiles()[0].getFileType(), "RAWData"); TEST_STRING_EQUAL(e.getSourceFiles()[0].getChecksum(), "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"); TEST_EQUAL(e.getSourceFiles()[0].getChecksumType(),SourceFile::ChecksumType::SHA1) TEST_STRING_EQUAL(e.getSourceFiles()[1].getNameOfFile(), "File_test_2.raw"); TEST_STRING_EQUAL(e.getSourceFiles()[1].getPathToFile(), ""); TEST_STRING_EQUAL(e.getSourceFiles()[1].getFileType(), "processedData"); TEST_STRING_EQUAL(e.getSourceFiles()[1].getChecksum(), "2fd4e1c67a2d28fced849ee1bb76e7391b93eb13"); TEST_EQUAL(e.getSourceFiles()[1].getChecksumType(),SourceFile::ChecksumType::SHA1) //--------------------------------------------------------------------------- // data processing (assigned to each spectrum) //--------------------------------------------------------------------------- for (Size i=0; i<e.size(); ++i) { TEST_EQUAL(e[i].getDataProcessing().size(),2) TEST_EQUAL(e[i].getDataProcessing()[0]->getSoftware().getName(), "MS-X"); TEST_EQUAL(e[i].getDataProcessing()[0]->getSoftware().getVersion(), "1.0"); TEST_STRING_EQUAL(e[i].getDataProcessing()[0]->getMetaValue("#type").toString(), "conversion"); TEST_STRING_EQUAL(e[i].getDataProcessing()[0]->getMetaValue("processing 1").toString(), "done 1"); TEST_STRING_EQUAL(e[i].getDataProcessing()[0]->getMetaValue("processing 2").toString(), "done 2"); TEST_EQUAL(e[i].getDataProcessing()[0]->getCompletionTime().get(), "2001-02-03 04:05:06"); TEST_EQUAL(e[i].getDataProcessing()[0]->getProcessingActions().size(),0) TEST_EQUAL(e[i].getDataProcessing()[1]->getSoftware().getName(), "MS-Y"); TEST_EQUAL(e[i].getDataProcessing()[1]->getSoftware().getVersion(), "1.1"); TEST_STRING_EQUAL(e[i].getDataProcessing()[1]->getMetaValue("#type").toString(), "processing"); TEST_REAL_SIMILAR((double)(e[i].getDataProcessing()[1]->getMetaValue("#intensity_cutoff")), 3.4); TEST_STRING_EQUAL(e[i].getDataProcessing()[1]->getMetaValue("processing 3").toString(), "done 3"); TEST_EQUAL(e[i].getDataProcessing()[1]->getCompletionTime().get(), "0000-00-00 00:00:00"); TEST_EQUAL(e[i].getDataProcessing()[1]->getProcessingActions().size(),3) TEST_EQUAL(e[i].getDataProcessing()[1]->getProcessingActions().count(DataProcessing::DEISOTOPING),1) TEST_EQUAL(e[i].getDataProcessing()[1]->getProcessingActions().count(DataProcessing::CHARGE_DECONVOLUTION),1) TEST_EQUAL(e[i].getDataProcessing()[1]->getProcessingActions().count(DataProcessing::PEAK_PICKING),1) } //--------------------------------------------------------------------------- // instrument //--------------------------------------------------------------------------- const Instrument& inst = e.getInstrument(); TEST_EQUAL(inst.getVendor(), "MS-Vendor") TEST_EQUAL(inst.getModel(), "MS 1") TEST_EQUAL(inst.getMetaValue("URL1"), "www.open-ms.de") TEST_EQUAL(inst.getMetaValue("URL2"), "www.uni-tuebingen.de") TEST_EQUAL(inst.getMetaValue("#comment"), "Instrument Comment") TEST_EQUAL(inst.getName(), "") TEST_EQUAL(inst.getCustomizations(), "") TEST_EQUAL(inst.getIonSources().size(),1) TEST_EQUAL(inst.getIonSources()[0].getIonizationMethod(), IonSource::IonizationMethod::ESI) TEST_EQUAL(inst.getIonSources()[0].getInletType(), IonSource::InletType::INLETNULL) TEST_EQUAL(inst.getIonSources()[0].getPolarity(), IonSource::Polarity::POLNULL) TEST_EQUAL(inst.getIonDetectors().size(),1) TEST_EQUAL(inst.getIonDetectors()[0].getType(), IonDetector::Type::FARADAYCUP) TEST_REAL_SIMILAR(inst.getIonDetectors()[0].getResolution(), 0.0f) TEST_REAL_SIMILAR(inst.getIonDetectors()[0].getADCSamplingFrequency(), 0.0f) TEST_EQUAL(inst.getIonDetectors()[0].getAcquisitionMode(), IonDetector::AcquisitionMode::ACQMODENULL) TEST_EQUAL(inst.getMassAnalyzers().size(), 1) TEST_EQUAL(inst.getMassAnalyzers()[0].getType(), MassAnalyzer::AnalyzerType::PAULIONTRAP) TEST_EQUAL(inst.getMassAnalyzers()[0].getResolutionMethod(), MassAnalyzer::ResolutionMethod::FWHM) TEST_EQUAL(inst.getMassAnalyzers()[0].getResolutionType(), MassAnalyzer::ResolutionType::RESTYPENULL) TEST_EQUAL(inst.getMassAnalyzers()[0].getScanDirection(), MassAnalyzer::ScanDirection::SCANDIRNULL) TEST_EQUAL(inst.getMassAnalyzers()[0].getScanLaw(), MassAnalyzer::ScanLaw::SCANLAWNULL) TEST_EQUAL(inst.getMassAnalyzers()[0].getReflectronState(), MassAnalyzer::ReflectronState::REFLSTATENULL) TEST_EQUAL(inst.getMassAnalyzers()[0].getResolution(), 0.0f) TEST_EQUAL(inst.getMassAnalyzers()[0].getAccuracy(), 0.0f) TEST_EQUAL(inst.getMassAnalyzers()[0].getScanRate(), 0.0f) TEST_EQUAL(inst.getMassAnalyzers()[0].getScanTime(), 0.0f) TEST_EQUAL(inst.getMassAnalyzers()[0].getTOFTotalPathLength(), 0.0f) TEST_EQUAL(inst.getMassAnalyzers()[0].getIsolationWidth(), 0.0f) TEST_EQUAL(inst.getMassAnalyzers()[0].getFinalMSExponent(), 0) TEST_EQUAL(inst.getMassAnalyzers()[0].getMagneticFieldStrength(), 0.0f) TEST_EQUAL(inst.getSoftware().getName(),"MS-Z") TEST_EQUAL(inst.getSoftware().getVersion(),"3.0") //--------------------------------------------------------------------------- // contact persons //--------------------------------------------------------------------------- const vector<ContactPerson>& contacts = e.getContacts(); TEST_EQUAL(contacts.size(),1) TEST_STRING_EQUAL(contacts[0].getFirstName(),"FirstName") TEST_STRING_EQUAL(contacts[0].getLastName(),"LastName") TEST_STRING_EQUAL(contacts[0].getMetaValue("#phone"),"0049") TEST_STRING_EQUAL(contacts[0].getEmail(),"a@b.de") TEST_STRING_EQUAL(contacts[0].getURL(),"http://bla.de") TEST_STRING_EQUAL(contacts[0].getContactInfo(),"") //--------------------------------------------------------------------------- // sample //--------------------------------------------------------------------------- TEST_EQUAL(e.getSample().getName(), "") TEST_EQUAL(e.getSample().getNumber(), "") TEST_EQUAL(e.getSample().getState(), Sample::SampleState::SAMPLENULL) TEST_EQUAL(e.getSample().getMass(), 0.0f) TEST_EQUAL(e.getSample().getVolume(), 0.0f) TEST_EQUAL(e.getSample().getConcentration(), 0.0f) //--------------------------------------------------------------------------- // precursors //--------------------------------------------------------------------------- TEST_EQUAL(e[0].getPrecursors().size(),0) TEST_EQUAL(e[1].getPrecursors().size(),0) TEST_EQUAL(e[2].getPrecursors().size(),0) TEST_EQUAL(e[3].getPrecursors().size(),3) TEST_REAL_SIMILAR(e[3].getPrecursors()[0].getMZ(),101.0) TEST_REAL_SIMILAR(e[3].getPrecursors()[0].getIntensity(),100.0) TEST_REAL_SIMILAR(e[3].getPrecursors()[0].getIsolationWindowLowerOffset(),5) TEST_REAL_SIMILAR(e[3].getPrecursors()[0].getIsolationWindowUpperOffset(),5) TEST_EQUAL(e[3].getPrecursors()[0].getCharge(),1) TEST_REAL_SIMILAR(e[3].getPrecursors()[1].getMZ(),201.0) TEST_REAL_SIMILAR(e[3].getPrecursors()[1].getIntensity(),200.0) TEST_REAL_SIMILAR(e[3].getPrecursors()[1].getIsolationWindowLowerOffset(),10) TEST_REAL_SIMILAR(e[3].getPrecursors()[1].getIsolationWindowUpperOffset(),10) TEST_EQUAL(e[3].getPrecursors()[1].getCharge(),2) TEST_REAL_SIMILAR(e[3].getPrecursors()[2].getMZ(),301.0) TEST_REAL_SIMILAR(e[3].getPrecursors()[2].getIntensity(),300.0) TEST_REAL_SIMILAR(e[3].getPrecursors()[2].getIsolationWindowLowerOffset(),15) TEST_REAL_SIMILAR(e[3].getPrecursors()[2].getIsolationWindowUpperOffset(),15) TEST_EQUAL(e[3].getPrecursors()[2].getCharge(),3) /////////////////////// TESTING SPECIAL CASES /////////////////////// //load a second time to make sure everything is re-initialized correctly PeakMap e2; file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"),e2); TEST_EQUAL(e==e2,true) //test reading 64 bit data PeakMap e3; file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_3_64bit.mzXML"),e3); TEST_EQUAL(e3.size(), 3) TEST_EQUAL(e3[0].getMSLevel(), 1) TEST_EQUAL(e3[1].getMSLevel(), 1) TEST_EQUAL(e3[2].getMSLevel(), 1) TEST_REAL_SIMILAR(e3[0].getRT(), 1) TEST_REAL_SIMILAR(e3[1].getRT(), 121) TEST_REAL_SIMILAR(e3[2].getRT(), 3661) TEST_EQUAL(e3[0].size(), 1) TEST_EQUAL(e3[1].size(), 3) TEST_EQUAL(e3[2].size(), 5) TEST_REAL_SIMILAR(e3[0][0].getPosition()[0], 120) TEST_REAL_SIMILAR(e3[0][0].getIntensity(), 100) TEST_REAL_SIMILAR(e3[1][0].getPosition()[0], 110) TEST_REAL_SIMILAR(e3[1][0].getIntensity(), 100) TEST_REAL_SIMILAR(e3[1][1].getPosition()[0], 120) TEST_REAL_SIMILAR(e3[1][1].getIntensity(), 200) TEST_REAL_SIMILAR(e3[1][2].getPosition()[0], 130) TEST_REAL_SIMILAR(e3[1][2].getIntensity(), 100) TEST_REAL_SIMILAR(e3[2][0].getPosition()[0], 100) TEST_REAL_SIMILAR(e3[2][0].getIntensity(), 100) TEST_REAL_SIMILAR(e3[2][1].getPosition()[0], 110) TEST_REAL_SIMILAR(e3[2][1].getIntensity(), 200) TEST_REAL_SIMILAR(e3[2][2].getPosition()[0], 120) TEST_REAL_SIMILAR(e3[2][2].getIntensity(), 300) TEST_REAL_SIMILAR(e3[2][3].getPosition()[0], 130) TEST_REAL_SIMILAR(e3[2][3].getIntensity(), 200) TEST_REAL_SIMILAR(e3[2][4].getPosition()[0], 140) TEST_REAL_SIMILAR(e3[2][4].getIntensity(), 100) //loading a minimal file containing one spectrum - with whitespaces inside the base64 data PeakMap e4; file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_2_minimal.mzXML"),e4); TEST_EQUAL(e4.size(),1) TEST_EQUAL(e4[0].size(),1) //load one extremely long spectrum - tests CDATA splitting PeakMap e5; file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_4_long.mzXML"),e5); TEST_EQUAL(e5.size(), 1) TEST_EQUAL(e5[0].size(), 997530) //zlib functionality PeakMap zlib; PeakMap none; file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"),none); file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1_compressed.mzXML"),zlib); TEST_EQUAL(zlib==none,true) } END_SECTION START_SECTION(([EXTRA] load with metadata only flag)) { TOLERANCE_ABSOLUTE(0.01) PeakMap e; MzXMLFile file; file.getOptions().setMetadataOnly(true); // real test file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"),e); TEST_EQUAL(e.size(),0) TEST_EQUAL(e.getSourceFiles().size(),2) TEST_STRING_EQUAL(e.getSourceFiles()[0].getNameOfFile(), "File_test_1.raw"); TEST_STRING_EQUAL(e.getSourceFiles()[0].getPathToFile(), ""); TEST_EQUAL(e.getContacts().size(),1) TEST_STRING_EQUAL(e.getContacts()[0].getFirstName(),"FirstName") TEST_STRING_EQUAL( e.getContacts()[0].getLastName(),"LastName") TEST_STRING_EQUAL(e.getSample().getName(), "") TEST_STRING_EQUAL(e.getSample().getNumber(), "") } END_SECTION START_SECTION(([EXTRA] load with selected MS levels)) { TOLERANCE_ABSOLUTE(0.01) PeakMap e; MzXMLFile file; // load only MS level 1 file.getOptions().addMSLevel(1); file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"),e); TEST_EQUAL(e.size(), 3) TEST_EQUAL(e[0].getMSLevel(), 1) TEST_EQUAL(e[1].getMSLevel(), 1) TEST_EQUAL(e[2].getMSLevel(), 1) TEST_EQUAL(e[0].size(), 1) TEST_EQUAL(e[1].size(), 3) TEST_EQUAL(e[2].size(), 5) TEST_STRING_EQUAL(e[0].getNativeID(),"scan=10") TEST_STRING_EQUAL(e[1].getNativeID(),"scan=11") TEST_STRING_EQUAL(e[2].getNativeID(),"scan=12") // load all levels file.getOptions().clearMSLevels(); file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"),e); TEST_EQUAL(e.size(), 4) } END_SECTION START_SECTION(([EXTRA] load with selected MZ range)) { TOLERANCE_ABSOLUTE(0.01) PeakMap e; MzXMLFile file; file.getOptions().setMZRange(makeRange(115,135)); file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"),e); //--------------------------------------------------------------------------- // 60 : +(120,100) // 120: -(110,100) +(120,200) +(130,100) // 180: -(100,100) -(110,200) +(120,300) +(130,200) -(140,100) //--------------------------------------------------------------------------- TEST_EQUAL(e[0].size(), 1) TEST_EQUAL(e[1].size(), 2) TEST_EQUAL(e[2].size(), 2) TEST_REAL_SIMILAR(e[0][0].getPosition()[0], 120) TEST_REAL_SIMILAR(e[0][0].getIntensity(), 100) TEST_REAL_SIMILAR(e[1][0].getPosition()[0], 120) TEST_REAL_SIMILAR(e[1][0].getIntensity(), 200) TEST_REAL_SIMILAR(e[1][1].getPosition()[0], 130) TEST_REAL_SIMILAR(e[1][1].getIntensity(), 100) TEST_REAL_SIMILAR(e[2][0].getPosition()[0], 120) TEST_REAL_SIMILAR(e[2][0].getIntensity(), 300) TEST_REAL_SIMILAR(e[2][1].getPosition()[0], 130) TEST_REAL_SIMILAR(e[2][1].getIntensity(), 200) } END_SECTION START_SECTION(([EXTRA] load with RT range)) { TOLERANCE_ABSOLUTE(0.01) PeakMap e; MzXMLFile file; file.getOptions().setRTRange(makeRange(100, 200)); file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"),e); //--------------------------------------------------------------------------- // 120: (110,100) (120,200) (130,100) // 180: (100,100) (110,200) (120,300) (130,200) (140,100) //--------------------------------------------------------------------------- TEST_EQUAL(e.size(), 2) TEST_EQUAL(e[0].size(), 3) TEST_EQUAL(e[1].size(), 5) TEST_REAL_SIMILAR(e[0][0].getPosition()[0], 110) TEST_REAL_SIMILAR(e[0][0].getIntensity(), 100) TEST_REAL_SIMILAR(e[0][1].getPosition()[0], 120) TEST_REAL_SIMILAR(e[0][1].getIntensity(), 200) TEST_REAL_SIMILAR(e[0][2].getPosition()[0], 130) TEST_REAL_SIMILAR(e[0][2].getIntensity(), 100) TEST_REAL_SIMILAR(e[1][0].getPosition()[0], 100) TEST_REAL_SIMILAR(e[1][0].getIntensity(), 100) TEST_REAL_SIMILAR(e[1][1].getPosition()[0], 110) TEST_REAL_SIMILAR(e[1][1].getIntensity(), 200) TEST_REAL_SIMILAR(e[1][2].getPosition()[0], 120) TEST_REAL_SIMILAR(e[1][2].getIntensity(), 300) TEST_REAL_SIMILAR(e[1][3].getPosition()[0], 130) TEST_REAL_SIMILAR(e[1][3].getIntensity(), 200) TEST_REAL_SIMILAR(e[1][4].getPosition()[0], 140) TEST_REAL_SIMILAR(e[1][4].getIntensity(), 100) } END_SECTION START_SECTION(([EXTRA] load with intensity range)) { TOLERANCE_ABSOLUTE(0.01) PeakMap e; MzXMLFile file; file.getOptions().setIntensityRange(makeRange(150, 350)); file.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"),e); //--------------------------------------------------------------------------- // 60 : -(120,100) // 120: -(110,100) +(120,200) -(130,100) // 180: -(100,100) +(110,200) +(120,300) +(130,200) -(140,100) //--------------------------------------------------------------------------- TEST_EQUAL(e[0].size(), 0) TEST_EQUAL(e[1].size(), 1) TEST_EQUAL(e[2].size(), 3) TEST_REAL_SIMILAR(e[1][0].getPosition()[0], 120) TEST_REAL_SIMILAR(e[1][0].getIntensity(), 200) TEST_REAL_SIMILAR(e[2][0].getPosition()[0], 110) TEST_REAL_SIMILAR(e[2][0].getIntensity(), 200) TEST_REAL_SIMILAR(e[2][1].getPosition()[0], 120) TEST_REAL_SIMILAR(e[2][1].getIntensity(), 300) TEST_REAL_SIMILAR(e[2][2].getPosition()[0], 130) TEST_REAL_SIMILAR(e[2][2].getIntensity(), 200) } END_SECTION START_SECTION(([EXTRA] load/store for nested scans)) { std::string tmp_filename; NEW_TMP_FILE(tmp_filename); MzXMLFile f; PeakMap e2; e2.resize(5); //alternating e2[0].setMSLevel(1); e2[1].setMSLevel(2); e2[2].setMSLevel(1); e2[3].setMSLevel(2); e2[4].setMSLevel(1); f.store(tmp_filename,e2); f.load(tmp_filename,e2); TEST_EQUAL(e2.size(),5); //ending with ms level 2 e2[0].setMSLevel(1); e2[1].setMSLevel(2); e2[2].setMSLevel(1); e2[3].setMSLevel(2); e2[4].setMSLevel(2); f.store(tmp_filename,e2); f.load(tmp_filename,e2); TEST_EQUAL(e2.size(),5); //MS level 1-3 e2[0].setMSLevel(1); e2[1].setMSLevel(2); e2[2].setMSLevel(3); e2[3].setMSLevel(2); e2[4].setMSLevel(3); f.store(tmp_filename,e2); f.load(tmp_filename,e2); TEST_EQUAL(e2.size(),5); //MS level 2 e2[0].setMSLevel(2); e2[1].setMSLevel(2); e2[2].setMSLevel(2); e2[3].setMSLevel(2); e2[4].setMSLevel(2); f.store(tmp_filename,e2); f.load(tmp_filename,e2); TEST_EQUAL(e2.size(),5); //MS level 2-3 e2[0].setMSLevel(2); e2[1].setMSLevel(2); e2[2].setMSLevel(3); e2[3].setMSLevel(2); e2[4].setMSLevel(3); f.store(tmp_filename,e2); f.load(tmp_filename,e2); TEST_EQUAL(e2.size(),5); //MS level 1-3 (not starting with 1) e2[0].setMSLevel(2); e2[1].setMSLevel(1); e2[2].setMSLevel(2); e2[3].setMSLevel(3); e2[4].setMSLevel(1); f.store(tmp_filename,e2); f.load(tmp_filename,e2); TEST_EQUAL(e2.size(),5); } END_SECTION START_SECTION((template<typename MapType> void store(const String& filename, const MapType& map) const )) { std::string tmp_filename; PeakMap e1, e2; MzXMLFile f; NEW_TMP_FILE(tmp_filename); f.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"),e1); TEST_EQUAL(e1.size(), 4) f.store(tmp_filename, e1); f.load(tmp_filename, e2); TEST_TRUE(e1 == e2); } END_SECTION START_SECTION([EXTRA] static bool isValid(const String& filename)) { std::string tmp_filename; MzXMLFile f; PeakMap e; //Note: empty mzXML files are not valid, thus this test is omitted // test if full file is valid NEW_TMP_FILE(tmp_filename); f.load(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"), e); f.store(tmp_filename, e); TEST_EQUAL(f.isValid(tmp_filename, std::cerr), true); } END_SECTION START_SECTION(void transform(const String& filename_in, Interfaces::IMSDataConsumer * consumer, bool skip_full_count = false)) { // Create the consumer, set output file name, transform TICConsumer consumer; MzXMLFile f; String in = OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"); PeakFileOptions opt = f.getOptions(); opt.setFillData(true); // whether to actually load any data opt.setSkipXMLChecks(true); // save time by not checking base64 strings for whitespaces opt.setMaxDataPoolSize(100); opt.setAlwaysAppendData(false); f.setOptions(opt); f.transform(in, &consumer, true); TEST_EQUAL(consumer.nr_spectra, 4) TEST_EQUAL(consumer.nr_peaks, 14) TEST_REAL_SIMILAR(consumer.TIC, 2300) } END_SECTION START_SECTION(void transform(const String& filename_in, Interfaces::IMSDataConsumer * consumer, MapType& map, bool skip_full_count = false) ) { // Create the consumer, set output file name, transform TICConsumer consumer; MzXMLFile f; PeakMap map; String in = OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"); PeakFileOptions opt = f.getOptions(); opt.setFillData(true); // whether to actually load any data opt.setSkipXMLChecks(true); // save time by not checking base64 strings for whitespaces opt.setMaxDataPoolSize(100); opt.setAlwaysAppendData(false); f.setOptions(opt); f.transform(in, &consumer, map, true); TEST_EQUAL(consumer.nr_spectra, 4) TEST_EQUAL(consumer.nr_peaks, 14) TEST_REAL_SIMILAR(consumer.TIC, 2300) TEST_EQUAL(map.getNrSpectra(), 4) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Element_test.cpp
.cpp
5,794
201
// 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/Element.h> #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/CHEMISTRY/ElementDB.h> #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(Element, "$Id$") ///////////////////////////////////////////////////////////// Element* e_ptr = nullptr; Element* e_nullPointer = nullptr; START_SECTION(Element()) e_ptr = new Element; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION(~Element()) delete e_ptr; END_SECTION IsotopeDistribution dist; string name("Name"), symbol("Symbol"); unsigned int atomic_number(43); double average_weight(0.12345); double mono_weight(0.123456789); e_ptr = nullptr; START_SECTION((Element(const string& name, const string& symbol, unsigned int atomic_number, double average_weight, double mono_weight, const IsotopeDistribution& isotopes))) e_ptr = new Element(name, symbol, atomic_number, average_weight, mono_weight, dist); TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION(Element(const Element& element)) Element copy(*e_ptr); TEST_EQUAL(*e_ptr == copy, true) END_SECTION delete e_ptr; e_ptr = new Element; START_SECTION(void setAtomicNumber(unsigned int atomic_number)) e_ptr->setAtomicNumber(atomic_number); NOT_TESTABLE END_SECTION START_SECTION(UInt getAtomicNumber() const) TEST_EQUAL(e_ptr->getAtomicNumber(), atomic_number) END_SECTION START_SECTION(void setName(const string& name)) e_ptr->setName(name); NOT_TESTABLE END_SECTION START_SECTION(const string& getName() const) TEST_EQUAL(e_ptr->getName(), name) END_SECTION START_SECTION(void setSymbol(const string& symbol)) e_ptr->setSymbol(symbol); NOT_TESTABLE END_SECTION START_SECTION(const string& getSymbol() const) TEST_EQUAL(e_ptr->getSymbol(), symbol) END_SECTION START_SECTION(void setIsotopeDistribution(const IsotopeDistribution& isotopes)) e_ptr->setIsotopeDistribution(dist); NOT_TESTABLE END_SECTION START_SECTION((const IsotopeDistribution& getIsotopeDistribution() const)) TEST_EQUAL(e_ptr->getIsotopeDistribution() == dist, true) END_SECTION START_SECTION(void setAverageWeight(double weight)) e_ptr->setAverageWeight(average_weight); NOT_TESTABLE END_SECTION START_SECTION(double getAverageWeight() const) TEST_REAL_SIMILAR(e_ptr->getAverageWeight(), average_weight) END_SECTION START_SECTION(void setMonoWeight(double weight)) e_ptr->setMonoWeight(2.333); NOT_TESTABLE END_SECTION START_SECTION(double getMonoWeight() const) TEST_REAL_SIMILAR(e_ptr->getMonoWeight(), 2.333) END_SECTION START_SECTION(Element& operator = (const Element& element)) Element e = *e_ptr; TEST_EQUAL(e == *e_ptr, true) END_SECTION START_SECTION(bool operator != (const Element& element) const) Element e(*e_ptr); TEST_EQUAL(e != *e_ptr, false) e.setAverageWeight(0.54321); TEST_EQUAL(e != *e_ptr, true) END_SECTION START_SECTION(bool operator == (const Element& element) const) Element e(*e_ptr); TEST_EQUAL(e == *e_ptr, true) e.setAverageWeight(0.54321); TEST_EQUAL(e == *e_ptr, false) END_SECTION START_SECTION(bool operator < (const Element& element) const) const Element * h = ElementDB::getInstance()->getElement("H"); const Element * c = ElementDB::getInstance()->getElement("Carbon"); const Element * o = ElementDB::getInstance()->getElement("O"); const Element * s = ElementDB::getInstance()->getElement("S"); TEST_EQUAL(*h < *c, true) TEST_EQUAL(*c < *o, true) TEST_EQUAL(*c < *c, false) TEST_EQUAL(*s < *c, false) END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// // Hash tests ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] std::hash<Element>)) { // Test that equal objects have equal hashes IsotopeDistribution dist1; dist1.insert(12.0, 0.989); dist1.insert(13.003355, 0.011); Element e1("Carbon", "C", 6, 12.0107, 12.0, dist1); Element e2("Carbon", "C", 6, 12.0107, 12.0, dist1); std::hash<Element> hasher; TEST_EQUAL(e1 == e2, true) TEST_EQUAL(hasher(e1), hasher(e2)) // Test that different objects (likely) have different hashes Element e3("Nitrogen", "N", 7, 14.0067, 14.003074, IsotopeDistribution()); TEST_EQUAL(e1 == e3, false) // Note: Different objects should have different hashes (with very high probability) TEST_NOT_EQUAL(hasher(e1), hasher(e3)) // Test consistency: same object hashes to same value TEST_EQUAL(hasher(e1), hasher(e1)) // Test use in unordered_set std::unordered_set<Element> element_set; element_set.insert(e1); element_set.insert(e2); // Should not increase size (duplicate) element_set.insert(e3); TEST_EQUAL(element_set.size(), 2) TEST_EQUAL(element_set.count(e1), 1) TEST_EQUAL(element_set.count(e3), 1) // Test use in unordered_map std::unordered_map<Element, std::string> element_map; element_map[e1] = "first carbon"; element_map[e2] = "second carbon"; // Should overwrite element_map[e3] = "nitrogen"; TEST_EQUAL(element_map.size(), 2) TEST_EQUAL(element_map[e1], "second carbon") TEST_EQUAL(element_map[e3], "nitrogen") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ProteinIdentification_test.cpp
.cpp
27,614
915
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Nico Pfeifer, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <string> #include <unordered_set> #include <unordered_map> #include <OpenMS/FORMAT/MascotXMLFile.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/DateTime.h> /////////////////////////// START_TEST(ProteinIdentification, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; float protein_significance_threshold = 63.2f; std::vector<ProteinHit> protein_hits; ProteinHit protein_hit; ProteinIdentification protein_identification; MascotXMLFile xml_file; protein_hits.push_back(protein_hit); ProteinIdentification* ptr = nullptr; ProteinIdentification* nullPointer = nullptr; START_SECTION((ProteinIdentification())) ptr = new ProteinIdentification(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~ProteinIdentification())) ProteinIdentification hits; delete ptr; END_SECTION START_SECTION((ProteinIdentification(const ProteinIdentification &source))) ProteinIdentification hits; hits.setDateTime(DateTime::now()); hits.setSignificanceThreshold(protein_significance_threshold); hits.insertHit(protein_hit); hits.setMetaValue("label",17); hits.setIdentifier("id"); hits.setScoreType("score_type"); hits.setHigherScoreBetter(false); hits.setSearchEngine("Mascot"); hits.setSearchEngineVersion("2.1"); ProteinIdentification::SearchParameters param; param.db = "RefSeq"; ProteinIdentification::ProteinGroup g; g.probability = 0.99; g.accessions.push_back("protein0"); g.accessions.push_back("protein3"); hits.insertProteinGroup(g); hits.insertProteinGroup(g); hits.setSearchParameters(param); ProteinIdentification hits2(hits); TEST_EQUAL(hits.getDateTime() == hits2.getDateTime(), true) TEST_EQUAL(hits.getSignificanceThreshold(), hits2.getSignificanceThreshold()) TEST_EQUAL(hits.getHits().size() == 1, true) TEST_EQUAL(hits.getHits()[0].getSequence(), String("")) TEST_EQUAL(hits.getHits()[0] == protein_hit, true) TEST_EQUAL(hits.getProteinGroups().size() == 2, true) TEST_EQUAL(hits.getProteinGroups()[0] == g, true) TEST_EQUAL(hits.getProteinGroups()[1] == g, true) TEST_EQUAL((UInt)hits.getMetaValue("label"), 17) TEST_EQUAL(hits.getIdentifier(), "id") TEST_EQUAL(hits.getScoreType(), "score_type") TEST_EQUAL(hits.isHigherScoreBetter(), false) TEST_EQUAL(hits.getSearchEngine(), "Mascot") TEST_EQUAL(hits.getSearchEngineVersion(), "2.1") TEST_EQUAL(hits.getSearchParameters() == param, true) END_SECTION START_SECTION((ProteinIdentification& operator=(const ProteinIdentification& source))) ProteinIdentification hits; hits.setDateTime(DateTime::now()); hits.setSignificanceThreshold(protein_significance_threshold); hits.insertHit(protein_hit); hits.setIdentifier("id"); hits.setScoreType("score_type"); hits.setHigherScoreBetter(false); hits.setSearchEngine("Mascot"); hits.setSearchEngineVersion("2.1"); ProteinIdentification::ProteinGroup g; g.probability = 0.99; g.accessions.push_back("protein0"); g.accessions.push_back("protein3"); hits.insertProteinGroup(g); ProteinIdentification::SearchParameters param; param.db = "RefSeq"; hits.setSearchParameters(param); ProteinIdentification hits2; hits2 = hits; TEST_EQUAL(hits.getDateTime() == hits2.getDateTime(), true) TEST_EQUAL(hits.getSignificanceThreshold(), hits2.getSignificanceThreshold()) TEST_EQUAL(hits2.getHits().size() == 1, true) TEST_EQUAL(*(hits2.getHits().begin()) == protein_hit, true) TEST_EQUAL(hits2.getProteinGroups().size() == 1, true) TEST_EQUAL(hits2.getProteinGroups()[0] == g, true) TEST_EQUAL(hits2.getIdentifier(), "id") TEST_EQUAL(hits2.getScoreType(), "score_type") TEST_EQUAL(hits2.isHigherScoreBetter(), false) TEST_EQUAL(hits2.getSearchEngine(), "Mascot") TEST_EQUAL(hits2.getSearchEngineVersion(), "2.1") TEST_EQUAL(hits2.getSearchParameters() == param, true) END_SECTION START_SECTION((bool operator==(const ProteinIdentification& rhs) const)) ProteinIdentification search1; ProteinIdentification search2; TEST_TRUE(search1 == search2) search1.setDateTime(DateTime::now()); TEST_EQUAL(search1 == search2, false) search1 = search2; search1.setSignificanceThreshold(protein_significance_threshold); TEST_EQUAL(search1 == search2, false) search1 = search2; search2.setIdentifier("id"); TEST_EQUAL(search1 == search2, false) search1 = search2; search2.setScoreType("score_type"); TEST_EQUAL(search1 == search2, false) search1 = search2; search2.setHigherScoreBetter(false); TEST_EQUAL(search1 == search2, false) search1 = search2; search2.setSearchEngine("Mascot"); TEST_EQUAL(search1 == search2, false) search1 = search2; search2.setSearchEngineVersion("2.1"); TEST_EQUAL(search1 == search2, false) search1 = search2; ProteinIdentification::SearchParameters param; param.db = "RefSeq"; search2.setSearchParameters(param); TEST_EQUAL(search1 == search2, false) search1 = search2; ProteinIdentification::ProteinGroup g; g.probability = 0.99; g.accessions.push_back("protein0"); g.accessions.push_back("protein3"); search2.insertProteinGroup(g); TEST_EQUAL(search1 == search2, false) search1 = search2; END_SECTION START_SECTION((bool operator!=(const ProteinIdentification& rhs) const)) ProteinIdentification search1; ProteinIdentification search2; TEST_EQUAL(search1 != search2, false) search1.setDateTime(DateTime::now()); TEST_FALSE(search1 == search2) //rest does not need to be tested, as it is tested in the operator== test implicitly! END_SECTION START_SECTION((const DateTime& getDateTime() const)) ProteinIdentification hits; DateTime date = DateTime::now(); hits.setDateTime(date); const DateTime& date_time = hits.getDateTime(); TEST_TRUE(date_time == date) END_SECTION START_SECTION((double getSignificanceThreshold() const)) ProteinIdentification hits; hits.setSignificanceThreshold(protein_significance_threshold); TEST_EQUAL(hits.getSignificanceThreshold(), protein_significance_threshold) END_SECTION START_SECTION((const std::vector<ProteinHit>& getHits() const)) ProteinIdentification hits; hits.insertHit(protein_hit); TEST_EQUAL(hits.getHits().size() == 1, true) TEST_EQUAL(*(hits.getHits().begin()) == protein_hit, true) END_SECTION START_SECTION((std::vector<ProteinHit>& getHits())) ProteinIdentification hits; hits.insertHit(protein_hit); TEST_EQUAL(hits.getHits().size() == 1, true) TEST_EQUAL(*(hits.getHits().begin()) == protein_hit, true) END_SECTION START_SECTION((void insertHit(const ProteinHit& input))) ProteinIdentification hits; hits.insertHit(protein_hit); TEST_EQUAL(hits.getHits().size() == 1, true) TEST_EQUAL(*(hits.getHits().begin()) == protein_hit, true) END_SECTION START_SECTION((void setDateTime(const DateTime& date))) ProteinIdentification hits; DateTime date = DateTime::now(); hits.setDateTime(date); TEST_EQUAL(hits.getDateTime() == date, true) END_SECTION START_SECTION((void setSignificanceThreshold(double value))) ProteinIdentification hits; hits.setSignificanceThreshold(protein_significance_threshold); TEST_EQUAL(hits.getSignificanceThreshold(), protein_significance_threshold) END_SECTION START_SECTION((void setHits(const std::vector<ProteinHit> &hits))) ProteinHit hit_1; ProteinHit hit_2; ProteinHit hit_3; vector<ProteinHit> hits; ProteinIdentification id; hit_1.setScore(23); hit_2.setScore(11); hit_3.setScore(45); hit_1.setAccession("SECONDPROTEIN"); hit_2.setAccession("THIRDPROTEIN"); hit_3.setAccession("FIRSTPROTEIN"); hits.push_back(hit_1); hits.push_back(hit_2); hits.push_back(hit_3); id.setHits(hits); TEST_EQUAL(id.getHits()[2].getAccession(), "FIRSTPROTEIN") TEST_EQUAL(id.getHits()[0].getAccession(), "SECONDPROTEIN") TEST_EQUAL(id.getHits()[1].getAccession(), "THIRDPROTEIN") END_SECTION START_SECTION((const String& getScoreType() const)) ProteinIdentification hits; TEST_EQUAL(hits.getScoreType(), "") END_SECTION START_SECTION((void setScoreType(const String& type))) ProteinIdentification hits; hits.setScoreType("bla"); TEST_EQUAL(hits.getScoreType(), "bla") END_SECTION START_SECTION((bool isHigherScoreBetter() const)) ProteinIdentification hits; TEST_EQUAL(hits.isHigherScoreBetter(), true) END_SECTION START_SECTION((void setHigherScoreBetter(bool higher_is_better))) ProteinIdentification hits; hits.setHigherScoreBetter(false); TEST_EQUAL(hits.isHigherScoreBetter(), false) END_SECTION START_SECTION((const String& getIdentifier() const)) ProteinIdentification hits; TEST_EQUAL(hits.getIdentifier(), "") END_SECTION START_SECTION((void setIdentifier(const String& id))) ProteinIdentification hits; hits.setIdentifier("bla"); TEST_EQUAL(hits.getIdentifier(), "bla") END_SECTION START_SECTION((const String& getSearchEngine() const)) ProteinIdentification hits; TEST_EQUAL(hits.getSearchEngine(), "") END_SECTION START_SECTION((void setSearchEngine(const String& search_engine))) ProteinIdentification hits; hits.setIdentifier("bla"); TEST_EQUAL(hits.getIdentifier(), "bla") END_SECTION START_SECTION((const String& getSearchEngineVersion() const)) ProteinIdentification hits; TEST_EQUAL(hits.getSearchEngineVersion(), "") END_SECTION START_SECTION((void setSearchEngineVersion(const String &search_engine_version))) ProteinIdentification hits; hits.setSearchEngineVersion("bla"); TEST_EQUAL(hits.getSearchEngineVersion(), "bla") END_SECTION START_SECTION((const SearchParameters& getSearchParameters() const)) ProteinIdentification hits; TEST_EQUAL(hits.getSearchParameters() == ProteinIdentification::SearchParameters(), true) END_SECTION START_SECTION((void setSearchParameters(const SearchParameters& search_parameters))) ProteinIdentification hits; ProteinIdentification::SearchParameters param; param.db = "Mascot"; hits.setSearchParameters(param); TEST_EQUAL(hits.getSearchParameters() == ProteinIdentification::SearchParameters(), false) END_SECTION START_SECTION((void sort())) { ProteinIdentification id; ProteinHit hit; hit.setScore(23); hit.setAccession("SECONDPROTEIN"); id.insertHit(hit); hit.setScore(45); hit.setAccession("FIRSTPROTEIN"); id.insertHit(hit); hit.setScore(7); hit.setAccession("THIRDPROTEIN"); id.insertHit(hit); //higher score is better id.sort(); TEST_EQUAL(id.getHits()[0].getAccession(), "FIRSTPROTEIN") TEST_EQUAL(id.getHits()[1].getAccession(), "SECONDPROTEIN") TEST_EQUAL(id.getHits()[2].getAccession(), "THIRDPROTEIN") TEST_EQUAL(id.getHits()[0].getScore(), 45) TEST_EQUAL(id.getHits()[1].getScore(), 23) TEST_EQUAL(id.getHits()[2].getScore(), 7) //lower score is better id.setHigherScoreBetter(false); id.sort(); TEST_EQUAL(id.getHits()[0].getAccession(), "THIRDPROTEIN") TEST_EQUAL(id.getHits()[1].getAccession(), "SECONDPROTEIN") TEST_EQUAL(id.getHits()[2].getAccession(), "FIRSTPROTEIN") TEST_EQUAL(id.getHits()[0].getScore(), 7) TEST_EQUAL(id.getHits()[1].getScore(), 23) TEST_EQUAL(id.getHits()[2].getScore(), 45) } { ProteinIdentification id; ProteinHit hit; hit.setScore(45); hit.setAccession("SECONDPROTEIN"); id.insertHit(hit); hit.setScore(7); hit.setAccession("FOURTHPROTEIN"); id.insertHit(hit); hit.setScore(23); hit.setAccession("THIRDPROTEIN"); id.insertHit(hit); hit.setScore(99); hit.setAccession("FIRSTPROTEIN"); id.insertHit(hit); ProteinIdentification::ProteinGroup g1, g2; g1.probability = 0.99; g1.accessions.push_back("FIRSTPROTEIN"); g1.accessions.push_back("FOURTHPROTEIN"); id.insertProteinGroup(g1); g2.probability = 0.96; g2.accessions.push_back("FIRSTPROTEIN"); g2.accessions.push_back("SECONDPROTEIN"); g2.accessions.push_back("THIRDPROTEIN"); id.insertProteinGroup(g2); //higher score is better id.sort(); TEST_EQUAL(id.getHits()[0].getAccession(), "FIRSTPROTEIN") TEST_EQUAL(id.getHits()[1].getAccession(), "SECONDPROTEIN") TEST_EQUAL(id.getHits()[2].getAccession(), "THIRDPROTEIN") TEST_EQUAL(id.getHits()[0].getScore(), 99) TEST_EQUAL(id.getHits()[1].getScore(), 45) TEST_EQUAL(id.getHits()[2].getScore(), 23) TEST_EQUAL(id.getProteinGroups().size(), 2); TEST_EQUAL(id.getProteinGroups()[0] == g1, true); TEST_EQUAL(id.getProteinGroups()[1] == g2, true); } END_SECTION START_SECTION((void sort())) ProteinIdentification id; ProteinHit hit; hit.setScore(23); hit.setAccession("SECONDPROTEIN"); id.insertHit(hit); hit.setScore(45); hit.setAccession("FIRSTPROTEIN"); id.insertHit(hit); hit.setScore(7); hit.setAccession("THIRDPROTEIN"); id.insertHit(hit); id.sort(); TEST_EQUAL(id.getHits()[0].getAccession(), "FIRSTPROTEIN") TEST_EQUAL(id.getHits()[1].getAccession(), "SECONDPROTEIN") TEST_EQUAL(id.getHits()[2].getAccession(), "THIRDPROTEIN") END_SECTION START_SECTION((Size computeCoverage(const PeptideIdentificationList& pep_ids))) ProteinIdentification id; // prep hit ProteinHit hit; hit.setAccession("P1"); hit.setSequence("MKQSTIALALLPLLFTPVTKARTPEMPVLENRAAQGDITAPGGARRLTGDQTAALRDSLS" "DKPAKNIILLIGDGMGDSEITAARNYAEGAGGFFKGIDALPLTGQYTHYALNKKTGKPDY" "VTDSAASATAWSTGVKTYNGALGVDIHEKDHPTILEMAKAAGLATGNVSTAELQDATPAA"); id.insertHit(hit); hit.setAccession("P2"); hit.setSequence("PEMPVLENRAAQGDITAPPGGARRLTGDQTAALRDSLS"); id.insertHit(hit); // prep peptides PeptideIdentificationList pep_ids; PeptideIdentification pid; PeptideHit phit(0, 0, 1, AASequence::fromString("")); PeptideEvidence pe; pe.setProteinAccession("P1"); pe.setStart(0); pe.setEnd(59); phit.addPeptideEvidence(pe); phit.setSequence(AASequence::fromString("MKQSTIALALLPLLFTPVTKARTPEMPVLENRAAQGDITAPGGARRLTGDQTAALRDSLS")); pid.insertHit(phit); pe.setStart(60); pe.setEnd(119); phit.addPeptideEvidence(pe); phit.setSequence(AASequence::fromString("DKPAKNIILLIGDGMGDSEITAARNYAEGAGGFFKGIDALPLTGQYTHYALNKKTGKPDY")); pid.insertHit(phit); pe.setStart(0); pe.setEnd(59); phit.addPeptideEvidence(pe); phit.setSequence(AASequence::fromString("MKQSTIALALLPLLFTPVTKARTPEMPVLENRAAQGDITAPGGARRLTGDQTAALRDSLS")); // should not count pid.insertHit(phit); pep_ids.push_back(pid); PeptideIdentification pid2; PeptideHit phit2(0, 0, 1, AASequence::fromString("")); pe.setStart(0); pe.setEnd(59); phit2.addPeptideEvidence(pe); phit2.setSequence(AASequence::fromString("MKQSTIALALLPLLFTPVTKARTPEMPVLENRAAQGDITAPGGARRLTGDQTAALRDSLS")); pid2.insertHit(phit2); // should not count pep_ids.push_back(pid2); id.computeCoverage(pep_ids); TEST_REAL_SIMILAR(id.getHits()[0].getCoverage(), 200.0 / 3.0); TEST_REAL_SIMILAR(id.getHits()[1].getCoverage(), 0.0); pe.setStart(120); pe.setEnd(179); phit2.addPeptideEvidence(pe); phit2.setSequence(AASequence::fromString("VTDSAASATAWSTGVKTYNGALGVDIHEKDHPTILEMAKAAGLATGNVSTAELQDATPAA")); pid2.insertHit(phit2); pep_ids.push_back(pid2); id.computeCoverage(pep_ids); TEST_REAL_SIMILAR(id.getHits()[0].getCoverage(), 100.0); TEST_REAL_SIMILAR(id.getHits()[1].getCoverage(), 0.0); pep_ids.clear(); PeptideIdentification pid3; PeptideHit phit3(0, 0, 1, AASequence::fromString("")); PeptideEvidence pe2; pe2.setProteinAccession("P2"); pe2.setStart(0); pe2.setEnd(18); phit3.addPeptideEvidence(pe2); phit3.setSequence(AASequence::fromString("PEMPVLENRAAQGDITAPP")); // 1st half pid3.insertHit(phit3); pe2.setStart(19); pe2.setEnd(37); phit3.addPeptideEvidence(pe2); phit3.setSequence(AASequence::fromString("GGARRLTGDQTAALRDSLS")); // 2nd half pid3.insertHit(phit3); pe2.setStart(8); pe2.setEnd(26); phit3.addPeptideEvidence(pe2); phit3.setSequence(AASequence::fromString("RAAQGDITAPPGGARRLTG")); // middle half pid3.insertHit(phit3); pep_ids.push_back(pid3); id.computeCoverage(pep_ids); TEST_REAL_SIMILAR(id.getHits()[0].getCoverage(), 0.0); TEST_REAL_SIMILAR(id.getHits()[1].getCoverage(), 100.0); END_SECTION START_SECTION(([ProteinIdentification::ProteinGroup] ProteinGroup())) ProteinIdentification::ProteinGroup p; TEST_EQUAL(p.probability, 0) TEST_EQUAL(p.accessions.size(), 0) END_SECTION START_SECTION(([ProteinIdentification::ProteinGroup] bool operator==(const ProteinGroup& rhs) const)) ProteinIdentification::ProteinGroup p, p_c; p.probability = 0.5; TEST_NOT_EQUAL(p == p_c, true) p.probability = 0.0; p.accessions.push_back("bla"); TEST_NOT_EQUAL(p == p_c, true) p_c = p; TEST_TRUE(p == p_c) END_SECTION START_SECTION(([ProteinIdentification::ProteinGroup] bool operator<(const ProteinGroup& rhs) const)) { ProteinIdentification::ProteinGroup p1, p2; // both are equal: TEST_EQUAL(p1 < p2, false); TEST_EQUAL(p2 < p1, false); // different probabilities: p1.probability = 0.1; p2.probability = 0.2; TEST_EQUAL(p2 < p1, true); // yes! (see documentation) TEST_EQUAL(p1 < p2, false); // equal again: p2.probability = 0.1; p1.accessions.push_back("bla"); p2.accessions.push_back("bla"); TEST_EQUAL(p1 < p2, false); TEST_EQUAL(p2 < p1, false); // different numbers of accessions: p2.accessions.push_back("blubb"); TEST_EQUAL(p1 < p2, true); TEST_EQUAL(p2 < p1, false); // different accessions: p1.accessions.push_back("laber"); TEST_EQUAL(p1 < p2, false); TEST_EQUAL(p2 < p1, true); } END_SECTION START_SECTION(([ProteinIdentification::SearchParameters] SearchParameters())) ProteinIdentification::SearchParameters sp; TEST_EQUAL(sp.db.size(), 0) TEST_EQUAL(sp.db_version.size(), 0) TEST_EQUAL(sp.taxonomy.size(), 0) TEST_EQUAL(sp.charges.size(), 0) TEST_EQUAL(static_cast<int>(sp.mass_type), static_cast<int>(ProteinIdentification::PeakMassType::MONOISOTOPIC)) TEST_EQUAL(sp.fixed_modifications.size(), 0) TEST_EQUAL(sp.variable_modifications.size(), 0) TEST_EQUAL(sp.digestion_enzyme.getName(), "unknown_enzyme") TEST_EQUAL(sp.missed_cleavages, 0) TEST_EQUAL(sp.fragment_mass_tolerance, 0.0) TEST_EQUAL(sp.fragment_mass_tolerance_ppm, false) TEST_EQUAL(sp.precursor_mass_tolerance, 0.0) TEST_EQUAL(sp.precursor_mass_tolerance_ppm, false) END_SECTION START_SECTION(([ProteinIdentification::SearchParameters] bool operator==(const SearchParameters& rhs) const)) ProteinIdentification::SearchParameters sp, sp_n; sp_n.charges = "1,2,3"; TEST_EQUAL(sp == sp_n, false) END_SECTION START_SECTION(([ProteinIdentification::SearchParameters] bool operator!=(const SearchParameters& rhs) const)) ProteinIdentification::SearchParameters sp, sp_n; sp_n.charges = "1,2,3"; TEST_FALSE(sp == sp_n) END_SECTION START_SECTION(([ProteinIdentification::SearchParameters] pair<int,int> getChargeRange() const)) { ProteinIdentification::SearchParameters sp; sp.charges = "1,2,3"; auto range = sp.getChargeRange(); TEST_EQUAL(range.first, 1); TEST_EQUAL(range.second, 3); sp.charges = "+2-+5"; range = sp.getChargeRange(); TEST_EQUAL(range.first, 2); TEST_EQUAL(range.second, 5); sp.charges = "-1,-2,-3"; range = sp.getChargeRange(); TEST_EQUAL(range.first, -3); TEST_EQUAL(range.second, -1); sp.charges = "2"; range = sp.getChargeRange(); TEST_EQUAL(range.first, 2); TEST_EQUAL(range.second, 2); } END_SECTION START_SECTION((const vector<ProteinGroup>& getProteinGroups() const)) ProteinIdentification id; ProteinIdentification::ProteinGroup g; g.probability = 0.99; g.accessions.push_back("protein0"); g.accessions.push_back("protein3"); id.insertProteinGroup(g); TEST_EQUAL(id.getProteinGroups().size(), 1); TEST_EQUAL(id.getProteinGroups()[0] == g, true); END_SECTION START_SECTION((vector<ProteinGroup>& getProteinGroups())) ProteinIdentification id; ProteinIdentification::ProteinGroup g; g.probability = 0.99; g.accessions.push_back("protein0"); g.accessions.push_back("protein3"); id.insertProteinGroup(g); TEST_EQUAL(id.getProteinGroups().size(), 1); TEST_EQUAL(id.getProteinGroups()[0] == g, true); TEST_EQUAL(id.getProteinGroups()[0].probability, 0.99); END_SECTION START_SECTION((void insertProteinGroup(const ProteinGroup& group))) NOT_TESTABLE //tested above END_SECTION START_SECTION((const vector<ProteinGroup>& getIndistinguishableProteins() const)) ProteinIdentification id; ProteinIdentification::ProteinGroup g; g.accessions.push_back("protein0"); g.accessions.push_back("protein3"); id.insertIndistinguishableProteins(g); TEST_EQUAL(id.getIndistinguishableProteins().size(), 1); TEST_EQUAL(id.getIndistinguishableProteins()[0] == g, true); END_SECTION START_SECTION((vector<ProteinGroup>& getIndistinguishableProteins())) ProteinIdentification id; ProteinIdentification::ProteinGroup g; g.probability = 0.99; g.accessions.push_back("protein0"); g.accessions.push_back("protein3"); id.insertIndistinguishableProteins(g); TEST_EQUAL(id.getIndistinguishableProteins().size(), 1); TEST_EQUAL(id.getIndistinguishableProteins()[0] == g, true); id.getIndistinguishableProteins()[0].accessions.push_back("protein1"); TEST_EQUAL(id.getIndistinguishableProteins()[0].accessions.size(), 3); END_SECTION START_SECTION((void insertIndistinguishableProteins(const ProteinGroup& group))) NOT_TESTABLE //tested above END_SECTION START_SECTION((vector<ProteinHit>::iterator findHit(const String& accession))) { ProteinIdentification protein; ProteinHit hit; hit.setAccession("test1"); protein.insertHit(hit); hit.setAccession("test2"); protein.insertHit(hit); TEST_EQUAL(protein.findHit("test1")->getAccession(), "test1"); TEST_EQUAL(protein.findHit("test2")->getAccession(), "test2"); TEST_EQUAL(protein.findHit("test3") == protein.getHits().end(), true); } END_SECTION START_SECTION((static StringList getAllNamesOfPeakMassType())) StringList names = ProteinIdentification::getAllNamesOfPeakMassType(); size_t expected_size = static_cast<size_t>(ProteinIdentification::PeakMassType::SIZE_OF_PEAKMASSTYPE); size_t mono_idx = static_cast<size_t>(ProteinIdentification::PeakMassType::MONOISOTOPIC); size_t avg_idx = static_cast<size_t>(ProteinIdentification::PeakMassType::AVERAGE); TEST_EQUAL(names.size(), expected_size); TEST_EQUAL(names[mono_idx], "Monoisotopic"); TEST_EQUAL(names[avg_idx], "Average"); END_SECTION ///////////////////////////////////////////////////////////// // Hash function tests ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] std::hash<ProteinIdentification>)) { // Test that equal ProteinIdentifications have equal hashes ProteinIdentification pi1; pi1.setIdentifier("test_id"); pi1.setSearchEngine("Mascot"); pi1.setSearchEngineVersion("2.1"); pi1.setScoreType("Mascot"); pi1.setHigherScoreBetter(true); pi1.setSignificanceThreshold(0.05); ProteinHit hit; hit.setAccession("protein1"); hit.setScore(100.0); pi1.insertHit(hit); ProteinIdentification::ProteinGroup group; group.probability = 0.99; group.accessions.push_back("protein1"); pi1.insertProteinGroup(group); ProteinIdentification::SearchParameters params; params.db = "SwissProt"; params.db_version = "2023.1"; params.charges = "2,3"; params.missed_cleavages = 2; params.fragment_mass_tolerance = 0.5; params.precursor_mass_tolerance = 10.0; pi1.setSearchParameters(params); ProteinIdentification pi2; pi2.setIdentifier("test_id"); pi2.setSearchEngine("Mascot"); pi2.setSearchEngineVersion("2.1"); pi2.setScoreType("Mascot"); pi2.setHigherScoreBetter(true); pi2.setSignificanceThreshold(0.05); pi2.insertHit(hit); pi2.insertProteinGroup(group); pi2.setSearchParameters(params); // Equal objects must have equal hashes std::hash<ProteinIdentification> hasher; TEST_EQUAL(hasher(pi1), hasher(pi2)) // Test that hash changes when content changes ProteinIdentification pi3(pi1); pi3.setIdentifier("different_id"); TEST_NOT_EQUAL(hasher(pi1), hasher(pi3)) // Test use in unordered_set std::unordered_set<ProteinIdentification> pi_set; pi_set.insert(pi1); pi_set.insert(pi2); // Should not add duplicate TEST_EQUAL(pi_set.size(), 1) pi_set.insert(pi3); // Should add different element TEST_EQUAL(pi_set.size(), 2) // Test use in unordered_map std::unordered_map<ProteinIdentification, std::string> pi_map; pi_map[pi1] = "first"; pi_map[pi2] = "second"; // Should overwrite TEST_EQUAL(pi_map.size(), 1) TEST_EQUAL(pi_map[pi1], "second") pi_map[pi3] = "third"; TEST_EQUAL(pi_map.size(), 2) } END_SECTION START_SECTION(([EXTRA] std::hash<ProteinIdentification::ProteinGroup>)) { ProteinIdentification::ProteinGroup g1; g1.probability = 0.95; g1.accessions.push_back("protein1"); g1.accessions.push_back("protein2"); ProteinIdentification::ProteinGroup g2; g2.probability = 0.95; g2.accessions.push_back("protein1"); g2.accessions.push_back("protein2"); // Equal groups must have equal hashes std::hash<ProteinIdentification::ProteinGroup> hasher; TEST_EQUAL(hasher(g1), hasher(g2)) // Test that hash changes when content changes ProteinIdentification::ProteinGroup g3; g3.probability = 0.80; g3.accessions.push_back("protein1"); g3.accessions.push_back("protein2"); TEST_NOT_EQUAL(hasher(g1), hasher(g3)) // Test use in unordered_set std::unordered_set<ProteinIdentification::ProteinGroup> group_set; group_set.insert(g1); group_set.insert(g2); // Should not add duplicate TEST_EQUAL(group_set.size(), 1) group_set.insert(g3); TEST_EQUAL(group_set.size(), 2) } END_SECTION START_SECTION(([EXTRA] std::hash<ProteinIdentification::SearchParameters>)) { ProteinIdentification::SearchParameters sp1; sp1.db = "SwissProt"; sp1.db_version = "2023.1"; sp1.taxonomy = "Homo sapiens"; sp1.charges = "2,3,4"; sp1.mass_type = ProteinIdentification::PeakMassType::MONOISOTOPIC; sp1.fixed_modifications.push_back("Carbamidomethyl (C)"); sp1.variable_modifications.push_back("Oxidation (M)"); sp1.missed_cleavages = 2; sp1.fragment_mass_tolerance = 0.5; sp1.precursor_mass_tolerance = 10.0; ProteinIdentification::SearchParameters sp2; sp2.db = "SwissProt"; sp2.db_version = "2023.1"; sp2.taxonomy = "Homo sapiens"; sp2.charges = "2,3,4"; sp2.mass_type = ProteinIdentification::PeakMassType::MONOISOTOPIC; sp2.fixed_modifications.push_back("Carbamidomethyl (C)"); sp2.variable_modifications.push_back("Oxidation (M)"); sp2.missed_cleavages = 2; sp2.fragment_mass_tolerance = 0.5; sp2.precursor_mass_tolerance = 10.0; // Equal parameters must have equal hashes std::hash<ProteinIdentification::SearchParameters> hasher; TEST_EQUAL(hasher(sp1), hasher(sp2)) // Test that hash changes when content changes ProteinIdentification::SearchParameters sp3(sp1); sp3.db = "TrEMBL"; TEST_NOT_EQUAL(hasher(sp1), hasher(sp3)) // Test use in unordered_set std::unordered_set<ProteinIdentification::SearchParameters> sp_set; sp_set.insert(sp1); sp_set.insert(sp2); // Should not add duplicate TEST_EQUAL(sp_set.size(), 1) sp_set.insert(sp3); TEST_EQUAL(sp_set.size(), 2) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FeatureGroupingAlgorithmUnlabeled_test.cpp
.cpp
1,490
48
// 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/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmUnlabeled.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(FeatureGroupingAlgorithmUnlabeled, "$Id FeatureGroupingAlgorithmUnlabeled_test.C 139 2006-07-14 10:08:39Z ole_st $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FeatureGroupingAlgorithmUnlabeled* ptr = nullptr; FeatureGroupingAlgorithmUnlabeled* nullPointer = nullptr; START_SECTION((FeatureGroupingAlgorithmUnlabeled())) ptr = new FeatureGroupingAlgorithmUnlabeled(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~FeatureGroupingAlgorithmUnlabeled())) delete ptr; END_SECTION START_SECTION((virtual void group(const std::vector< FeatureMap > &maps, ConsensusMap &out))) // This is tested extensively in TEST/TOPP NOT_TESTABLE; END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SpectrumPrecursorComparator_test.cpp
.cpp
2,602
87
// 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/SpectrumPrecursorComparator.h> /////////////////////////// #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/DTAFile.h> using namespace OpenMS; using namespace std; START_TEST(SpectrumPrecursorComparator, "$Id$") ///////////////////////////////////////////////////////////// SpectrumPrecursorComparator* e_ptr = nullptr; SpectrumPrecursorComparator* e_nullPointer = nullptr; START_SECTION(SpectrumPrecursorComparator()) e_ptr = new SpectrumPrecursorComparator; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION(~SpectrumPrecursorComparator()) delete e_ptr; END_SECTION e_ptr = new SpectrumPrecursorComparator(); START_SECTION(SpectrumPrecursorComparator(const SpectrumPrecursorComparator& source)) SpectrumPrecursorComparator copy(*e_ptr); TEST_EQUAL(copy.getName(), e_ptr->getName()) TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) END_SECTION START_SECTION(SpectrumPrecursorComparator& operator = (const SpectrumPrecursorComparator& source)) SpectrumPrecursorComparator copy; copy = *e_ptr; TEST_EQUAL(copy.getName(), e_ptr->getName()) TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) END_SECTION START_SECTION(double operator () (const PeakSpectrum& a, const PeakSpectrum& b) const) DTAFile dta_file; PeakSpectrum spec1; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec1); DTAFile dta_file2; PeakSpectrum spec2; dta_file2.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests_2.dta"), spec2); double score = (*e_ptr)(spec1, spec2); TEST_REAL_SIMILAR(score, 1.7685) score = (*e_ptr)(spec1, spec1); TEST_REAL_SIMILAR(score, 2) END_SECTION START_SECTION(double operator () (const PeakSpectrum& a) const) DTAFile dta_file; PeakSpectrum spec1; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec1); TEST_REAL_SIMILAR((*e_ptr)(spec1), 2.0) END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MRMFeaturePickerFile_test.cpp
.cpp
7,310
148
// 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/MRMFeaturePickerFile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MRMFeaturePickerFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MRMFeaturePickerFile* ptr = nullptr; MRMFeaturePickerFile* null_ptr = nullptr; const String filepath = OPENMS_GET_TEST_DATA_PATH("MRMFeaturePickerFile.csv"); START_SECTION(MRMFeaturePickerFile()) { ptr = new MRMFeaturePickerFile(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~MRMFeaturePickerFile()) { delete ptr; } END_SECTION START_SECTION(void load( const String& filename, std::vector<MRMFeaturePicker::ComponentParams>& cp_list, std::vector<MRMFeaturePicker::ComponentGroupParams>& cgp_list )) { MRMFeaturePickerFile file; std::vector<MRMFeaturePicker::ComponentParams> cp_list; std::vector<MRMFeaturePicker::ComponentGroupParams> cgp_list; file.load(filepath, cp_list, cgp_list); TEST_EQUAL(cp_list.size(), 11) TEST_EQUAL(cgp_list.size(), 5) TEST_EQUAL(cp_list[1].component_name, "arg-L.arg-L_1.Light") TEST_EQUAL(cp_list[1].component_group_name, "arg-L") TEST_EQUAL(cp_list[1].params.getValue("sgolay_frame_length"), 152) TEST_EQUAL(cp_list[1].params.getValue("sgolay_polynomial_order"), 32) TEST_REAL_SIMILAR(cp_list[1].params.getValue("gauss_width"), 0.152) TEST_EQUAL(cp_list[1].params.getValue("use_gauss"), "false") TEST_REAL_SIMILAR(cp_list[1].params.getValue("peak_width"), 0.12) TEST_REAL_SIMILAR(cp_list[1].params.getValue("signal_to_noise"), 0.012) TEST_REAL_SIMILAR(cp_list[1].params.getValue("sn_win_len"), 10002.0) TEST_EQUAL(cp_list[1].params.getValue("sn_bin_count"), 302) TEST_EQUAL(cp_list[1].params.getValue("write_sn_log_messages"), "false") TEST_EQUAL(cp_list[1].params.getValue("remove_overlapping_peaks"), "true") TEST_EQUAL(cp_list[1].params.getValue("method"), "corrected2") TEST_EQUAL(cp_list[9].component_name, "ser-L.ser-L_2.Light") TEST_EQUAL(cp_list[9].component_group_name, "ser-L") TEST_EQUAL(cp_list[9].params.getValue("sgolay_frame_length"), 160) TEST_EQUAL(cp_list[9].params.getValue("sgolay_polynomial_order"), 40) TEST_REAL_SIMILAR(cp_list[9].params.getValue("gauss_width"), 0.16) TEST_EQUAL(cp_list[9].params.getValue("use_gauss"), "false") TEST_REAL_SIMILAR(cp_list[9].params.getValue("peak_width"), 0.2) TEST_REAL_SIMILAR(cp_list[9].params.getValue("signal_to_noise"), 0.02) TEST_REAL_SIMILAR(cp_list[9].params.getValue("sn_win_len"), 10010.0) TEST_EQUAL(cp_list[9].params.getValue("sn_bin_count"), 310) TEST_EQUAL(cp_list[9].params.getValue("write_sn_log_messages"), "false") TEST_EQUAL(cp_list[9].params.getValue("remove_overlapping_peaks"), "true") TEST_EQUAL(cp_list[9].params.getValue("method"), "corrected10") TEST_EQUAL(cp_list[10].component_name, "component2") TEST_EQUAL(cp_list[10].component_group_name, "group2") TEST_EQUAL(cp_list[10].params.getValue("sgolay_polynomial_order"), 43) TEST_REAL_SIMILAR(cp_list[10].params.getValue("gauss_width"), 0.163) TEST_EQUAL(cp_list[10].params.getValue("use_gauss"), "true") TEST_REAL_SIMILAR(cp_list[10].params.getValue("peak_width"), 0.23) TEST_REAL_SIMILAR(cp_list[10].params.getValue("signal_to_noise"), 0.023) TEST_REAL_SIMILAR(cp_list[10].params.getValue("sn_win_len"), 10013.0) TEST_EQUAL(cp_list[10].params.getValue("sn_bin_count"), 313) TEST_EQUAL(cp_list[10].params.getValue("write_sn_log_messages"), "true") TEST_EQUAL(cp_list[10].params.getValue("remove_overlapping_peaks"), "false") TEST_EQUAL(cp_list[10].params.getValue("method"), "corrected13") TEST_EQUAL(cp_list[10].params.exists("sgolay_frame_length"), false) TEST_EQUAL(cgp_list[1].component_group_name, "orn") TEST_EQUAL(cgp_list[1].params.getValue("stop_after_feature"), 6) TEST_REAL_SIMILAR(cgp_list[1].params.getValue("stop_after_intensity_ratio"), 0.0006) TEST_REAL_SIMILAR(cgp_list[1].params.getValue("min_peak_width"), -6.0) TEST_EQUAL(cgp_list[1].params.getValue("peak_integration"), "smoothed3") TEST_EQUAL(cgp_list[1].params.getValue("background_subtraction"), "none3") TEST_EQUAL(cgp_list[1].params.getValue("recalculate_peaks"), "false") TEST_EQUAL(cgp_list[1].params.getValue("use_precursors"), "true") TEST_REAL_SIMILAR(cgp_list[1].params.getValue("recalculate_peaks_max_z"), 3.0) TEST_REAL_SIMILAR(cgp_list[1].params.getValue("minimal_quality"), -10003.0) TEST_REAL_SIMILAR(cgp_list[1].params.getValue("resample_boundary"), 0.03) TEST_EQUAL(cgp_list[1].params.getValue("compute_peak_quality"), "true") TEST_EQUAL(cgp_list[1].params.getValue("compute_peak_shape_metrics"), "false") TEST_EQUAL(cgp_list[3].component_group_name, "ser-L") TEST_EQUAL(cgp_list[3].params.getValue("stop_after_feature"), 16) TEST_REAL_SIMILAR(cgp_list[3].params.getValue("stop_after_intensity_ratio"), 0.0016) TEST_REAL_SIMILAR(cgp_list[3].params.getValue("min_peak_width"), -16.0) TEST_EQUAL(cgp_list[3].params.getValue("peak_integration"), "smoothed8") TEST_EQUAL(cgp_list[3].params.getValue("background_subtraction"), "none8") TEST_EQUAL(cgp_list[3].params.getValue("recalculate_peaks"), "true") TEST_EQUAL(cgp_list[3].params.getValue("use_precursors"), "false") TEST_REAL_SIMILAR(cgp_list[3].params.getValue("recalculate_peaks_max_z"), 8.0) TEST_REAL_SIMILAR(cgp_list[3].params.getValue("minimal_quality"), -10008.0) TEST_REAL_SIMILAR(cgp_list[3].params.getValue("resample_boundary"), 0.08) TEST_EQUAL(cgp_list[3].params.getValue("compute_peak_quality"), "false") TEST_EQUAL(cgp_list[3].params.getValue("compute_peak_shape_metrics"), "true") TEST_EQUAL(cgp_list[4].component_group_name, "group2") TEST_REAL_SIMILAR(cgp_list[4].params.getValue("stop_after_intensity_ratio"), 0.0026) TEST_REAL_SIMILAR(cgp_list[4].params.getValue("min_peak_width"), -26.0) TEST_EQUAL(cgp_list[4].params.getValue("peak_integration"), "smoothed13") TEST_EQUAL(cgp_list[4].params.getValue("background_subtraction"), "none13") TEST_EQUAL(cgp_list[4].params.getValue("recalculate_peaks"), "false") TEST_EQUAL(cgp_list[4].params.getValue("use_precursors"), "true") TEST_REAL_SIMILAR(cgp_list[4].params.getValue("recalculate_peaks_max_z"), 13.0) TEST_REAL_SIMILAR(cgp_list[4].params.getValue("minimal_quality"), -10013.0) TEST_REAL_SIMILAR(cgp_list[4].params.getValue("resample_boundary"), 0.13) TEST_EQUAL(cgp_list[4].params.getValue("compute_peak_quality"), "true") TEST_EQUAL(cgp_list[4].params.getValue("compute_peak_shape_metrics"), "false") TEST_EQUAL(cgp_list[4].params.exists("stop_after_feature"), false) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeptideProteinResolution_test.cpp
.cpp
2,178
69
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Timo Sachsenberg$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/ID/PeptideProteinResolution.h> #include <OpenMS/FORMAT/IdXMLFile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(PeptideProteinResolution, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeptideProteinResolution* ptr = nullptr; PeptideProteinResolution* null_ptr = nullptr; START_SECTION(PeptideProteinResolution()) { ptr = new PeptideProteinResolution(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(static void PeptideProteinResolution::run(vector<ProteinIdentification>& proteins, PeptideIdentificationList& peptides)) { vector<ProteinIdentification> prots; PeptideIdentificationList peps; IdXMLFile idf; idf.load(OPENMS_GET_TEST_DATA_PATH("PeptideProteinResolution_in.idXML"), prots, peps); PeptideProteinResolution::run(prots, peps); std::string tmp_filename; NEW_TMP_FILE(tmp_filename); IdXMLFile().store(tmp_filename, prots, peps); TEST_FILE_SIMILAR(OPENMS_GET_TEST_DATA_PATH("PeptideProteinResolution_out.idXML"), tmp_filename); prots.clear(); peps.clear(); tmp_filename.clear(); NEW_TMP_FILE(tmp_filename); idf.load(OPENMS_GET_TEST_DATA_PATH("PeptideProteinResolution_in2.idXML"), prots, peps); PeptideProteinResolution::run(prots, peps); IdXMLFile().store(tmp_filename, prots, peps); TEST_FILE_SIMILAR(OPENMS_GET_TEST_DATA_PATH("PeptideProteinResolution_out2.idXML"), tmp_filename); } END_SECTION START_SECTION(~PeptideProteinResolution()) { delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MapAlignmentAlgorithmTreeGuided_test.cpp
.cpp
5,955
151
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Julia Thueringer $ // $Authors: Julia Thueringer $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentAlgorithmTreeGuided.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <iostream> using namespace std; using namespace OpenMS; ///////////////////////////////////////////////////////////// START_TEST(MapAlignmentAlgorithmTreeGuided, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MapAlignmentAlgorithmTreeGuided* ptr = nullptr; MapAlignmentAlgorithmTreeGuided* nullPointer = nullptr; START_SECTION((MapAlignmentAlgorithmTreeGuided())) ptr = new MapAlignmentAlgorithmTreeGuided(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~MapAlignmentAlgorithmTreeGuided())) delete ptr; END_SECTION vector<FeatureMap> maps(3); FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MapAlignmentAlgorithmTreeGuided_test_in0.featureXML"), maps[0]); FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MapAlignmentAlgorithmTreeGuided_test_in1.featureXML"), maps[1]); FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MapAlignmentAlgorithmTreeGuided_test_in2.featureXML"), maps[2]); // copy maps for computeTrafosByOriginalRT and computeTransformedFeatureMaps vector<FeatureMap> maps_orig = maps; MapAlignmentAlgorithmTreeGuided aligner; aligner.setLogType(ProgressLogger::CMD); Param params = aligner.getParameters(); aligner.setParameters(params); vector<BinaryTreeNode> result_tree; vector<vector<double>> maps_ranges(3); FeatureMap map_transformed; vector<Size> trafo_order; vector<TransformationDescription> trafos(3); START_SECTION((static void buildTree(std::vector<FeatureMap>& feature_maps, std::vector<BinaryTreeNode>& tree, std::vector<std::vector<double>>& maps_ranges))) { // test of protected nested class PeptideIdentificationsPearsonDistance_ that functions as comparator for ClusterHierarchical with AverageLinkage: // input map in0 and in2 are nearly identical with in2 having larger RT range, in1 has largest rt range and differs in identifications vector<BinaryTreeNode> test_tree; test_tree.emplace_back(0, 2, 1.84834e-04); test_tree.emplace_back(0, 1, 0.505752); OpenMS::MapAlignmentAlgorithmTreeGuided::buildTree(maps, result_tree, maps_ranges); TEST_EQUAL(result_tree.size(), test_tree.size()); for (Size i = 0; i < result_tree.size(); ++i) { TEST_EQUAL(test_tree[i].left_child, result_tree[i].left_child); TEST_EQUAL(test_tree[i].right_child, result_tree[i].right_child); TEST_REAL_SIMILAR(test_tree[i].distance, result_tree[i].distance); } TEST_EQUAL(maps_ranges.size(), 3); // peptide identification counts for indirect test of protected methods extractSeqAndRt_ and addPeptideSequences_ TEST_EQUAL(maps_ranges[0].size(), 6); TEST_EQUAL(maps_ranges[1].size(), 5); TEST_EQUAL(maps_ranges[2].size(), 5); } END_SECTION START_SECTION((void treeGuidedAlignment(const std::vector<BinaryTreeNode>& tree, std::vector<FeatureMap>& feature_maps_transformed, std::vector<std::vector<double>>& maps_ranges, FeatureMap& map_transformed, std::vector<Size>& trafo_order))) { aligner.treeGuidedAlignment(result_tree, maps, maps_ranges, map_transformed, trafo_order); TEST_EQUAL(map_transformed.size(), 15); // contains 3*5 feature from input maps // map_transformed contains all input map feature in order of trafo_order // trafo order should be: (1, (2, 0)), because cluster with larger rt is reference in alignment and other cluster is attached to it TEST_EQUAL(trafo_order[0], 1); TEST_EQUAL(map_transformed[0].getUniqueId(), 20); TEST_EQUAL(trafo_order[2], 0); TEST_EQUAL(map_transformed.back().getUniqueId(), 14); // order of aligned features should correspond to trafo_order // check indirectly with the existence of meta value "original_RT" // RTs of in1 (first 5 features) should be unchanged (no meta value) because map is last cluster and a reference for (Size i = 0; i < 5; ++i) { TEST_EQUAL(map_transformed[i].metaValueExists("original_RT"), false); } // feature RTs of maps 0 and 2 should be corrected -> meta value exists for (Size i = 5; i < 15; ++i) { TEST_EQUAL(map_transformed[i].metaValueExists("original_RT"), true); } } END_SECTION START_SECTION((void computeTrafosByOriginalRT(std::vector<FeatureMap>& feature_maps, FeatureMap& map_transformed, std::vector<TransformationDescription>& transformations, const std::vector<Size>& trafo_order))) { aligner.computeTrafosByOriginalRT(maps_orig, map_transformed, trafos, trafo_order); TEST_EQUAL(trafos.size(), 3); for (Size i = 0; i < maps.size(); ++i) { // first rt in trafo should be the same as in original map Size j = 0; for (auto feature_it = maps_orig[i].begin(); feature_it < maps_orig[i].end(); ++feature_it) { TEST_REAL_SIMILAR(trafos[i].getDataPoints()[j].first, feature_it->getRT()); ++j; } } } END_SECTION START_SECTION((static void computeTransformedFeatureMaps(std::vector<FeatureMap>& feature_maps, const std::vector<TransformationDescription>& transformations))) { OpenMS::MapAlignmentAlgorithmTreeGuided::computeTransformedFeatureMaps(maps_orig, trafos); // check storing of original RTs: for (auto& map : maps_orig) { for (auto feat_it = map.begin(); feat_it < map.end(); ++feat_it) { TEST_EQUAL(feat_it->metaValueExists("original_RT"), true); } } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ChromatogramPeak_test.cpp
.cpp
12,594
426
// 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/ChromatogramPeak.h> /////////////////////////// #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; START_TEST(ChromatogramPeak, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ChromatogramPeak* ptr = nullptr; ChromatogramPeak* nullPointer = nullptr; START_SECTION(ChromatogramPeak()) { ptr = new ChromatogramPeak(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~ChromatogramPeak()) { delete ptr; } END_SECTION START_SECTION((IntensityType getIntensity() const)) TEST_REAL_SIMILAR(ChromatogramPeak().getIntensity(), 0.0) END_SECTION START_SECTION((PositionType const& getPosition() const)) TEST_REAL_SIMILAR(ChromatogramPeak().getPosition()[0], 0.0) END_SECTION START_SECTION((CoordinateType getRT() const)) TEST_REAL_SIMILAR(ChromatogramPeak().getRT(), 0.0) END_SECTION START_SECTION((CoordinateType getPos() const)) TEST_REAL_SIMILAR(ChromatogramPeak().getPos(), 0.0) END_SECTION START_SECTION((void setIntensity(IntensityType intensity))) ChromatogramPeak p; p.setIntensity(17.8f); TEST_REAL_SIMILAR(p.getIntensity(), 17.8) END_SECTION START_SECTION((void setPosition(PositionType const &position))) ChromatogramPeak::PositionType pos; pos[0] = 1.0; ChromatogramPeak p; p.setPosition(pos); TEST_REAL_SIMILAR(p.getPosition()[0], 1.0) END_SECTION START_SECTION((PositionType& getPosition())) ChromatogramPeak::PositionType pos; pos[0] = 1.0; ChromatogramPeak p; p.getPosition() = pos; TEST_REAL_SIMILAR(p.getPosition()[0], 1.0) END_SECTION START_SECTION((void setRT(CoordinateType rt))) ChromatogramPeak p; p.setRT(5.0); TEST_REAL_SIMILAR(p.getRT(), 5.0) END_SECTION START_SECTION((void setPos(CoordinateTypepos))) ChromatogramPeak p; p.setPos(5.0); TEST_REAL_SIMILAR(p.getPos(), 5.0) END_SECTION START_SECTION((ChromatogramPeak(const ChromatogramPeak& p))) ChromatogramPeak::PositionType pos; pos[0] = 21.21; ChromatogramPeak p; p.setIntensity(123.456f); p.setPosition(pos); ChromatogramPeak::PositionType pos2; ChromatogramPeak::IntensityType i2; ChromatogramPeak 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) END_SECTION START_SECTION((ChromatogramPeak(const PositionType retention_time, const IntensityType intensity))) ChromatogramPeak p1(3.0, 5.0); TEST_REAL_SIMILAR(p1.getRT(), 3.0) TEST_REAL_SIMILAR(p1.getIntensity(), 5.0) ChromatogramPeak::PositionType retention_time; retention_time[0] = 2.0; ChromatogramPeak::IntensityType intensity = 4.0; ChromatogramPeak p2(retention_time, intensity); TEST_REAL_SIMILAR(p2.getRT(), 2.0) TEST_REAL_SIMILAR(p2.getIntensity(), 4.0) END_SECTION START_SECTION((ChromatogramPeak& operator = (const ChromatogramPeak& rhs))) ChromatogramPeak::PositionType pos; pos[0] = 21.21; ChromatogramPeak p; p.setIntensity(123.456f); p.setPosition(pos); ChromatogramPeak::PositionType pos2; ChromatogramPeak::IntensityType i2; ChromatogramPeak copy_of_p; copy_of_p = p; i2 = copy_of_p.getIntensity(); pos2 = copy_of_p.getPosition(); TEST_REAL_SIMILAR(i2, 123.456) TEST_REAL_SIMILAR(pos2[0], 21.21) END_SECTION START_SECTION((bool operator == (const ChromatogramPeak& rhs) const)) ChromatogramPeak p1; ChromatogramPeak p2(p1); TEST_TRUE(p1 == p2) p1.setIntensity(5.0f); TEST_EQUAL(p1==p2, false) p2.setIntensity(5.0f); TEST_TRUE(p1 == p2) p1.getPosition()[0]=5; TEST_EQUAL(p1==p2, false) p2.getPosition()[0]=5; TEST_TRUE(p1 == p2) END_SECTION START_SECTION((bool operator != (const ChromatogramPeak& rhs) const)) ChromatogramPeak p1; ChromatogramPeak 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] class PositionLess) std::vector<ChromatogramPeak > v; ChromatogramPeak p; p.getPosition()[0]=3.0; v.push_back(p); p.getPosition()[0]=2.0; v.push_back(p); p.getPosition()[0]=1.0; v.push_back(p); std::sort(v.begin(), v.end(), ChromatogramPeak::PositionLess()); TEST_REAL_SIMILAR(v[0].getPosition()[0], 1.0) TEST_REAL_SIMILAR(v[1].getPosition()[0], 2.0) TEST_REAL_SIMILAR(v[2].getPosition()[0], 3.0) END_SECTION START_SECTION([EXTRA] struct IntensityLess) std::vector<ChromatogramPeak > v; ChromatogramPeak p; p.setIntensity(2.5f); v.push_back(p); p.setIntensity(3.5f); v.push_back(p); p.setIntensity(1.5f); v.push_back(p); std::sort(v.begin(), v.end(), ChromatogramPeak::IntensityLess()); TEST_REAL_SIMILAR(v[0].getIntensity(), 1.5) TEST_REAL_SIMILAR(v[1].getIntensity(), 2.5) TEST_REAL_SIMILAR(v[2].getIntensity(), 3.5) v[0]=v[2]; v[2]=p; std::sort(v.begin(), v.end(), ChromatogramPeak::IntensityLess()); TEST_REAL_SIMILAR(v[0].getIntensity(), 1.5) TEST_REAL_SIMILAR(v[1].getIntensity(), 2.5) TEST_REAL_SIMILAR(v[2].getIntensity(), 3.5) END_SECTION START_SECTION(([ChromatogramPeak::IntensityLess] bool operator()(ChromatogramPeak const &left, ChromatogramPeak const &right) const)) { ChromatogramPeak left,right; left.setIntensity(10.0); right.setIntensity(20.0); TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::IntensityLess] bool operator()(ChromatogramPeak const &left, IntensityType right) const)) { ChromatogramPeak left; left.setIntensity(10.0); ChromatogramPeak::IntensityType right; right = 20.0; TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::IntensityLess] bool operator()(IntensityType left, ChromatogramPeak const &right) const)) { ChromatogramPeak::IntensityType left; left = 10.0; ChromatogramPeak right; right.setIntensity(20.0); TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::IntensityLess] bool operator()(IntensityType left, IntensityType right) const)) { ChromatogramPeak::IntensityType left,right; left = 10.0; right = 20.0; TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::IntensityLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::PositionLess] bool operator()(const ChromatogramPeak &left, const ChromatogramPeak &right) const)) { ChromatogramPeak left,right; left.setPosition(10.0); right.setPosition(20.0); TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::PositionLess] bool operator()(const ChromatogramPeak &left, const PositionType &right) const)) { ChromatogramPeak left; left.setPosition(10.0); ChromatogramPeak::PositionType right; right = 20.0; TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::PositionLess] bool operator()(const PositionType &left, const ChromatogramPeak &right) const)) { ChromatogramPeak::PositionType left; left = 10.0; ChromatogramPeak right; right.setPosition(20.0); TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::PositionLess] bool operator()(const PositionType &left, const PositionType &right) const)) { ChromatogramPeak::PositionType left,right; left = 10.0; right = 20.0; TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::PositionLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::RTLess] bool operator()(const ChromatogramPeak &left, const ChromatogramPeak &right) const)) { ChromatogramPeak left; left.setRT(10.0); ChromatogramPeak right; right.setRT(20.0); TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::RTLess] bool operator()(ChromatogramPeak const &left, CoordinateType right) const)) { ChromatogramPeak left; left.setRT(10.0); ChromatogramPeak::CoordinateType right; right = 20.0; TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::RTLess] bool operator()(CoordinateType left, ChromatogramPeak const &right) const)) { ChromatogramPeak::CoordinateType left; left = 10.0; ChromatogramPeak right; right.setRT(20.0); TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(left,left), false) } END_SECTION START_SECTION(([ChromatogramPeak::RTLess] bool operator()(CoordinateType left, CoordinateType right) const)) { ChromatogramPeak::CoordinateType left; left = 10.0; ChromatogramPeak::CoordinateType right; right = 20.0; TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(left,right), true) TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(right,left), false) TEST_EQUAL(ChromatogramPeak::RTLess().operator ()(left,left), false) } END_SECTION ///////////////////////////////////////////////////////////// // Hash function tests ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] std::hash<ChromatogramPeak>)) { // Test that equal peaks have equal hashes ChromatogramPeak p1, p2; p1.setRT(10.5); p1.setIntensity(1000.0); p2.setRT(10.5); p2.setIntensity(1000.0); std::hash<ChromatogramPeak> hasher; TEST_EQUAL(hasher(p1), hasher(p2)) // Test that hash changes when values change ChromatogramPeak p3; p3.setRT(20.5); p3.setIntensity(1000.0); TEST_NOT_EQUAL(hasher(p1), hasher(p3)) // Test use in unordered_set std::unordered_set<ChromatogramPeak> peak_set; peak_set.insert(p1); TEST_EQUAL(peak_set.size(), 1) peak_set.insert(p2); // same as p1 TEST_EQUAL(peak_set.size(), 1) // should not increase peak_set.insert(p3); TEST_EQUAL(peak_set.size(), 2) // Test use in unordered_map std::unordered_map<ChromatogramPeak, int> peak_map; peak_map[p1] = 42; TEST_EQUAL(peak_map[p1], 42) TEST_EQUAL(peak_map[p2], 42) // p2 == p1, should get same value peak_map[p3] = 99; TEST_EQUAL(peak_map[p3], 99) TEST_EQUAL(peak_map.size(), 2) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GaussTraceFitter_test.cpp
.cpp
12,324
409
// 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/GaussTraceFitter.h> /////////////////////////// #include <OpenMS/KERNEL/Peak1D.h> using namespace OpenMS; using namespace std; START_TEST(GaussTraceFitter, "$Id$") ///////////////////////////////////////////////////////////// typedef GaussTraceFitter GTF; ///////////////////////////////////////////////////////////// FeatureFinderAlgorithmPickedHelperStructs::MassTraces mts; FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt1; mt1.theoretical_int = 0.8; FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt2; mt2.theoretical_int = 0.2; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // set up mass traces to fit Peak1D p1_1; p1_1.setIntensity(1.08268226589f); p1_1.setMZ(1000); mt1.peaks.push_back(make_pair(677.1, &p1_1)); Peak1D p2_1; p2_1.setIntensity(0.270670566473f); p2_1.setMZ(1001); mt2.peaks.push_back(make_pair(677.1, &p2_1)); Peak1D p1_2; p1_2.setIntensity(1.58318959267f); p1_2.setMZ(1000); mt1.peaks.push_back(make_pair(677.4, &p1_2)); Peak1D p2_2; p2_2.setIntensity(0.395797398167f); p2_2.setMZ(1001); mt2.peaks.push_back(make_pair(677.4, &p2_2)); Peak1D p1_3; p1_3.setIntensity(2.22429840363f); p1_3.setMZ(1000); mt1.peaks.push_back(make_pair(677.7, &p1_3)); Peak1D p2_3; p2_3.setIntensity(0.556074600906f); p2_3.setMZ(1001); mt2.peaks.push_back(make_pair(677.7, &p2_3)); Peak1D p1_4; p1_4.setIntensity(3.00248879081f); p1_4.setMZ(1000); mt1.peaks.push_back(make_pair(678, &p1_4)); Peak1D p2_4; p2_4.setIntensity(0.750622197703f); p2_4.setMZ(1001); mt2.peaks.push_back(make_pair(678, &p2_4)); Peak1D p1_5; p1_5.setIntensity(3.89401804768f); p1_5.setMZ(1000); mt1.peaks.push_back(make_pair(678.3, &p1_5)); Peak1D p2_5; p2_5.setIntensity(0.97350451192f); p2_5.setMZ(1001); mt2.peaks.push_back(make_pair(678.3, &p2_5)); Peak1D p1_6; p1_6.setIntensity(4.8522452777f); p1_6.setMZ(1000); mt1.peaks.push_back(make_pair(678.6, &p1_6)); Peak1D p2_6; p2_6.setIntensity(1.21306131943f); p2_6.setMZ(1001); mt2.peaks.push_back(make_pair(678.6, &p2_6)); Peak1D p1_7; p1_7.setIntensity(5.80919229659f); p1_7.setMZ(1000); mt1.peaks.push_back(make_pair(678.9, &p1_7)); Peak1D p2_7; p2_7.setIntensity(1.45229807415f); p2_7.setMZ(1001); mt2.peaks.push_back(make_pair(678.9, &p2_7)); Peak1D p1_8; p1_8.setIntensity(6.68216169129f); p1_8.setMZ(1000); mt1.peaks.push_back(make_pair(679.2, &p1_8)); Peak1D p2_8; p2_8.setIntensity(1.67054042282f); p2_8.setMZ(1001); mt2.peaks.push_back(make_pair(679.2, &p2_8)); Peak1D p1_9; p1_9.setIntensity(7.38493077109f); p1_9.setMZ(1000); mt1.peaks.push_back(make_pair(679.5, &p1_9)); Peak1D p2_9; p2_9.setIntensity(1.84623269277f); p2_9.setMZ(1001); mt2.peaks.push_back(make_pair(679.5, &p2_9)); Peak1D p1_10; p1_10.setIntensity(7.84158938645f); p1_10.setMZ(1000); mt1.peaks.push_back(make_pair(679.8, &p1_10)); Peak1D p2_10; p2_10.setIntensity(1.96039734661f); p2_10.setMZ(1001); mt2.peaks.push_back(make_pair(679.8, &p2_10)); Peak1D p1_11; p1_11.setIntensity(8.0f); p1_11.setMZ(1000); mt1.peaks.push_back(make_pair(680.1, &p1_11)); Peak1D p2_11; p2_11.setIntensity(2.0f); p2_11.setMZ(1001); mt2.peaks.push_back(make_pair(680.1, &p2_11)); Peak1D p1_12; p1_12.setIntensity(7.84158938645f); p1_12.setMZ(1000); mt1.peaks.push_back(make_pair(680.4, &p1_12)); Peak1D p2_12; p2_12.setIntensity(1.96039734661f); p2_12.setMZ(1001); mt2.peaks.push_back(make_pair(680.4, &p2_12)); Peak1D p1_13; p1_13.setIntensity(7.38493077109f); p1_13.setMZ(1000); mt1.peaks.push_back(make_pair(680.7, &p1_13)); Peak1D p2_13; p2_13.setIntensity(1.84623269277f); p2_13.setMZ(1001); mt2.peaks.push_back(make_pair(680.7, &p2_13)); Peak1D p1_14; p1_14.setIntensity(6.68216169129f); p1_14.setMZ(1000); mt1.peaks.push_back(make_pair(681, &p1_14)); Peak1D p2_14; p2_14.setIntensity(1.67054042282f); p2_14.setMZ(1001); mt2.peaks.push_back(make_pair(681, &p2_14)); Peak1D p1_15; p1_15.setIntensity(5.80919229659f); p1_15.setMZ(1000); mt1.peaks.push_back(make_pair(681.3, &p1_15)); Peak1D p2_15; p2_15.setIntensity(1.45229807415f); p2_15.setMZ(1001); mt2.peaks.push_back(make_pair(681.3, &p2_15)); Peak1D p1_16; p1_16.setIntensity(4.8522452777f); p1_16.setMZ(1000); mt1.peaks.push_back(make_pair(681.6, &p1_16)); Peak1D p2_16; p2_16.setIntensity(1.21306131943f); p2_16.setMZ(1001); mt2.peaks.push_back(make_pair(681.6, &p2_16)); Peak1D p1_17; p1_17.setIntensity(3.89401804768f); p1_17.setMZ(1000); mt1.peaks.push_back(make_pair(681.9, &p1_17)); Peak1D p2_17; p2_17.setIntensity(0.97350451192f); p2_17.setMZ(1001); mt2.peaks.push_back(make_pair(681.9, &p2_17)); Peak1D p1_18; p1_18.setIntensity(3.00248879081f); p1_18.setMZ(1000); mt1.peaks.push_back(make_pair(682.2, &p1_18)); Peak1D p2_18; p2_18.setIntensity(0.750622197703f); p2_18.setMZ(1001); mt2.peaks.push_back(make_pair(682.2, &p2_18)); Peak1D p1_19; p1_19.setIntensity(2.22429840363f); p1_19.setMZ(1000); mt1.peaks.push_back(make_pair(682.5, &p1_19)); Peak1D p2_19; p2_19.setIntensity(0.556074600906f); p2_19.setMZ(1001); mt2.peaks.push_back(make_pair(682.5, &p2_19)); Peak1D p1_20; p1_20.setIntensity(1.58318959267f); p1_20.setMZ(1000); mt1.peaks.push_back(make_pair(682.8, &p1_20)); Peak1D p2_20; p2_20.setIntensity(0.395797398167f); p2_20.setMZ(1001); mt2.peaks.push_back(make_pair(682.8, &p2_20)); Peak1D p1_21; p1_21.setIntensity(1.08268226589f); p1_21.setMZ(1000); mt1.peaks.push_back(make_pair(683.1, &p1_21)); Peak1D p2_21; p2_21.setIntensity(0.270670566473f); p2_21.setMZ(1001); mt2.peaks.push_back(make_pair(683.1, &p2_21)); mt1.updateMaximum(); mts.push_back(mt1); mt2.updateMaximum(); mts.push_back(mt2); // fix base line to 0 since we have no baseline here mts.baseline = 0.0; mts.max_trace = 0; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // setup fitter Param p; p.setValue("max_iteration", 500); GTF gaussian_trace_fitter; gaussian_trace_fitter.setParameters(p); gaussian_trace_fitter.fit(mts); double expected_sigma = 1.5; double expected_H = 10.0; double expected_x0 = 680.1; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TOLERANCE_RELATIVE(1.001) GTF* ptr = nullptr; GTF* nullPointer = nullptr; START_SECTION(GaussTraceFitter()) { ptr = new GTF(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~GaussTraceFitter()) { delete ptr; } END_SECTION START_SECTION((GaussTraceFitter(const GaussTraceFitter& other))) { GTF gtf2(gaussian_trace_fitter); TEST_REAL_SIMILAR(gaussian_trace_fitter.getCenter(), gtf2.getCenter()) TEST_REAL_SIMILAR(gaussian_trace_fitter.getHeight(), gtf2.getHeight()) TEST_REAL_SIMILAR(gaussian_trace_fitter.getSigma(), gtf2.getSigma()) TEST_REAL_SIMILAR(gaussian_trace_fitter.getLowerRTBound(), gtf2.getLowerRTBound()) } END_SECTION START_SECTION((GaussTraceFitter& operator=(const GaussTraceFitter& source))) { GTF gtf3 = gaussian_trace_fitter; TEST_REAL_SIMILAR(gaussian_trace_fitter.getCenter(), gtf3.getCenter()) TEST_REAL_SIMILAR(gaussian_trace_fitter.getHeight(), gtf3.getHeight()) TEST_REAL_SIMILAR(gaussian_trace_fitter.getSigma(), gtf3.getSigma()) TEST_REAL_SIMILAR(gaussian_trace_fitter.getLowerRTBound(), gtf3.getLowerRTBound()) } END_SECTION START_SECTION((void fit(FeatureFinderAlgorithmPickedHelperStructs::MassTraces& traces))) { TEST_REAL_SIMILAR(gaussian_trace_fitter.getCenter(), expected_x0) TEST_REAL_SIMILAR(gaussian_trace_fitter.getHeight(), expected_H) TEST_REAL_SIMILAR(gaussian_trace_fitter.getSigma(), expected_sigma) GaussTraceFitter weighted_fitter; Param params = weighted_fitter.getDefaults(); params.setValue("weighted", "true"); weighted_fitter.setParameters(params); weighted_fitter.fit(mts); TEST_REAL_SIMILAR(weighted_fitter.getCenter(), expected_x0) TEST_REAL_SIMILAR(weighted_fitter.getHeight(), expected_H - 0.0035) mts[0].theoretical_int = 0.4; mts[1].theoretical_int = 0.6; weighted_fitter.fit(mts); TEST_REAL_SIMILAR(weighted_fitter.getCenter(), expected_x0) TEST_REAL_SIMILAR(weighted_fitter.getHeight(), 6.0847) } END_SECTION START_SECTION((double getLowerRTBound() const)) { // given sigma this should be // x0_ - 2.5 * sigma_; TEST_REAL_SIMILAR(gaussian_trace_fitter.getLowerRTBound(), expected_x0 - 2.5 * expected_sigma) } END_SECTION START_SECTION((double getUpperRTBound() const)) { // given sigma this should be // x0_ + 2.5 * sigma_; TEST_REAL_SIMILAR(gaussian_trace_fitter.getUpperRTBound(), expected_x0 + 2.5 * expected_sigma) } END_SECTION START_SECTION((double getHeight() const)) { TEST_REAL_SIMILAR(gaussian_trace_fitter.getHeight(), 10.0) } END_SECTION START_SECTION((double getCenter() const)) { TEST_REAL_SIMILAR(gaussian_trace_fitter.getCenter(), 680.1) } END_SECTION START_SECTION((double getSigma() const)) { TEST_REAL_SIMILAR(gaussian_trace_fitter.getSigma(), 1.5) } END_SECTION START_SECTION((bool checkMaximalRTSpan(const double max_rt_span))) { // Maximum RT span in relation to extended area that the model is allowed to have // 5.0 * sigma_ > max_rt_span * region_rt_span_ double region_rt_span = mt1.peaks[mt1.peaks.size() - 1].first - mt1.peaks[0].first; double max_rt_span = 5.0 * gaussian_trace_fitter.getSigma() / region_rt_span + 0.00000000000001; // we add some small number to overcome precision problems on 32-bit machines TEST_EQUAL(gaussian_trace_fitter.checkMaximalRTSpan(max_rt_span), false); max_rt_span -= 0.1; // accept only smaller regions TEST_EQUAL(gaussian_trace_fitter.checkMaximalRTSpan(max_rt_span), true); } END_SECTION START_SECTION((bool checkMinimalRTSpan(const std::pair<double, double> &rt_bounds, const double min_rt_span))) { // is // (rt_bounds.second-rt_bounds.first) < min_rt_span * 5.0 * sigma_; // Minimum RT span in relation to extended area that has to remain after model fitting. pair<double, double> rt_bounds = make_pair(0.0,4.0); double min_rt_span = 0.5; TEST_EQUAL(gaussian_trace_fitter.checkMinimalRTSpan(rt_bounds, min_rt_span), false) min_rt_span += 0.5; TEST_EQUAL(gaussian_trace_fitter.checkMinimalRTSpan(rt_bounds, min_rt_span), true) } END_SECTION START_SECTION((double getValue(double rt) const)) { TEST_REAL_SIMILAR(gaussian_trace_fitter.getValue(expected_x0), expected_H) } END_SECTION START_SECTION((double computeTheoretical(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace& trace, Size k))) { FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt; mt.theoretical_int = 0.8; Peak1D peak; peak.setIntensity(8.0); mt.peaks.push_back(make_pair(expected_x0, &peak)); // theoretical should be expected_H * theoretical_int at position expected_x0 TEST_REAL_SIMILAR(gaussian_trace_fitter.computeTheoretical(mt, 0), mt.theoretical_int * expected_H) } END_SECTION START_SECTION((virtual double getArea())) { // is 2.5... * height_ * sigma_; TEST_REAL_SIMILAR(gaussian_trace_fitter.getArea(), 2.506628 * expected_sigma * expected_H) } END_SECTION START_SECTION((virtual String getGnuplotFormula(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace& trace, const char function_name, const double baseline, const double rt_shift))) { String formula = gaussian_trace_fitter.getGnuplotFormula(mts[0], 'f', 0.0, 0.0); // should look like -- f(x)= 0 + 7.99996 * exp(-0.5*(x-680.1)**2/(1.50001)**2) -- TEST_EQUAL(formula.hasPrefix("f(x)= 0 + "), true) TEST_EQUAL(formula.hasSubstring("exp(-0.5*(x-"), true) TEST_EQUAL(formula.hasSubstring(")**2/("), true) TEST_EQUAL(formula.hasSuffix(")**2)"), true) } END_SECTION START_SECTION((double getFWHM() const)) { TEST_REAL_SIMILAR(gaussian_trace_fitter.getFWHM(), 2.35482 * expected_sigma) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SteinScottImproveScore_test.cpp
.cpp
2,771
104
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Vipul Patel $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <iostream> #include <OpenMS/COMPARISON/SteinScottImproveScore.h> #include <OpenMS/FORMAT/DTAFile.h> #include <OpenMS/PROCESSING/SCALING/Normalizer.h> /////////////////////////// START_TEST(SteinScottImproveScore, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; SteinScottImproveScore* ptr = nullptr; SteinScottImproveScore* nullPointer = nullptr; START_SECTION(SteinScottImproveScore()) ptr = new SteinScottImproveScore(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(virtual ~SteinScottImproveScore()) delete ptr; END_SECTION ptr = new SteinScottImproveScore(); START_SECTION(SteinScottImproveScore(const SteinScottImproveScore& source)) SteinScottImproveScore copy(*ptr); TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); END_SECTION START_SECTION(SteinScottImproveScore& operator = (const SteinScottImproveScore& source)) SteinScottImproveScore copy; copy = *ptr; TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); END_SECTION START_SECTION(double operator () (const PeakSpectrum& spec) const) MSSpectrum spectrum; spectrum.setRT(1); spectrum.setMSLevel(1); for (float mz=500.0; mz<=900; mz+=100.0) { Peak1D peak; peak.setMZ(mz); peak.setIntensity(mz); spectrum.push_back(peak); } double score = (*ptr)(spectrum); if(score >0.99) score =1; TEST_REAL_SIMILAR(score, 1); END_SECTION START_SECTION(double operator () (const PeakSpectrum& spec1, const PeakSpectrum& spec2) const) MSSpectrum spectrum1,spectrum2; spectrum1.setRT(1); spectrum2.setRT(1); spectrum1.setMSLevel(1); spectrum2.setMSLevel(1); for (float mz=500.0; mz<=900; mz+=100.0) { Peak1D peak; peak.setMZ(mz); peak.setIntensity(mz); spectrum1.push_back(peak); spectrum2.push_back(peak); } double score = (*ptr)(spectrum1, spectrum2); if(score >0.99) score =1; TEST_REAL_SIMILAR(score, 1.0) END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SpectrumNativeIDParser_test.cpp
.cpp
10,194
202
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Timo Sachsenberg $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/METADATA/SpectrumNativeIDParser.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(SpectrumNativeIDParser, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION((static bool isNativeID(const String& id))) { // Test recognized native ID prefixes TEST_EQUAL(SpectrumNativeIDParser::isNativeID("scan=123"), true); TEST_EQUAL(SpectrumNativeIDParser::isNativeID("scanId=456"), true); TEST_EQUAL(SpectrumNativeIDParser::isNativeID("scanID=456"), true); // both cases supported TEST_EQUAL(SpectrumNativeIDParser::isNativeID("controllerType=0 controllerNumber=1 scan=100"), true); TEST_EQUAL(SpectrumNativeIDParser::isNativeID("function=2 process=1 scan=100"), true); TEST_EQUAL(SpectrumNativeIDParser::isNativeID("sample=1 period=1 cycle=42 experiment=1"), true); TEST_EQUAL(SpectrumNativeIDParser::isNativeID("index=789"), true); TEST_EQUAL(SpectrumNativeIDParser::isNativeID("spectrum=101112"), true); TEST_EQUAL(SpectrumNativeIDParser::isNativeID("file=42"), true); // Test non-native IDs TEST_EQUAL(SpectrumNativeIDParser::isNativeID("123"), false); TEST_EQUAL(SpectrumNativeIDParser::isNativeID(""), false); TEST_EQUAL(SpectrumNativeIDParser::isNativeID("some_random_string"), false); TEST_EQUAL(SpectrumNativeIDParser::isNativeID("SCAN=123"), false); // case-sensitive } END_SECTION START_SECTION((static std::string getRegExFromNativeID(const String& native_id))) { // Test Thermo format: "controllerType=0 controllerNumber=1 scan=NUMBER" TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID("controllerType=0 controllerNumber=1 scan=100"), R"(scan=(?<GROUP>\d+))"); // Test Waters format: "function= process= scan=NUMBER" TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID("function=2 process=1 scan=100"), R"(scan=(?<GROUP>\d+))"); // Test simple scan format: "scan=NUMBER" TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID("scan=123"), R"(scan=(?<GROUP>\d+))"); // Test index format: "index=NUMBER" TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID("index=456"), R"(index=(?<GROUP>\d+))"); // Test Agilent MassHunter format: "scanId=NUMBER" or "scanID=NUMBER" TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID("scanId=789"), R"(scanId=(?<GROUP>\d+))"); TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID("scanID=789"), R"(scanID=(?<GROUP>\d+))"); // Test spectrum format: "spectrum=NUMBER" TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID("spectrum=101112"), R"(spectrum=(?<GROUP>\d+))"); // Test Bruker FID format: "file=NUMBER" TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID("file=42"), R"(file=(?<GROUP>\d+))"); // Test plain number (fallback) TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID("123"), R"((?<GROUP>\d+))"); // Test unknown format falls back to plain number extraction TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID("unknown=123"), R"((?<GROUP>\d+))"); // Test empty string falls back to plain number extraction TEST_EQUAL(SpectrumNativeIDParser::getRegExFromNativeID(""), R"((?<GROUP>\d+))"); } END_SECTION START_SECTION((static Int extractScanNumber(const String& native_id, const boost::regex& scan_regexp, bool no_error = false))) { // Test successful extraction with spectrum= format boost::regex re_spectrum("spectrum=(?<SCAN>\\d+)"); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("spectrum=42", re_spectrum), 42); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("spectrum=0", re_spectrum), 0); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("spectrum=99999", re_spectrum), 99999); // Test successful extraction with scan= format boost::regex re_scan("scan=(?<SCAN>\\d+)"); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=123", re_scan), 123); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("controllerType=0 controllerNumber=1 scan=456", re_scan), 456); // Test no_error=true returns -1 instead of throwing TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=42", re_spectrum, true), -1); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("no_match_here", re_spectrum, true), -1); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("", re_spectrum, true), -1); // Test exception when no_error=false (default) and no match TEST_EXCEPTION(Exception::ParseError, SpectrumNativeIDParser::extractScanNumber("scan=42", re_spectrum)); TEST_EXCEPTION(Exception::ParseError, SpectrumNativeIDParser::extractScanNumber("no_match", re_spectrum, false)); // Test multiple matches - should return last one boost::regex re_multi("(?<SCAN>\\d+)"); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("1 2 3 42", re_multi), 42); // Test edge cases boost::regex re_index("index=(?<SCAN>\\d+)"); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("index=0", re_index), 0); } END_SECTION START_SECTION((static Int extractScanNumber(const String& native_id, const String& native_id_type_accession))) { // Test Thermo nativeID format (MS:1000768) - scan=NUMBER TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=42", "MS:1000768"), 42); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=0", "MS:1000768"), 0); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("controllerType=0 controllerNumber=1 scan=123", "MS:1000768"), 123); // Test Waters nativeID format (MS:1000769) - function=X process=Y scan=NUMBER TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=42", "MS:1000769"), 42); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("function=1 process=1 scan=99", "MS:1000769"), 99); // Test WIFF nativeID format (MS:1000770) - cycle * 1000 + experiment TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("sample=1 period=1 cycle=42 experiment=1", "MS:1000770"), 42001); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("sample=1 period=1 cycle=1 experiment=999", "MS:1000770"), 1999); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("sample=1 period=1 cycle=100 experiment=50", "MS:1000770"), 100050); // Test Bruker BAF nativeID format (MS:1000771) - scan=NUMBER TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=42", "MS:1000771"), 42); // Test Bruker U2 nativeID format (MS:1000772) - scan=NUMBER TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=42", "MS:1000772"), 42); // Test Bruker FID nativeID format (MS:1000773) - file=NUMBER TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("file=42", "MS:1000773"), 42); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("file=0", "MS:1000773"), 0); // Test multiple spectra per file (MS:1000774) - index=NUMBER -> returns index+1 TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("index=42", "MS:1000774"), 43); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("index=0", "MS:1000774"), 1); // Test single peak list nativeID format (MS:1000775) - file=NUMBER TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("file=42", "MS:1000775"), 42); // Test Thermo/Bruker TDF nativeID format (MS:1000776) - scan=NUMBER TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=42", "MS:1000776"), 42); // Test spectrum identifier nativeID format (MS:1000777) - spectrum=NUMBER TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("spectrum=42", "MS:1000777"), 42); // Test Agilent MassHunter nativeID format (MS:1001508) - scanId=NUMBER TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scanId=42", "MS:1001508"), 42); // Test mzML unique identifier (MS:1001530) - plain NUMBER TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("42", "MS:1001530"), 42); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("0", "MS:1001530"), 0); // Test invalid accession returns -1 TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=42", "MS:9999999"), -1); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=42", "invalid"), -1); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=42", ""), -1); // Test invalid native_id for given accession returns -1 TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("spectrum=42", "MS:1000768"), -1); // expects scan= TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("", "MS:1000768"), -1); TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("malformed", "MS:1000768"), -1); // Test merged spectra - should return last scan number TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("controllerType=0 controllerNumber=1 scan=100 merged controllerType=0 controllerNumber=1 scan=200", "MS:1000768"), 200); } END_SECTION // Additional edge case tests START_SECTION([EXTRA] Edge cases and error handling) { // Test very large numbers TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("scan=999999999", "MS:1000768"), 999999999); // Test whitespace handling in WIFF format TEST_EQUAL(SpectrumNativeIDParser::extractScanNumber("sample=1 period=1 cycle=42 experiment=1", "MS:1000770"), 42001); // Test isNativeID with various whitespace TEST_EQUAL(SpectrumNativeIDParser::isNativeID(" scan=123"), false); // leading space TEST_EQUAL(SpectrumNativeIDParser::isNativeID("scan =123"), false); // space before = // Test getRegExFromNativeID preserves regex structure std::string regex = SpectrumNativeIDParser::getRegExFromNativeID("scan=123"); boost::regex re(regex); boost::smatch match; std::string test = "scan=456"; TEST_EQUAL(boost::regex_search(test, match, re), true); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ResidueModification_test.cpp
.cpp
20,715
642
// 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/ResidueDB.h> #include <OpenMS/CHEMISTRY/ResidueModification.h> #include <OpenMS/CHEMISTRY/Residue.h> #include <OpenMS/CHEMISTRY/ModificationsDB.h> #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(Residue, "$Id$") ///////////////////////////////////////////////////////////// // Modification tests ResidueModification* ptr = nullptr; ResidueModification* nullPointer = nullptr; START_SECTION(ResidueModification()) ptr = new ResidueModification(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~ResidueModification()) delete ptr; END_SECTION ModificationsDB* mod_DB = ModificationsDB::getInstance(); ResidueDB* res_DB = ResidueDB::getInstance(); ptr = new ResidueModification(); START_SECTION(ResidueModification(const ResidueModification& modification)) ResidueModification m(*ptr); TEST_EQUAL(m == *ptr, true) END_SECTION START_SECTION(ResidueModification& operator=(const ResidueModification& modification)) ResidueModification m; m = *ptr; TEST_EQUAL(m == *ptr, true) END_SECTION START_SECTION(bool ResidueModification::operator<(const ResidueModification& rhs) const) ModificationsDB* ptr = ModificationsDB::getInstance(); const ResidueModification* cm = ptr->getModification("Carboxymethyl (C)"); const ResidueModification* pm = ptr->getModification("Phospho (S)"); TEST_EQUAL(*cm < *pm, true); END_SECTION START_SECTION(void setId(const String& id)) ptr->setId("blubb_new_id"); TEST_STRING_EQUAL(ptr->getId(), "blubb_new_id") END_SECTION START_SECTION(const String& getId() const) NOT_TESTABLE END_SECTION START_SECTION(void setFullName(const String& full_name)) ptr->setFullName("blubb_new_full_name"); TEST_STRING_EQUAL(ptr->getFullName(), "blubb_new_full_name") END_SECTION START_SECTION(const String& getFullName() const) NOT_TESTABLE END_SECTION START_SECTION(void setName(const String& name)) ptr->setName("blubb_new_name"); TEST_STRING_EQUAL(ptr->getName(), "blubb_new_name") END_SECTION START_SECTION(const String& getName() const) NOT_TESTABLE END_SECTION START_SECTION((void setNeutralLossDiffFormula(const EmpiricalFormula& loss))) vector<EmpiricalFormula> loss_formulas; loss_formulas.push_back(EmpiricalFormula("H2O2")); ptr->setNeutralLossDiffFormulas(loss_formulas); TEST_EQUAL(ptr->getNeutralLossDiffFormulas()[0] == EmpiricalFormula("H2O2"), true) END_SECTION START_SECTION(const EmpiricalFormula& getNeutralLossDiffFormula() const) NOT_TESTABLE END_SECTION START_SECTION(void setNeutralLossMonoMass(double mono_mass)) vector<double> neutral_loss_mono_masses; neutral_loss_mono_masses.push_back(123.345678); ptr->setNeutralLossMonoMasses(neutral_loss_mono_masses); TEST_REAL_SIMILAR(ptr->getNeutralLossMonoMasses()[0], 123.345678); END_SECTION START_SECTION((double getNeutralLossMonoMass() const)) NOT_TESTABLE END_SECTION START_SECTION((void setNeutralLossAverageMass(double average_mass))) vector<double> neutral_loss_avg_masses; neutral_loss_avg_masses.push_back(23.345678); ptr->setNeutralLossAverageMasses(neutral_loss_avg_masses); TEST_REAL_SIMILAR(ptr->getNeutralLossAverageMasses()[0], 23.345678) END_SECTION START_SECTION(double getNeutralLossAverageMass() const) NOT_TESTABLE END_SECTION START_SECTION((bool hasNeutralLoss() const)) TEST_EQUAL(ptr->hasNeutralLoss(), true) ResidueModification mod; TEST_EQUAL(mod.hasNeutralLoss(), false) vector<EmpiricalFormula> loss_formulas; loss_formulas.push_back(EmpiricalFormula("H2O")); mod.setNeutralLossDiffFormulas(loss_formulas); TEST_EQUAL(mod.hasNeutralLoss(), true) END_SECTION START_SECTION((void setFullId(const String& full_id))) ptr->setFullId("blubb_new_fullid"); TEST_STRING_EQUAL(ptr->getFullId(), "blubb_new_fullid") END_SECTION START_SECTION((const String& getFullId() const)) NOT_TESTABLE END_SECTION START_SECTION((void setUniModRecordId(const Int& id))) ptr->setUniModRecordId(42); TEST_EQUAL(ptr->getUniModRecordId(), 42) END_SECTION START_SECTION((const String& getUniModRecordId() const)) NOT_TESTABLE END_SECTION START_SECTION((const String& getUniModAccession() const)) ptr->setUniModRecordId(42); TEST_STRING_EQUAL(ptr->getUniModAccession(), "UniMod:42") END_SECTION START_SECTION((void setPSIMODAccession(const String& id))) ptr->setPSIMODAccession("blubb_new_PSIMODAccession"); TEST_STRING_EQUAL(ptr->getPSIMODAccession(), "blubb_new_PSIMODAccession") END_SECTION START_SECTION((const String& getPSIMODAccession() const)) NOT_TESTABLE END_SECTION START_SECTION(void setTermSpecificity(TermSpecificity term_spec)) ptr->setTermSpecificity(ResidueModification::ANYWHERE); TEST_EQUAL(ptr->getTermSpecificity(), ResidueModification::ANYWHERE) ptr->setTermSpecificity(ResidueModification::C_TERM); TEST_EQUAL(ptr->getTermSpecificity(), ResidueModification::C_TERM) ptr->setTermSpecificity(ResidueModification::N_TERM); TEST_EQUAL(ptr->getTermSpecificity(), ResidueModification::N_TERM) END_SECTION START_SECTION(void setTermSpecificity(const String& name)) ptr->setTermSpecificity("C-term"); TEST_EQUAL(ptr->getTermSpecificity(), ResidueModification::C_TERM) ptr->setTermSpecificity("N-term"); TEST_EQUAL(ptr->getTermSpecificity(), ResidueModification::N_TERM) ptr->setTermSpecificity("none"); TEST_EQUAL(ptr->getTermSpecificity(), ResidueModification::ANYWHERE) END_SECTION START_SECTION(TermSpecificity getTermSpecificity() const) NOT_TESTABLE END_SECTION START_SECTION(String getTermSpecificityName(TermSpecificity=NUMBER_OF_TERM_SPECIFICITY) const) ptr->setTermSpecificity(ResidueModification::C_TERM); TEST_STRING_EQUAL(ptr->getTermSpecificityName(), "C-term") ptr->setTermSpecificity(ResidueModification::N_TERM); TEST_STRING_EQUAL(ptr->getTermSpecificityName(), "N-term") ptr->setTermSpecificity(ResidueModification::ANYWHERE); TEST_STRING_EQUAL(ptr->getTermSpecificityName(), "none") TEST_STRING_EQUAL(ptr->getTermSpecificityName(ResidueModification::C_TERM), "C-term") TEST_STRING_EQUAL(ptr->getTermSpecificityName(ResidueModification::N_TERM), "N-term") TEST_STRING_EQUAL(ptr->getTermSpecificityName(ResidueModification::ANYWHERE), "none") END_SECTION START_SECTION(void setOrigin(char origin)) ptr->setOrigin('A'); TEST_EQUAL(ptr->getOrigin(), 'A') END_SECTION START_SECTION(char getOrigin() const) NOT_TESTABLE END_SECTION START_SECTION(void setSourceClassification(SourceClassification classification)) ptr->setSourceClassification(ResidueModification::ARTIFACT); TEST_EQUAL(ptr->getSourceClassification(), ResidueModification::ARTIFACT) ptr->setSourceClassification(ResidueModification::NATURAL); TEST_EQUAL(ptr->getSourceClassification(), ResidueModification::NATURAL) ptr->setSourceClassification(ResidueModification::HYPOTHETICAL); TEST_EQUAL(ptr->getSourceClassification(), ResidueModification::HYPOTHETICAL) END_SECTION START_SECTION(void setSourceClassification(const String& classification)) ptr->setSourceClassification("Artifact"); TEST_EQUAL(ptr->getSourceClassification(), ResidueModification::ARTIFACT) ptr->setSourceClassification("Natural"); TEST_EQUAL(ptr->getSourceClassification(), ResidueModification::NATURAL) ptr->setSourceClassification("Hypothetical"); TEST_EQUAL(ptr->getSourceClassification(), ResidueModification::HYPOTHETICAL) END_SECTION START_SECTION(SourceClassification getSourceClassification() const) NOT_TESTABLE END_SECTION START_SECTION(String getSourceClassificationName(SourceClassification classification=NUMBER_OF_SOURCE_CLASSIFICATIONS) const) ptr->setSourceClassification(ResidueModification::ARTIFACT); TEST_STRING_EQUAL(ptr->getSourceClassificationName(), "Artefact") ptr->setSourceClassification(ResidueModification::NATURAL); TEST_STRING_EQUAL(ptr->getSourceClassificationName(), "Natural") ptr->setSourceClassification(ResidueModification::HYPOTHETICAL); TEST_STRING_EQUAL(ptr->getSourceClassificationName(), "Hypothetical") TEST_STRING_EQUAL(ptr->getSourceClassificationName(ResidueModification::ARTIFACT), "Artefact") TEST_STRING_EQUAL(ptr->getSourceClassificationName(ResidueModification::NATURAL), "Natural") TEST_STRING_EQUAL(ptr->getSourceClassificationName(ResidueModification::HYPOTHETICAL), "Hypothetical") END_SECTION START_SECTION(void setAverageMass(double mass)) ptr->setAverageMass(2.0); TEST_REAL_SIMILAR(ptr->getAverageMass(), 2.0) END_SECTION START_SECTION(double getAverageMass() const) NOT_TESTABLE END_SECTION START_SECTION(void setMonoMass(double mass)) ptr->setMonoMass(3.0); TEST_REAL_SIMILAR(ptr->getMonoMass(), 3.0) END_SECTION START_SECTION(double getMonoMass() const) NOT_TESTABLE END_SECTION START_SECTION(void setDiffAverageMass(double mass)) ptr->setDiffAverageMass(4.0); TEST_REAL_SIMILAR(ptr->getDiffAverageMass(), 4.0) END_SECTION START_SECTION(double getDiffAverageMass() const) NOT_TESTABLE END_SECTION START_SECTION(void setDiffMonoMass(double mass)) ptr->setDiffMonoMass(5.0); TEST_REAL_SIMILAR(ptr->getDiffMonoMass(), 5.0) END_SECTION START_SECTION(double getDiffMonoMass() const) NOT_TESTABLE END_SECTION START_SECTION(void setFormula(const String& composition)) ptr->setFormula("blubb_new_formula"); TEST_STRING_EQUAL(ptr->getFormula(), "blubb_new_formula") END_SECTION START_SECTION(const String& getFormula() const) NOT_TESTABLE END_SECTION START_SECTION(void setDiffFormula(const EmpiricalFormula& diff_formula)) EmpiricalFormula ef("C3H4S-3"); ptr->setDiffFormula(ef); TEST_EQUAL(ptr->getDiffFormula() == ef, true) END_SECTION START_SECTION(const EmpiricalFormula& getDiffFormula() const) NOT_TESTABLE END_SECTION START_SECTION(void setSynonyms(const std::set<String>& synonyms)) set<String> synonyms; synonyms.insert("blubb_syn1"); synonyms.insert("blubb_syn2"); ptr->setSynonyms(synonyms); TEST_EQUAL(ptr->getSynonyms() == synonyms, true) END_SECTION START_SECTION(void addSynonym(const String& synonym)) ptr->addSynonym("blubb_syn3"); TEST_EQUAL(ptr->getSynonyms().size(), 3) END_SECTION START_SECTION(const std::set<String>& getSynonyms() const) NOT_TESTABLE END_SECTION START_SECTION(bool operator==(const ResidueModification& modification) const) ResidueModification mod1, mod2; mod1.setId("Id"); TEST_EQUAL(mod1 == mod2, false) mod2.setId("Id"); TEST_TRUE(mod1 == mod2) mod1.setFullName("FullName"); TEST_EQUAL(mod1 == mod2, false) mod2.setFullName("FullName"); TEST_TRUE(mod1 == mod2) mod1.setName("Name"); TEST_EQUAL(mod1 == mod2, false) mod2.setName("Name"); TEST_TRUE(mod1 == mod2) mod1.setTermSpecificity(ResidueModification::N_TERM); TEST_EQUAL(mod1 == mod2, false) mod2.setTermSpecificity(ResidueModification::N_TERM); TEST_TRUE(mod1 == mod2) mod1.setOrigin('C'); TEST_EQUAL(mod1 == mod2, false) mod2.setOrigin('C'); TEST_TRUE(mod1 == mod2) mod1.setSourceClassification(ResidueModification::NATURAL); TEST_EQUAL(mod1 == mod2, false) mod2.setSourceClassification(ResidueModification::NATURAL); TEST_TRUE(mod1 == mod2) mod1.setAverageMass(0.123); TEST_EQUAL(mod1 == mod2, false) mod2.setAverageMass(0.123); TEST_TRUE(mod1 == mod2) mod1.setMonoMass(1.23); TEST_EQUAL(mod1 == mod2, false) mod2.setMonoMass(1.23); TEST_TRUE(mod1 == mod2) mod1.setDiffAverageMass(2.34); TEST_EQUAL(mod1 == mod2, false) mod2.setDiffAverageMass(2.34); TEST_TRUE(mod1 == mod2) mod1.setDiffMonoMass(3.45); TEST_EQUAL(mod1 == mod2, false) mod2.setDiffMonoMass(3.45); TEST_TRUE(mod1 == mod2) mod1.setFormula("C 3 H 4"); TEST_EQUAL(mod1 == mod2, false) mod2.setFormula("C 3 H 4"); TEST_TRUE(mod1 == mod2) mod1.setDiffFormula(EmpiricalFormula("C0H-2N0O0")); TEST_EQUAL(mod1 == mod2, false) mod2.setDiffFormula(EmpiricalFormula("C0H-2N0O0")); TEST_TRUE(mod1 == mod2) mod1.addSynonym("new_syn"); TEST_EQUAL(mod1 == mod2, false) mod2.addSynonym("new_syn"); TEST_TRUE(mod1 == mod2) END_SECTION START_SECTION(bool operator!=(const ResidueModification& modification) const) ResidueModification mod1, mod2; mod1.setId("Id"); TEST_FALSE(mod1 == mod2) mod2.setId("Id"); TEST_EQUAL(mod1 != mod2, false) mod1.setFullName("FullName"); TEST_FALSE(mod1 == mod2) mod2.setFullName("FullName"); TEST_EQUAL(mod1 != mod2, false) mod1.setName("Name"); TEST_FALSE(mod1 == mod2) mod2.setName("Name"); TEST_EQUAL(mod1 != mod2, false) mod1.setTermSpecificity(ResidueModification::N_TERM); TEST_FALSE(mod1 == mod2) mod2.setTermSpecificity(ResidueModification::N_TERM); TEST_EQUAL(mod1 != mod2, false) mod1.setOrigin('C'); TEST_FALSE(mod1 == mod2) mod2.setOrigin('C'); TEST_EQUAL(mod1 != mod2, false) mod1.setSourceClassification(ResidueModification::NATURAL); TEST_FALSE(mod1 == mod2) mod2.setSourceClassification(ResidueModification::NATURAL); TEST_EQUAL(mod1 != mod2, false) mod1.setAverageMass(0.123); TEST_FALSE(mod1 == mod2) mod2.setAverageMass(0.123); TEST_EQUAL(mod1 != mod2, false) mod1.setMonoMass(1.23); TEST_FALSE(mod1 == mod2) mod2.setMonoMass(1.23); TEST_EQUAL(mod1 != mod2, false) mod1.setDiffAverageMass(2.34); TEST_FALSE(mod1 == mod2) mod2.setDiffAverageMass(2.34); TEST_EQUAL(mod1 != mod2, false) mod1.setDiffMonoMass(3.45); TEST_FALSE(mod1 == mod2) mod2.setDiffMonoMass(3.45); TEST_EQUAL(mod1 != mod2, false) mod1.setFormula("C 3 H 4"); TEST_FALSE(mod1 == mod2) mod2.setFormula("C 3 H 4"); TEST_EQUAL(mod1 != mod2, false) mod1.setDiffFormula(EmpiricalFormula("C0H-2N0O0")); TEST_FALSE(mod1 == mod2) mod2.setDiffFormula(EmpiricalFormula("C0H-2N0O0")); TEST_EQUAL(mod1 != mod2, false) mod1.addSynonym("new_syn"); TEST_FALSE(mod1 == mod2) mod2.addSynonym("new_syn"); TEST_EQUAL(mod1 != mod2, false) END_SECTION const ResidueModification* combined_mod; START_SECTION(static const ResidueModification* combineMods(const ResidueModification* base, const std::set<const ResidueModification*>& addons, bool allow_unknown_masses = false, const Residue* residue = nullptr)) const ResidueModification* base = mod_DB->getModification("Phospho (S)"); std::set<const ResidueModification*> addons; addons.insert(mod_DB->getModification("Label:15N(1) (S)")); // boring case: 1 base + 1 addon auto res = ResidueModification::combineMods(base, addons, false, res_DB->getResidue('S')); TEST_EQUAL(res == nullptr, false); TEST_EQUAL(res->getOrigin(), 'S'); TEST_EQUAL(res->getTermSpecificity(), ResidueModification::ANYWHERE); TEST_REAL_SIMILAR(res->getDiffMonoMass(), base->getDiffMonoMass() + (*addons.begin())->getDiffMonoMass()); combined_mod = res; // useful for downstream tests // test empty addons TEST_EQUAL(base, ResidueModification::combineMods(base, {}, false, res_DB->getResidue('S'))); // test empty base + 1 addon res = ResidueModification::combineMods(nullptr, addons, false, res_DB->getResidue('S')); TEST_EQUAL(res, *addons.begin()); // 1 base, 2 addons (1 is invalid) addons.insert(mod_DB->getModification("Label:15N(1) (T)")); TEST_EXCEPTION(Exception::Precondition, ResidueModification::combineMods(base, addons, false, res_DB->getResidue('S'));) // both empty TEST_EQUAL(ResidueModification::combineMods(nullptr, {}, true) == nullptr, true) END_SECTION START_SECTION(String toString() const) const ResidueModification* base = mod_DB->getModification("Phospho (S)"); TEST_EQUAL(base->toString(), "S(Phospho)") TEST_EQUAL(combined_mod->toString(), "S[+80.963365999999994]") END_SECTION START_SECTION(static String getDiffMonoMassString(const double diff_mono_mass)) TEST_EQUAL(ResidueModification::getDiffMonoMassString(16), "+16.0"); TEST_EQUAL(ResidueModification::getDiffMonoMassString(-16), "-16.0"); END_SECTION /// return a string of the form '[+&gt;mass&lt;] (the '+' might be a '-', if mass is negative). START_SECTION(static String getDiffMonoMassWithBracket(const double diff_mono_mass)) TEST_EQUAL(ResidueModification::getDiffMonoMassWithBracket(16), "[+16.0]"); TEST_EQUAL(ResidueModification::getDiffMonoMassWithBracket(-16), "[-16.0]"); END_SECTION /// return a string of the form '[&gt;mass&lt;] START_SECTION(static String getMonoMassWithBracket(const double mono_mass)) TEST_EQUAL(ResidueModification::getDiffMonoMassWithBracket(16), "[+16.0]"); TEST_EXCEPTION(Exception::InvalidValue, ResidueModification::getMonoMassWithBracket(-16)); END_SECTION delete ptr; ///////////////////////////////////////////////////////////// // Hash function tests ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] std::hash<ResidueModification>)) { // Test that equal objects have equal hashes ResidueModification mod1, mod2; std::hash<ResidueModification> hasher; // Default-constructed objects should have equal hashes TEST_EQUAL(hasher(mod1), hasher(mod2)) // Set various fields and verify equal objects still have equal hashes mod1.setId("TestId"); mod2.setId("TestId"); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setFullName("TestFullName"); mod2.setFullName("TestFullName"); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setName("TestName"); mod2.setName("TestName"); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setTermSpecificity(ResidueModification::N_TERM); mod2.setTermSpecificity(ResidueModification::N_TERM); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setOrigin('M'); mod2.setOrigin('M'); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setSourceClassification(ResidueModification::NATURAL); mod2.setSourceClassification(ResidueModification::NATURAL); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setAverageMass(15.9994); mod2.setAverageMass(15.9994); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setMonoMass(15.994915); mod2.setMonoMass(15.994915); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setDiffAverageMass(15.9994); mod2.setDiffAverageMass(15.9994); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setDiffMonoMass(15.994915); mod2.setDiffMonoMass(15.994915); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setFormula("O"); mod2.setFormula("O"); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.setDiffFormula(EmpiricalFormula("O")); mod2.setDiffFormula(EmpiricalFormula("O")); TEST_EQUAL(hasher(mod1), hasher(mod2)) mod1.addSynonym("Syn1"); mod2.addSynonym("Syn1"); TEST_EQUAL(hasher(mod1), hasher(mod2)) vector<EmpiricalFormula> nl_formulas; nl_formulas.push_back(EmpiricalFormula("H2O")); mod1.setNeutralLossDiffFormulas(nl_formulas); mod2.setNeutralLossDiffFormulas(nl_formulas); TEST_EQUAL(hasher(mod1), hasher(mod2)) vector<double> nl_mono_masses; nl_mono_masses.push_back(18.01056); mod1.setNeutralLossMonoMasses(nl_mono_masses); mod2.setNeutralLossMonoMasses(nl_mono_masses); TEST_EQUAL(hasher(mod1), hasher(mod2)) vector<double> nl_avg_masses; nl_avg_masses.push_back(18.0153); mod1.setNeutralLossAverageMasses(nl_avg_masses); mod2.setNeutralLossAverageMasses(nl_avg_masses); TEST_EQUAL(hasher(mod1), hasher(mod2)) // Verify that different objects have different hashes ResidueModification mod3; mod3.setId("DifferentId"); TEST_NOT_EQUAL(hasher(mod1), hasher(mod3)) // Test use in unordered_set std::unordered_set<ResidueModification> mod_set; mod_set.insert(mod1); mod_set.insert(mod2); // Should not add duplicate TEST_EQUAL(mod_set.size(), 1) mod_set.insert(mod3); TEST_EQUAL(mod_set.size(), 2) TEST_EQUAL(mod_set.count(mod1), 1) TEST_EQUAL(mod_set.count(mod3), 1) // Test use in unordered_map std::unordered_map<ResidueModification, int> mod_map; mod_map[mod1] = 1; mod_map[mod3] = 3; TEST_EQUAL(mod_map.size(), 2) TEST_EQUAL(mod_map[mod1], 1) TEST_EQUAL(mod_map[mod2], 1) // mod2 equals mod1 TEST_EQUAL(mod_map[mod3], 3) // Test with modifications from database const ResidueModification* phospho = mod_DB->getModification("Phospho (S)"); const ResidueModification* oxidation = mod_DB->getModification("Oxidation (M)"); TEST_NOT_EQUAL(phospho, nullPointer) TEST_NOT_EQUAL(oxidation, nullPointer) // Same modification should have same hash ResidueModification phospho_copy(*phospho); TEST_EQUAL(hasher(phospho_copy), hasher(*phospho)) // Different modifications should have different hashes TEST_NOT_EQUAL(hasher(*phospho), hasher(*oxidation)) } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IdXMLFile_test.cpp
.cpp
13,125
277
// 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/IdXMLFile.h> #include <OpenMS/CONCEPT/FuzzyStringComparator.h> /////////////////////////// START_TEST(IdXMLFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; START_SECTION((IdXMLFile())) IdXMLFile* ptr = nullptr; IdXMLFile* nullPointer = nullptr; ptr = new IdXMLFile(); TEST_NOT_EQUAL(ptr,nullPointer) delete ptr; END_SECTION START_SECTION(void load(const String& filename, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids) ) std::vector<ProteinIdentification> protein_ids; PeptideIdentificationList peptide_ids; IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IdXMLFile_whole.idXML"), protein_ids, peptide_ids); TEST_EQUAL(protein_ids.size(),2) TEST_EQUAL(peptide_ids.size(),3) END_SECTION START_SECTION(void load(const String& filename, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids, String& document_id) ) std::vector<ProteinIdentification> protein_ids; PeptideIdentificationList peptide_ids; String document_id; IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IdXMLFile_whole.idXML"), protein_ids, peptide_ids, document_id); TEST_STRING_EQUAL(document_id,"LSID1234") TEST_EQUAL(protein_ids.size(),2) TEST_EQUAL(peptide_ids.size(),3) /////////////// protein id 1 ////////////////// TEST_EQUAL(protein_ids[0].getScoreType(),"MOWSE") TEST_EQUAL(protein_ids[0].isHigherScoreBetter(),true) TEST_EQUAL(protein_ids[0].getSearchEngine(),"Mascot") TEST_EQUAL(protein_ids[0].getSearchEngineVersion(),"2.1.0") TEST_EQUAL(protein_ids[0].getDateTime().getDate(),"2006-01-12") TEST_EQUAL(protein_ids[0].getDateTime().getTime(),"12:13:14") TEST_EQUAL(protein_ids[0].getIdentifier().hasPrefix("Mascot_2006-01-12T12:13:14"), true) TEST_EQUAL(protein_ids[0].getSearchParameters().db,"MSDB") TEST_EQUAL(protein_ids[0].getSearchParameters().db_version,"1.0") TEST_EQUAL(protein_ids[0].getSearchParameters().charges,"1, 2") TEST_EQUAL(protein_ids[0].getSearchParameters().mass_type,ProteinIdentification::PeakMassType::AVERAGE) TEST_REAL_SIMILAR(protein_ids[0].getSearchParameters().fragment_mass_tolerance,0.3) TEST_REAL_SIMILAR(protein_ids[0].getSearchParameters().precursor_mass_tolerance,1.0) TEST_EQUAL((String)(protein_ids[0].getMetaValue("name")),"ProteinIdentification") TEST_EQUAL(protein_ids[0].getProteinGroups().size(), 1); TEST_EQUAL(protein_ids[0].getProteinGroups()[0].probability, 0.88); TEST_EQUAL(protein_ids[0].getProteinGroups()[0].accessions.size(), 2); TEST_EQUAL(protein_ids[0].getProteinGroups()[0].accessions[0], "PROT1"); TEST_EQUAL(protein_ids[0].getProteinGroups()[0].accessions[1], "PROT2"); TEST_EQUAL(protein_ids[0].getIndistinguishableProteins().size(), 1); TEST_EQUAL(protein_ids[0].getIndistinguishableProteins()[0].accessions.size(), 2); TEST_EQUAL(protein_ids[0].getIndistinguishableProteins()[0].accessions[0], "PROT1"); TEST_EQUAL(protein_ids[0].getIndistinguishableProteins()[0].accessions[1], "PROT2"); TEST_EQUAL(protein_ids[0].getHits().size(),2) //protein hit 1 TEST_REAL_SIMILAR(protein_ids[0].getHits()[0].getScore(),34.4) TEST_EQUAL(protein_ids[0].getHits()[0].getAccession(),"PROT1") TEST_EQUAL(protein_ids[0].getHits()[0].getSequence(),"ABCDEFG") TEST_EQUAL((String)(protein_ids[0].getHits()[0].getMetaValue("name")),"ProteinHit") //protein hit 2 TEST_REAL_SIMILAR(protein_ids[0].getHits()[1].getScore(),24.4) TEST_EQUAL(protein_ids[0].getHits()[1].getAccession(),"PROT2") TEST_EQUAL(protein_ids[0].getHits()[1].getSequence(),"ABCDEFG") //peptide id 1 TEST_EQUAL(peptide_ids[0].getScoreType(),"MOWSE") TEST_EQUAL(peptide_ids[0].isHigherScoreBetter(),false) TEST_EQUAL(peptide_ids[0].getIdentifier().hasPrefix("Mascot_2006-01-12T12:13:14"), true) TEST_REAL_SIMILAR(peptide_ids[0].getMZ(),675.9) TEST_REAL_SIMILAR(peptide_ids[0].getRT(),1234.5) TEST_EQUAL((peptide_ids[0].getSpectrumReference()),"17") TEST_EQUAL((String)(peptide_ids[0].getMetaValue("name")),"PeptideIdentification") TEST_EQUAL(peptide_ids[0].getHits().size(),2) //peptide hit 1 TEST_REAL_SIMILAR(peptide_ids[0].getHits()[0].getScore(),0.9) TEST_EQUAL(peptide_ids[0].getHits()[0].getSequence(), AASequence::fromString("PEPTIDER")) TEST_EQUAL(peptide_ids[0].getHits()[0].getCharge(),1) vector<PeptideEvidence> pes0 = peptide_ids[0].getHits()[0].getPeptideEvidences(); TEST_EQUAL(pes0.size(),2) TEST_EQUAL(pes0[0].getProteinAccession(),"PROT1") TEST_EQUAL(pes0[1].getProteinAccession(),"PROT2") TEST_EQUAL(pes0[0].getAABefore(),'A') TEST_EQUAL(pes0[0].getAAAfter(),'B') TEST_EQUAL((String)(peptide_ids[0].getHits()[0].getMetaValue("name")),"PeptideHit") //peptide hit 2 TEST_REAL_SIMILAR(peptide_ids[0].getHits()[1].getScore(),1.4) vector<PeptideEvidence> pes1 = peptide_ids[0].getHits()[1].getPeptideEvidences(); TEST_EQUAL(peptide_ids[0].getHits()[1].getSequence(), AASequence::fromString("PEPTIDERR")) TEST_EQUAL(peptide_ids[0].getHits()[1].getCharge(),1) TEST_EQUAL(pes1.size(),0) //peptide id 2 TEST_EQUAL(peptide_ids[1].getScoreType(),"MOWSE") TEST_EQUAL(peptide_ids[1].isHigherScoreBetter(),true) TEST_EQUAL(peptide_ids[1].getIdentifier().hasPrefix("Mascot_2006-01-12T12:13:14"), true) TEST_EQUAL(peptide_ids[1].getHits().size(),2) //peptide hit 1 TEST_REAL_SIMILAR(peptide_ids[1].getHits()[0].getScore(),44.4) TEST_EQUAL(peptide_ids[1].getHits()[0].getSequence(), AASequence::fromString("PEPTIDERRR")) TEST_EQUAL(peptide_ids[1].getHits()[0].getCharge(),2) vector<PeptideEvidence> pes2 = peptide_ids[1].getHits()[0].getPeptideEvidences(); TEST_EQUAL(pes2.size(),0) //peptide hit 2 TEST_REAL_SIMILAR(peptide_ids[1].getHits()[1].getScore(),33.3) TEST_EQUAL(peptide_ids[1].getHits()[1].getSequence(), AASequence::fromString("PEPTIDERRRR")) TEST_EQUAL(peptide_ids[1].getHits()[1].getCharge(),2) vector<PeptideEvidence> pes3 = peptide_ids[1].getHits()[1].getPeptideEvidences(); TEST_EQUAL(pes3.size(),0) /////////////// protein id 2 ////////////////// TEST_EQUAL(protein_ids[1].getScoreType(),"MOWSE") TEST_EQUAL(protein_ids[1].isHigherScoreBetter(),true) TEST_EQUAL(protein_ids[1].getSearchEngine(),"Mascot") TEST_EQUAL(protein_ids[1].getSearchEngineVersion(),"2.1.1") TEST_EQUAL(protein_ids[1].getDateTime().getDate(),"2007-01-12") TEST_EQUAL(protein_ids[1].getDateTime().getTime(),"12:13:14") TEST_EQUAL(protein_ids[1].getIdentifier().hasPrefix("Mascot_2007-01-12T12:13:14"), true) TEST_EQUAL(protein_ids[1].getSearchParameters().db,"MSDB") TEST_EQUAL(protein_ids[1].getSearchParameters().db_version,"1.1") TEST_EQUAL(protein_ids[1].getSearchParameters().charges,"1, 2, 3") TEST_EQUAL(protein_ids[1].getSearchParameters().mass_type,ProteinIdentification::PeakMassType::MONOISOTOPIC) TEST_REAL_SIMILAR(protein_ids[1].getSearchParameters().fragment_mass_tolerance,0.3) TEST_REAL_SIMILAR(protein_ids[1].getSearchParameters().precursor_mass_tolerance,1.0) TEST_EQUAL(protein_ids[1].getSearchParameters().fixed_modifications.size(),2) TEST_EQUAL(protein_ids[1].getSearchParameters().fixed_modifications[0],"Fixed") TEST_EQUAL(protein_ids[1].getSearchParameters().fixed_modifications[1],"Fixed2") TEST_EQUAL(protein_ids[1].getSearchParameters().variable_modifications.size(),2) TEST_EQUAL(protein_ids[1].getSearchParameters().variable_modifications[0],"Variable") TEST_EQUAL(protein_ids[1].getSearchParameters().variable_modifications[1],"Variable2") TEST_EQUAL(protein_ids[1].getHits().size(),1) //protein hit 1 TEST_REAL_SIMILAR(protein_ids[1].getHits()[0].getScore(),100.0) TEST_EQUAL(protein_ids[1].getHits()[0].getAccession(),"PROT3") TEST_EQUAL(protein_ids[1].getHits()[0].getSequence(),"") //peptide id 3 TEST_EQUAL(peptide_ids[2].getScoreType(),"MOWSE") TEST_EQUAL(peptide_ids[2].isHigherScoreBetter(),true) TEST_EQUAL(peptide_ids[2].getIdentifier().hasPrefix("Mascot_2007-01-12T12:13:14"), true) TEST_EQUAL(peptide_ids[2].getHits().size(),1) //peptide hit 1 TEST_REAL_SIMILAR(peptide_ids[2].getHits()[0].getScore(),1.4) TEST_EQUAL(peptide_ids[2].getHits()[0].getSequence(), AASequence::fromString("PEPTIDERRRRR")) TEST_EQUAL(peptide_ids[2].getHits()[0].getCharge(),1) vector<PeptideEvidence> pes4 = peptide_ids[2].getHits()[0].getPeptideEvidences(); TEST_EQUAL(pes4.size(),1) TEST_EQUAL(pes4[0].getProteinAccession(),"PROT3") TEST_EQUAL(pes4[0].getAABefore(), PeptideEvidence::UNKNOWN_AA) TEST_EQUAL(pes4[0].getAAAfter(), PeptideEvidence::UNKNOWN_AA) END_SECTION START_SECTION(void store(String filename, const std::vector<ProteinIdentification>& protein_ids, const PeptideIdentificationList& peptide_ids, const String& document_id="") ) // load, store, and reload data std::vector<ProteinIdentification> protein_ids, protein_ids2; PeptideIdentificationList peptide_ids, peptide_ids2; String document_id, document_id2; String target_file = OPENMS_GET_TEST_DATA_PATH("IdXMLFile_whole.idXML"); IdXMLFile().load(target_file, protein_ids2, peptide_ids2, document_id2); String actual_file; NEW_TMP_FILE(actual_file) IdXMLFile().store(actual_file, protein_ids2, peptide_ids2, document_id2); FuzzyStringComparator fuzzy; fuzzy.setWhitelist(ListUtils::create<String>("<?xml-stylesheet")); fuzzy.setAcceptableAbsolute(0.0001); bool result = fuzzy.compareFiles(actual_file, target_file); TEST_EQUAL(result, true); END_SECTION START_SECTION([EXTRA] static bool isValid(const String& filename)) std::vector<ProteinIdentification> protein_ids, protein_ids2; PeptideIdentificationList peptide_ids, peptide_ids2; String filename; IdXMLFile f; //test if empty file is valid NEW_TMP_FILE(filename) f.store(filename, protein_ids2, peptide_ids2); TEST_EQUAL(f.isValid(filename, std::cerr),true); //test if full file is valid NEW_TMP_FILE(filename); String document_id; f.load(OPENMS_GET_TEST_DATA_PATH("IdXMLFile_whole.idXML"), protein_ids2, peptide_ids2, document_id); protein_ids2[0].setMetaValue("stringvalue",String("bla")); protein_ids2[0].setMetaValue("intvalue",4711); protein_ids2[0].setMetaValue("floatvalue",5.3); f.store(filename, protein_ids2, peptide_ids2); TEST_EQUAL(f.isValid(filename, std::cerr),true); //check if meta information can be loaded f.load(filename, protein_ids2, peptide_ids2, document_id); END_SECTION START_SECTION(([EXTRA] No protein identification bug)) IdXMLFile id_xmlfile; vector<ProteinIdentification> protein_ids; PeptideIdentificationList peptide_ids; id_xmlfile.load(OPENMS_GET_TEST_DATA_PATH("IdXMLFile_no_proteinhits.idXML"), protein_ids, peptide_ids); TEST_EQUAL(protein_ids.size(), 1) TEST_EQUAL(protein_ids[0].getHits().size(), 0) TEST_EQUAL(peptide_ids.size(), 10) TEST_EQUAL(peptide_ids[0].getHits().size(), 1) String filename; NEW_TMP_FILE(filename) id_xmlfile.store(filename , protein_ids, peptide_ids); vector<ProteinIdentification> protein_ids2; PeptideIdentificationList peptide_ids2; id_xmlfile.load(filename, protein_ids2, peptide_ids2); // identifiers contain a random number when loaded to avoid ambiguities when merging ProtIDs; make them equal for our purposes here protein_ids2[0].setIdentifier(protein_ids[0].getIdentifier()); for (auto& pep : peptide_ids2) { pep.setIdentifier(peptide_ids[0].getIdentifier()); } TEST_TRUE(protein_ids == protein_ids2) TEST_TRUE(peptide_ids == peptide_ids2) END_SECTION START_SECTION(([EXTRA] XLMS data labeled cross-linker)) vector<ProteinIdentification> protein_ids; PeptideIdentificationList peptide_ids; String input_file= OPENMS_GET_TEST_DATA_PATH("IdXML_XLMS_labelled.idXML"); IdXMLFile().load(input_file, protein_ids, peptide_ids); TEST_EQUAL(peptide_ids[0].getHits()[0].getPeakAnnotations()[0].annotation, "[alpha|ci$b2]") TEST_EQUAL(peptide_ids[0].getHits()[0].getPeakAnnotations()[0].charge, 1) TEST_EQUAL(peptide_ids[0].getHits()[0].getPeakAnnotations()[1].annotation, "[alpha|ci$b2]") TEST_EQUAL(peptide_ids[0].getHits()[0].getPeakAnnotations()[8].annotation, "[alpha|xi$b8]") TEST_EQUAL(peptide_ids[0].getHits()[0].getPeakAnnotations()[20].annotation, "[alpha|xi$b9]") TEST_EQUAL(peptide_ids[0].getHits()[0].getPeakAnnotations()[25].charge, 3) TEST_EQUAL(peptide_ids[0].getHits()[0].getPeakAnnotations()[25].annotation, "[alpha|xi$y8]") END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ListUtilsIO_test.cpp
.cpp
903
29
// 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/DATASTRUCTURES/ListUtilsIO.h> using namespace OpenMS; using namespace std; START_TEST(ListUtilsIO, "$Id$") START_SECTION(([EXTRA] template<typename StringType> StringList& operator<<(StringList& sl, const StringType& string))) StringList list; list << "a" << "b" << "c" << "a"; TEST_EQUAL(list.size(),4) ABORT_IF(list.size() != 4) TEST_STRING_EQUAL(list[0],"a") TEST_STRING_EQUAL(list[1],"b") TEST_STRING_EQUAL(list[2],"c") TEST_STRING_EQUAL(list[3],"a") END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IdentificationData_test.cpp
.cpp
26,442
715
// 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/SYSTEM/SysInfo.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/METADATA/ID/IdentificationData.h> #include <OpenMS/CHEMISTRY/ProteaseDB.h> #include <type_traits> // to check if movable /////////////////////////// START_TEST(IdentificationData, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; using ID = IdentificationData; IdentificationData* ptr = nullptr; IdentificationData* null = nullptr; START_SECTION((IdentificationData())) ptr = new IdentificationData(); TEST_NOT_EQUAL(ptr, null); END_SECTION START_SECTION((movable)) TEST_TRUE(std::is_nothrow_move_constructible_v<IdentificationData>); TEST_TRUE(std::is_nothrow_move_assignable_v<IdentificationData>); END_SECTION START_SECTION((~IdentificationData())) delete ptr; END_SECTION IdentificationData data; ID::InputFileRef file_ref; ID::ProcessingSoftwareRef sw_ref; ID::SearchParamRef param_ref; ID::ProcessingStepRef step_ref; ID::ScoreTypeRef score_ref; ID::ObservationRef obs_ref; ID::ParentSequenceRef protein_ref, rna_ref; ID::IdentifiedPeptideRef peptide_ref; ID::IdentifiedOligoRef oligo_ref; ID::IdentifiedCompoundRef compound_ref; ID::AdductRef adduct_ref; ID::ObservationMatchRef match_ref1, match_ref2, match_ref3; START_SECTION((const InputFiles& getInputFiles() const)) { TEST_EQUAL(data.getInputFiles().empty(), true); // tested further below } END_SECTION START_SECTION((InputFileRef registerInputFile(const InputFile& file))) { ID::InputFile file("test.mzML"); file_ref = data.registerInputFile(file); TEST_EQUAL(data.getInputFiles().size(), 1); TEST_STRING_EQUAL(file_ref->name, file.name); // re-registering doesn't lead to redundant entries: data.registerInputFile(file); TEST_EQUAL(data.getInputFiles().size(), 1); } END_SECTION START_SECTION((const ProcessingSoftwares& getProcessingSoftwares() const)) { TEST_EQUAL(data.getProcessingSoftwares().empty(), true); // tested further below } END_SECTION START_SECTION((ProcessingSoftwareRef registerProcessingSoftware(const Software& software))) { ID::ProcessingSoftware sw("Tool", "1.0"); sw_ref = data.registerProcessingSoftware(sw); TEST_EQUAL(data.getProcessingSoftwares().size(), 1); TEST_EQUAL(*sw_ref == sw, true); // "TEST_EQUAL(*sw_ref, sw)" doesn't compile - same below // re-registering doesn't lead to redundant entries: data.registerProcessingSoftware(sw); TEST_EQUAL(data.getProcessingSoftwares().size(), 1); } END_SECTION START_SECTION((const DBSearchParams& getDBSearchParams() const)) { TEST_EQUAL(data.getDBSearchParams().empty(), true); // tested further below } END_SECTION START_SECTION((SearchParamRef registerDBSearchParam(const DBSearchParam& param))) { ID::DBSearchParam param; param.database = "test-db.fasta"; param.precursor_mass_tolerance = 1; param.fragment_mass_tolerance = 2; param_ref = data.registerDBSearchParam(param); TEST_EQUAL(data.getDBSearchParams().size(), 1); TEST_EQUAL(*param_ref == param, true); // re-registering doesn't lead to redundant entries: data.registerDBSearchParam(param); TEST_EQUAL(data.getDBSearchParams().size(), 1); } END_SECTION START_SECTION((const ProcessingSteps& getProcessingSteps() const)) { TEST_EQUAL(data.getProcessingSteps().empty(), true); // tested further below } END_SECTION START_SECTION((ProcessingStepRef registerProcessingStep(const ProcessingStep& step))) { vector<ID::InputFileRef> file_refs(1, file_ref); ID::ProcessingStep step(sw_ref, file_refs); step_ref = data.registerProcessingStep(step); TEST_EQUAL(data.getProcessingSteps().size(), 1); TEST_EQUAL(*step_ref == step, true); // re-registering doesn't lead to redundant entries: data.registerProcessingStep(step); TEST_EQUAL(data.getProcessingSteps().size(), 1); } END_SECTION START_SECTION((const ProcessingSteps& getDBSearchSteps() const)) { TEST_EQUAL(data.getDBSearchSteps().empty(), true); // tested further below } END_SECTION START_SECTION((ProcessingStepRef registerProcessingStep(const ProcessingStep& step, SearchParamRef search_ref))) { ID::ProcessingStep step(sw_ref); step_ref = data.registerProcessingStep(step, param_ref); TEST_EQUAL(data.getProcessingSteps().size(), 2); TEST_EQUAL(*step_ref == step, true); TEST_EQUAL(data.getDBSearchSteps().size(), 1); TEST_EQUAL(data.getDBSearchSteps().at(step_ref), param_ref); // re-registering doesn't lead to redundant entries: data.registerProcessingStep(step, param_ref); TEST_EQUAL(data.getProcessingSteps().size(), 2); TEST_EQUAL(data.getDBSearchSteps().size(), 1); } END_SECTION START_SECTION((const ScoreTypes& getScoreTypes() const)) { TEST_EQUAL(data.getScoreTypes().empty(), true); // tested further below } END_SECTION START_SECTION((ScoreTypeRef registerScoreType(const ScoreType& score))) { ID::ScoreType score("test_score", true); score_ref = data.registerScoreType(score); TEST_EQUAL(data.getScoreTypes().size(), 1); TEST_EQUAL(*score_ref == score, true); // re-registering doesn't lead to redundant entries: data.registerScoreType(score); TEST_EQUAL(data.getScoreTypes().size(), 1); } END_SECTION START_SECTION((const Observations& getObservations() const)) { TEST_EQUAL(data.getObservations().empty(), true); // tested further below } END_SECTION START_SECTION((ObservationRef registerObservation(const Observation& obs))) { ID::Observation obs("spectrum_1", file_ref, 100.0, 1000.0); obs_ref = data.registerObservation(obs); TEST_EQUAL(data.getObservations().size(), 1); TEST_EQUAL(*obs_ref == obs, true); // re-registering doesn't lead to redundant entries: data.registerObservation(obs); TEST_EQUAL(data.getObservations().size(), 1); } END_SECTION START_SECTION((const ParentSequences& getParentSequences() const)) { TEST_EQUAL(data.getParentSequences().empty(), true); // tested further below } END_SECTION START_SECTION((ParentSequenceRef registerParentSequence(const ParentSequence& parent))) { ID::ParentSequence protein(""); // can't register a parent sequence without accession: TEST_EXCEPTION(Exception::IllegalArgument, data.registerParentSequence(protein)); TEST_EQUAL(data.getParentSequences().empty(), true); protein.accession = "protein_1"; protein.sequence = "TESTPEPTIDEAAA"; protein_ref = data.registerParentSequence(protein); TEST_EQUAL(data.getParentSequences().size(), 1); TEST_EQUAL(*protein_ref == protein, true); ID::ParentSequence rna("rna_1", ID::MoleculeType::RNA); rna_ref = data.registerParentSequence(rna); TEST_EQUAL(data.getParentSequences().size(), 2); TEST_EQUAL(*rna_ref == rna, true); // re-registering doesn't lead to redundant entries: data.registerParentSequence(rna); TEST_EQUAL(data.getParentSequences().size(), 2); } END_SECTION START_SECTION((const ParentGroupSets& getParentGroupSets() const)) { TEST_EQUAL(data.getParentGroupSets().empty(), true); // tested further below } END_SECTION START_SECTION((void registerParentGroupSet(const ParentGroupSet& groups))) { ID::ParentGroup group; group.parent_refs.insert(protein_ref); group.parent_refs.insert(rna_ref); ID::ParentGroupSet groups; groups.label = "test_grouping"; groups.groups.insert(group); data.registerParentGroupSet(groups); TEST_EQUAL(data.getParentGroupSets().size(), 1); TEST_EQUAL(data.getParentGroupSets()[0].groups.size(), 1); TEST_EQUAL(data.getParentGroupSets()[0].groups.begin()->parent_refs.size(), 2); } END_SECTION START_SECTION((const IdentifiedPeptides& getIdentifiedPeptides() const)) { TEST_EQUAL(data.getIdentifiedPeptides().empty(), true); // tested further below } END_SECTION START_SECTION((IdentifiedPeptideRef registerIdentifiedPeptide(const IdentifiedPeptide& peptide))) { ID::IdentifiedPeptide peptide(AASequence::fromString("")); // can't register a peptide without a sequence: TEST_EXCEPTION(Exception::IllegalArgument, data.registerIdentifiedPeptide(peptide)); TEST_EQUAL(data.getIdentifiedPeptides().empty(), true); // peptide without protein reference: peptide.sequence = AASequence::fromString("TEST"); peptide_ref = data.registerIdentifiedPeptide(peptide); TEST_EQUAL(data.getIdentifiedPeptides().size(), 1); TEST_EQUAL(*peptide_ref == peptide, true); // peptide with protein reference: peptide.sequence = AASequence::fromString("PEPTIDE"); peptide.parent_matches[protein_ref].insert(ID:: ParentMatch(4, 10)); peptide_ref = data.registerIdentifiedPeptide(peptide); TEST_EQUAL(data.getIdentifiedPeptides().size(), 2); TEST_EQUAL(*peptide_ref == peptide, true); // re-registering doesn't lead to redundant entries: data.registerIdentifiedPeptide(peptide); TEST_EQUAL(data.getIdentifiedPeptides().size(), 2); // registering a peptide with RNA reference doesn't work: peptide.parent_matches[rna_ref]; TEST_EXCEPTION(Exception::IllegalArgument, data.registerIdentifiedPeptide(peptide)); } END_SECTION START_SECTION((const IdentifiedOligos& getIdentifiedOligos() const)) { TEST_EQUAL(data.getIdentifiedOligos().empty(), true); // tested further below } END_SECTION START_SECTION((IdentifiedOligoRef registerIdentifiedOligo(const IdentifiedOligo& oligo))) { ID::IdentifiedOligo oligo(NASequence::fromString("")); // can't register an oligo without a sequence: TEST_EXCEPTION(Exception::IllegalArgument, data.registerIdentifiedOligo(oligo)); TEST_EQUAL(data.getIdentifiedOligos().empty(), true); // oligo without RNA reference: oligo.sequence = NASequence::fromString("ACGU"); oligo_ref = data.registerIdentifiedOligo(oligo); TEST_EQUAL(data.getIdentifiedOligos().size(), 1); TEST_EQUAL(*oligo_ref == oligo, true); // oligo with RNA reference: oligo.sequence = NASequence::fromString("UGCA"); oligo.parent_matches[rna_ref]; oligo_ref = data.registerIdentifiedOligo(oligo); TEST_EQUAL(data.getIdentifiedOligos().size(), 2); TEST_EQUAL(*oligo_ref == oligo, true); // re-registering doesn't lead to redundant entries: data.registerIdentifiedOligo(oligo); TEST_EQUAL(data.getIdentifiedOligos().size(), 2); // registering an oligo with protein reference doesn't work: oligo.parent_matches[protein_ref]; TEST_EXCEPTION(Exception::IllegalArgument, data.registerIdentifiedOligo(oligo)); } END_SECTION START_SECTION((const IdentifiedCompounds& getIdentifiedCompounds() const)) { TEST_EQUAL(data.getIdentifiedCompounds().empty(), true); // tested further below } END_SECTION START_SECTION((IdentifiedCompoundRef registerIdentifiedCompound(const IdentifiedCompound& compound))) { ID::IdentifiedCompound compound(""); // can't register a compound without identifier: TEST_EXCEPTION(Exception::IllegalArgument, data.registerIdentifiedCompound(compound)); TEST_EQUAL(data.getIdentifiedCompounds().empty(), true); compound = ID::IdentifiedCompound("compound_1", EmpiricalFormula("C2H5OH"), "ethanol"); compound_ref = data.registerIdentifiedCompound(compound); TEST_EQUAL(data.getIdentifiedCompounds().size(), 1); TEST_EQUAL(*compound_ref == compound, true); // re-registering doesn't lead to redundant entries: data.registerIdentifiedCompound(compound); TEST_EQUAL(data.getIdentifiedCompounds().size(), 1); } END_SECTION START_SECTION((const Adducts& getAdducts() const)) { TEST_EQUAL(data.getAdducts().empty(), true); // tested further below } END_SECTION START_SECTION((AdductRef registerAdduct(const AdductInfo& adduct))) { AdductInfo adduct("Na+", EmpiricalFormula("Na"), 1); adduct_ref = data.registerAdduct(adduct); TEST_EQUAL(data.getAdducts().size(), 1); TEST_EQUAL(*adduct_ref == adduct, true); } END_SECTION START_SECTION((const ObservationMatches& getObservationMatches() const)) { TEST_EQUAL(data.getObservationMatches().empty(), true); // tested further below } END_SECTION START_SECTION((ObservationMatchRef registerObservationMatch(const ObservationMatch& match))) { // match with a peptide: ID::ObservationMatch match(peptide_ref, obs_ref, 3); match_ref1 = data.registerObservationMatch(match); TEST_EQUAL(data.getObservationMatches().size(), 1); TEST_EQUAL(*match_ref1 == match, true); // match with an oligo (+ adduct): match = ID::ObservationMatch(oligo_ref, obs_ref, 2, adduct_ref); match_ref2 = data.registerObservationMatch(match); TEST_EQUAL(data.getObservationMatches().size(), 2); TEST_EQUAL(*match_ref2 == match, true); TEST_EQUAL((*match_ref2->adduct_opt)->getName(), "Na+"); // match with a compound: match = ID::ObservationMatch(compound_ref, obs_ref, 1); match_ref3 = data.registerObservationMatch(match); TEST_EQUAL(data.getObservationMatches().size(), 3); TEST_EQUAL(*match_ref3 == match, true); // re-registering doesn't lead to redundant entries: data.registerObservationMatch(match); TEST_EQUAL(data.getObservationMatches().size(), 3); } END_SECTION START_SECTION((const ObservationMatchGroups& getObservationMatchGroups() const)) { TEST_EQUAL(data.getObservationMatchGroups().empty(), true); // tested further below } END_SECTION START_SECTION((MatchGroupRef registerObservationMatchGroup(const ObservationMatchGroup& group))) { ID::ObservationMatchGroup group; group.observation_match_refs.insert(match_ref1); group.observation_match_refs.insert(match_ref2); group.observation_match_refs.insert(match_ref3); data.registerObservationMatchGroup(group); TEST_EQUAL(data.getObservationMatchGroups().size(), 1); TEST_EQUAL(*data.getObservationMatchGroups().begin() == group, true); } END_SECTION START_SECTION((void addScore(ObservationMatchRef match_ref, ScoreTypeRef score_ref, double value))) { TEST_EQUAL(match_ref1->steps_and_scores.empty(), true); data.addScore(match_ref1, score_ref, 100.0); TEST_EQUAL(match_ref1->steps_and_scores.size(), 1); TEST_EQUAL(match_ref1->steps_and_scores.back().scores.begin()->first, score_ref); TEST_EQUAL(match_ref1->steps_and_scores.back().scores.begin()->second, 100.0); TEST_EQUAL(match_ref2->steps_and_scores.empty(), true); data.addScore(match_ref2, score_ref, 200.0); TEST_EQUAL(match_ref2->steps_and_scores.size(), 1); TEST_EQUAL(match_ref2->steps_and_scores.back().scores.begin()->first, score_ref); TEST_EQUAL(match_ref2->steps_and_scores.back().scores.begin()->second, 200.0); } END_SECTION START_SECTION((ProcessingStepRef getCurrentProcessingStep())) { TEST_EQUAL(data.getCurrentProcessingStep() == data.getProcessingSteps().end(), true); // tested further below } END_SECTION START_SECTION((void setCurrentProcessingStep(ProcessingStepRef step_ref))) { data.setCurrentProcessingStep(step_ref); TEST_EQUAL(data.getCurrentProcessingStep() == step_ref, true); // registering new data automatically adds the processing step: ID::IdentifiedPeptide peptide(AASequence::fromString("EDIT")); peptide.parent_matches[protein_ref]; peptide_ref = data.registerIdentifiedPeptide(peptide); TEST_EQUAL(peptide_ref->steps_and_scores.size(), 1); TEST_EQUAL(peptide_ref->steps_and_scores.front().processing_step_opt == step_ref, true); } END_SECTION START_SECTION((void clearCurrentProcessingStep())) { data.clearCurrentProcessingStep(); TEST_EQUAL(data.getCurrentProcessingStep() == data.getProcessingSteps().end(), true); } END_SECTION START_SECTION((pair<ID::ObservationMatchRef, ID::ObservationMatchRef> getMatchesForObservation(ObservationRef obs_ref) const)) { pair<ID::ObservationMatchRef, ID::ObservationMatchRef> result = data.getMatchesForObservation(obs_ref); TEST_EQUAL(distance(result.first, result.second), 3); for (; result.first != result.second; ++result.first) { TEST_EQUAL((result.first == match_ref1) || (result.first == match_ref2) || (result.first == match_ref3), true); } } END_SECTION START_SECTION((ScoreTypeRef findScoreType(const String& score_name) const)) { // non-existent score: TEST_EQUAL(data.findScoreType("fake_score") == data.getScoreTypes().end(), true); // registered score: TEST_EQUAL(data.findScoreType("test_score") == score_ref, true); } END_SECTION START_SECTION((void calculateCoverages(bool check_molecule_length = false))) { TEST_EQUAL(protein_ref->coverage, 0.0); data.calculateCoverages(); TEST_REAL_SIMILAR(protein_ref->coverage, 0.5); // partially overlapping peptide: ID::IdentifiedPeptide peptide(AASequence::fromString("TESTPEP")); peptide.parent_matches[protein_ref].insert(ID::ParentMatch(0, 6)); data.registerIdentifiedPeptide(peptide); data.calculateCoverages(); TEST_REAL_SIMILAR(protein_ref->coverage, 11.0/14.0); } END_SECTION START_SECTION((void cleanup(bool require_observation_match = true, bool require_identified_sequence = true, bool require_parent_match = true, bool require_parent_group = false, bool require_match_group = false))) { TEST_EQUAL(data.getIdentifiedPeptides().size(), 4); TEST_EQUAL(data.getIdentifiedOligos().size(), 2); data.cleanup(false); // identified peptide/oligo without parent match is removed: TEST_EQUAL(data.getIdentifiedPeptides().size(), 3); TEST_EQUAL(data.getIdentifiedOligos().size(), 1); data.cleanup(); // identified peptides without matches are removed: TEST_EQUAL(data.getIdentifiedPeptides().size(), 1); TEST_EQUAL(data.getIdentifiedOligos().size(), 1); } END_SECTION START_SECTION((ProcessingStepRef merge(const IdentificationData& other))) { TEST_EQUAL(data.getIdentifiedPeptides().size(), 1); TEST_EQUAL(data.getIdentifiedOligos().size(), 1); TEST_EQUAL(data.getParentSequences().size(), 2); data.merge(data); // self-merge shouldn't change anything TEST_EQUAL(data.getIdentifiedPeptides().size(), 1); TEST_EQUAL(data.getIdentifiedOligos().size(), 1); TEST_EQUAL(data.getParentSequences().size(), 2); IdentificationData other; ID::IdentifiedPeptide peptide(AASequence::fromString("MASSSPEC")); other.registerIdentifiedPeptide(peptide); data.merge(other); TEST_EQUAL(data.getIdentifiedPeptides().size(), 2); TEST_EQUAL(data.getIdentifiedOligos().size(), 1); TEST_EQUAL(data.getParentSequences().size(), 2); } END_SECTION START_SECTION((IdentificationData(const IdentificationData& other))) { IdentificationData copy(data); TEST_EQUAL(copy.getIdentifiedPeptides().size(), 2); TEST_EQUAL(copy.getIdentifiedOligos().size(), 1); TEST_EQUAL(copy.getParentSequences().size(), 2); TEST_EQUAL(copy.getObservationMatches().size(), 3); // focus on processing steps and scores for observation matches: IdentificationData data2; ID::InputFile file("test.mzML"); auto file_ref = data2.registerInputFile(file); ID::ProcessingSoftware sw("Tool", "1.0"); auto sw_ref = data2.registerProcessingSoftware(sw); ID::ProcessingStep step(sw_ref, {file_ref}); auto step_ref = data2.registerProcessingStep(step); data2.setCurrentProcessingStep(step_ref); ID::Observation obs("spectrum_1", file_ref, 100.0, 1000.0); auto obs_ref = data2.registerObservation(obs); ID::IdentifiedPeptide peptide(AASequence::fromString("PEPTIDE")); auto pep_ref = data2.registerIdentifiedPeptide(peptide); ID::ObservationMatch match(pep_ref, obs_ref, 2); ID::ScoreType score("score1", true); auto score_ref1 = data2.registerScoreType(score); score = ID::ScoreType("score2", false); auto score_ref2 = data2.registerScoreType(score); // add first score, not connected to a processing step: match.addScore(score_ref1, 1.0); auto match_ref = data2.registerObservationMatch(match); // add second score, automatically connected to last processing step: data2.addScore(match_ref, score_ref2, 2.0); TEST_EQUAL(data2.getObservationMatches().begin()->steps_and_scores.size(), 2); TEST_EQUAL(data2.getObservationMatches().begin()->getNumberOfScores(), 2); // look up scores by score type: TEST_EQUAL(data2.getObservationMatches().begin()->getScore(score_ref1).first, 1.0); TEST_EQUAL(data2.getObservationMatches().begin()->getScore(score_ref2).first, 2.0); // look up score by score type and (wrong) processing step -> fails: TEST_EQUAL(data2.getObservationMatches().begin()->getScore(score_ref1, step_ref).second, false); // look up score by score type and (correct) processing step -> succeeds: TEST_EQUAL(data2.getObservationMatches().begin()->getScore(score_ref2, step_ref).first, 2.0); auto triple = data2.getObservationMatches().begin()->getMostRecentScore(); TEST_EQUAL(std::get<0>(triple), 2.0); TEST_EQUAL(std::get<1>(triple) == score_ref2, true); // after copying: IdentificationData copy2(data2); TEST_EQUAL(copy2.getObservationMatches().begin()->steps_and_scores.size(), 2); TEST_EQUAL(copy2.getObservationMatches().begin()->getNumberOfScores(), 2); score_ref1 = copy2.findScoreType("score1"); TEST_EQUAL(copy2.getObservationMatches().begin()->getScore(score_ref1).first, 1.0); score_ref2 = copy2.findScoreType("score2"); TEST_EQUAL(copy2.getObservationMatches().begin()->getScore(score_ref2).first, 2.0); step_ref = copy2.getCurrentProcessingStep(); TEST_EQUAL(copy2.getObservationMatches().begin()->getScore(score_ref1, step_ref).second, false); TEST_EQUAL(copy2.getObservationMatches().begin()->getScore(score_ref2, step_ref).first, 2.0); triple = copy2.getObservationMatches().begin()->getMostRecentScore(); TEST_EQUAL(std::get<0>(triple), 2.0); TEST_EQUAL(std::get<1>(triple) == score_ref2, true); } END_SECTION START_SECTION((vector<ObservationMatchRef> getBestMatchPerObservation(ScoreTypeRef score_ref) const)) { // add a second observation and match (without score): ID::Observation obs("spectrum_2", file_ref, 200.0, 2000.0); ID::ObservationRef obs_ref2 = data.registerObservation(obs); ID::ObservationMatch match(oligo_ref, obs_ref2, 2); ID::ObservationMatchRef match_ref4 = data.registerObservationMatch(match); TEST_EQUAL(data.getObservationMatches().size(), 4); // best matches, requiring score: vector<ID::ObservationMatchRef> results = data.getBestMatchPerObservation(score_ref, true); TEST_EQUAL(results.size(), 1); TEST_EQUAL(results[0] == match_ref2, true); // best matches, no score required: results = data.getBestMatchPerObservation(score_ref, false); TEST_EQUAL(results.size(), 2); ABORT_IF(results.size() != 2); if (results[0] == match_ref2) // can't be sure about the order { TEST_EQUAL(results[1] == match_ref4, true); } else { TEST_EQUAL(results[0] == match_ref4, true); TEST_EQUAL(results[1] == match_ref2, true); } } END_SECTION START_SECTION(([EXTRA] UseCaseBuildBottomUpProteomicsID())) { IdentificationData id; ID::InputFile file("file://ROOT/FOLDER/SPECTRA.mzML"); auto file_ref = id.registerInputFile(file); // register a score type ID::ScoreType score("MySearchEngineScore", true); auto score_ref = id.registerScoreType(score); // register software (connected to score) ID::ProcessingSoftware sw("MySearchEngineTool", "1.0"); sw.assigned_scores.push_back(score_ref); auto sw_ref = id.registerProcessingSoftware(sw); // all supported search settings ID::DBSearchParam search_param; search_param.database = "file://ROOT/FOLDER/DATABASE.fasta"; search_param.database_version = "nextprot1234"; search_param.taxonomy = "Homo Sapiens"; search_param.charges = {2,3,4,5}; search_param.precursor_mass_tolerance = 8.0; search_param.precursor_tolerance_ppm = true; search_param.fixed_mods = {"Carbamidomethyl (C)"}; search_param.variable_mods = {"Oxidation (M)"}; search_param.digestion_enzyme = ProteaseDB::getInstance()->getEnzyme("Trypsin"); search_param.enzyme_term_specificity = EnzymaticDigestion::SPEC_SEMI; search_param.missed_cleavages = 2; search_param.min_length = 6; search_param.max_length = 40; search_param.fragment_mass_tolerance = 0.3; search_param.fragment_tolerance_ppm = true; auto search_param_ref = id.registerDBSearchParam(search_param); // file has been processed by software ID::ProcessingStep step(sw_ref); step.input_file_refs.push_back(file_ref); auto step_ref = id.registerProcessingStep(step, search_param_ref); // all further data comes from this processing step id.setCurrentProcessingStep(step_ref); // register spectrum ID::Observation obs("spectrum_1", file_ref, 100.0, 1000.0); auto obs_ref = id.registerObservation(obs); // peptide without protein reference (yet) ID::IdentifiedPeptide peptide(AASequence::fromString("TESTPEPTIDR")); // seq. is required auto peptide_ref = id.registerIdentifiedPeptide(peptide); TEST_EQUAL(peptide_ref->parent_matches.size(), 0); // peptide-spectrum match ID::ObservationMatch match(peptide_ref, obs_ref); // both refs. are required match.addScore(score_ref, 123, step_ref); id.registerObservationMatch(match); // some calculations, inference etc. could take place ... ID::ParentSequence protein("protein_1"); // accession is required protein.sequence = "PRTTESTPEPTIDRPRT"; protein.description = "Human Random Protein 1"; auto protein_ref = id.registerParentSequence(protein); // add reference to parent (protein) and update peptide ID::IdentifiedPeptide augmented_pep = *peptide_ref; // @TODO: wrap this in a convenience function (like "match.addScore" above) augmented_pep.parent_matches[protein_ref].insert(ID::ParentMatch(3, 13)); id.registerIdentifiedPeptide(augmented_pep); // protein reference will be added // peptide_ref should still be valid and now contain link to protein TEST_EQUAL(peptide_ref->sequence, augmented_pep.sequence); TEST_EQUAL(peptide_ref->parent_matches.size(), 1); // and now update protein coverage of all proteins id.calculateCoverages(); TEST_NOT_EQUAL(protein_ref->coverage, 0.0); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FeatureFindingMetabo_test.cpp
.cpp
3,685
113
// 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$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/CONCEPT/FuzzyStringComparator.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/FEATUREFINDER/MassTraceDetection.h> #include <OpenMS/FEATUREFINDER/ElutionPeakDetection.h> #include <OpenMS/KERNEL/MSExperiment.h> /////////////////////////// #include <OpenMS/FEATUREFINDER/FeatureFindingMetabo.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(FeatureFindingMetabo, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FeatureFindingMetabo* ptr = nullptr; FeatureFindingMetabo* null_ptr = nullptr; START_SECTION(FeatureFindingMetabo()) { ptr = new FeatureFindingMetabo(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~FeatureFindingMetabo()) { delete ptr; } END_SECTION // load a mzML file for testing the algorithm PeakMap input; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("FeatureFindingMetabo_input1.mzML"), input); FeatureMap test_fm; std::vector<MassTrace> output_mt, splitted_mt, filtered_mt; std::vector<std::vector< OpenMS::MSChromatogram > > chromatograms; MassTraceDetection test_mtd; test_mtd.run(input, output_mt); ElutionPeakDetection test_epd; test_epd.detectPeaks(output_mt, splitted_mt); FuzzyStringComparator fsc; fsc.setAcceptableRelative(1.001); fsc.setAcceptableAbsolute(1); StringList sl; sl.push_back("xml-stylesheet"); sl.push_back("<featureMap"); sl.push_back("<feature id"); fsc.setWhitelist(sl); //std::cout << "\n\n" << fsc.compareStrings("529090", "529091") << "\n\n\n"; START_SECTION((void run(std::vector< MassTrace > &, FeatureMap &, chromatograms &))) { FeatureFindingMetabo test_ffm; // run with non-default setting (C13 isotope distance) Param p = test_ffm.getParameters(); p.setValue("mz_scoring_13C", "true"); test_ffm.setParameters(p); test_ffm.run(splitted_mt, test_fm, chromatograms); TEST_EQUAL(test_fm.size(), 84); // run with default settings (from paper using charge+isotope# dependent distances) p.setValue("report_convex_hulls", "true"); p.setValue("mz_scoring_13C", "false"); test_ffm.setParameters(p); test_ffm.run(splitted_mt, test_fm, chromatograms); TEST_EQUAL(test_fm.size(), 81); // --> this gives less features, i.e. more isotope clusters (but the input data is simulated and highly weird -- should be replaced at some point) // test annotation of input String tmp_file; NEW_TMP_FILE(tmp_file); FeatureXMLFile().store(tmp_file, test_fm); TEST_EQUAL(fsc.compareFiles(tmp_file, OPENMS_GET_TEST_DATA_PATH("FeatureFindingMetabo_output1.featureXML")), true); //todo the new isotope m/z scoring should produce similar results, but still has to be tested. p.setValue("report_convex_hulls", "true"); p.setValue("mz_scoring_by_elements", "true"); test_ffm.setParameters(p); test_ffm.run(splitted_mt, test_fm, chromatograms); TEST_EQUAL(test_fm.size(), 80); // --> this gives less features, i.e. more isotope clusters (but the input data is simulated and highly weird -- should be replaced at some point) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MzMLSqliteHandler_test.cpp
.cpp
21,380
650
// 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/MzMLSqliteHandler.h> /////////////////////////// #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <QFile> using namespace OpenMS; using namespace OpenMS::Internal; using namespace std; void cmpDataIntensity(const MSExperiment& exp1, const MSExperiment& exp2, double abs_tol = 1e-5, double rel_tol = 1+1e-5) { // Logic of comparison: if the absolute difference criterion is fulfilled, // the relative one does not matter. If the absolute difference is larger // than allowed, the test does not fail if the relative difference is less // than allowed. // Note that the sample spectrum intensity has a very large range, from // 0.00013 to 183 838 intensity and encoding both values with high accuracy // is difficult. TOLERANCE_ABSOLUTE(abs_tol) TOLERANCE_RELATIVE(rel_tol) for (Size i = 0; i < exp1.getNrSpectra(); i++) { TEST_EQUAL(exp1.getSpectra()[i].size(), exp2.getSpectra()[i].size()) for (Size k = 0; k < exp1.getSpectra()[i].size(); k++) { // slof is no good for values smaller than 5 // if (exp.getSpectrum(i)[k].getIntensity() < 1.0) {continue;} auto a = exp1.getSpectra()[i][k].getIntensity(); auto b = exp2.getSpectra()[i][k].getIntensity(); // avoid the console clutter if nothing interesing happens if (!TEST::isRealSimilar(a, b)) TEST_REAL_SIMILAR(a, b) } } for (Size i = 0; i < exp1.getNrChromatograms(); i++) { TEST_EQUAL(exp1.getChromatograms()[i].size() == exp2.getChromatograms()[i].size(), true) for (Size k = 0; k < exp1.getChromatograms()[i].size(); k++) { auto a = exp1.getChromatograms()[i][k].getIntensity(); auto b = exp2.getChromatograms()[i][k].getIntensity(); // avoid the console clutter if nothing interesing happens if (!TEST::isRealSimilar(a, b)) TEST_REAL_SIMILAR(a, b) } } } void cmpDataMZ(const MSExperiment& exp1, const MSExperiment& exp2, double abs_tol = 1e-5, double rel_tol = 1+1e-5) { // Logic of comparison: if the absolute difference criterion is fulfilled, // the relative one does not matter. If the absolute difference is larger // than allowed, the test does not fail if the relative difference is less // than allowed. // Note that the sample spectrum intensity has a very large range, from // 0.00013 to 183 838 intensity and encoding both values with high accuracy // is difficult. TOLERANCE_ABSOLUTE(abs_tol) TOLERANCE_RELATIVE(rel_tol) for (Size i = 0; i < exp1.getNrSpectra(); i++) { TEST_EQUAL(exp1.getSpectra()[i].size(), exp2.getSpectra()[i].size()) for (Size k = 0; k < exp1.getSpectra()[i].size(); k++) { // slof is no good for values smaller than 5 // if (exp.getSpectrum(i)[k].getIntensity() < 1.0) {continue;} auto a = exp1.getSpectra()[i][k].getMZ(); auto b = exp2.getSpectra()[i][k].getMZ(); // avoid the console clutter if nothing interesing happens if (!TEST::isRealSimilar(a, b)) TEST_REAL_SIMILAR(a, b) } } } void cmpDataRT(const MSExperiment& exp1, const MSExperiment& exp2, double abs_tol = 1e-5, double rel_tol = 1+1e-5) { // Logic of comparison: if the absolute difference criterion is fulfilled, // the relative one does not matter. If the absolute difference is larger // than allowed, the test does not fail if the relative difference is less // than allowed. // Note that the sample spectrum intensity has a very large range, from // 0.00013 to 183 838 intensity and encoding both values with high accuracy // is difficult. TOLERANCE_ABSOLUTE(abs_tol) TOLERANCE_RELATIVE(rel_tol) for (Size i = 0; i < exp1.getNrChromatograms(); i++) { TEST_EQUAL(exp1.getChromatograms()[i].size() == exp2.getChromatograms()[i].size(), true) for (Size k = 0; k < exp1.getChromatograms()[i].size(); k++) { auto a = exp1.getChromatograms()[i][k].getRT(); auto b = exp2.getChromatograms()[i][k].getRT(); // avoid the console clutter if nothing interesing happens if (!TEST::isRealSimilar(a, b)) TEST_REAL_SIMILAR(a, b) } } } /////////////////////////// START_TEST(MzMLSqliteHandler, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MzMLSqliteHandler* ptr = nullptr; MzMLSqliteHandler* nullPointer = nullptr; START_SECTION((MzMLSqliteHandler(const String& filename, const UInt64 run_id))) ptr = new MzMLSqliteHandler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~MzMLSqliteHandler())) delete ptr; END_SECTION TOLERANCE_RELATIVE(1.0005) START_SECTION(UInt64 getRunID() const) MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); TEST_EQUAL(handler.getRunID(), 12345) END_SECTION START_SECTION(void readExperiment(MSExperiment & exp, bool meta_only = false) const) { MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); MSExperiment exp_orig; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), exp_orig); // read in meta data only { MSExperiment exp; handler.readExperiment(exp, true); TEST_EQUAL(exp.getNrSpectra(), exp_orig.getSpectra().size()) TEST_EQUAL(exp.getNrChromatograms(), exp_orig.getChromatograms().size()) TEST_EQUAL(exp.getNrSpectra(), 2) TEST_EQUAL(exp.getNrChromatograms(), 1) TEST_EQUAL(exp.getSpectrum(0) == exp_orig.getSpectra()[0], false) // no exact duplicate for (Size i = 0; i < exp.getNrSpectra(); i++) { TEST_EQUAL(exp.getSpectrum(i).size(), 0) } for (Size i = 0; i < exp.getNrChromatograms(); i++) { TEST_EQUAL(exp.getChromatogram(i).size(), 0) } TEST_EQUAL(exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp_orig, true) TEST_EQUAL(exp.getSqlRunID(), 12345) } // read in all data { MSExperiment exp; handler.readExperiment(exp, false); TEST_EQUAL(exp.getNrSpectra(), exp_orig.getSpectra().size()) TEST_EQUAL(exp.getNrChromatograms(), exp_orig.getChromatograms().size()) TEST_EQUAL(exp.getNrSpectra(), 2) TEST_EQUAL(exp.getNrChromatograms(), 1) TEST_EQUAL(exp.getSpectrum(0) == exp_orig.getSpectra()[0], false) // no exact duplicate cout.precision(17); cmpDataIntensity(exp, exp_orig, 1e-4, 1.001); cmpDataMZ(exp, exp_orig, 1e-5, 1.000001); // less than 1ppm error for m/z cmpDataRT(exp, exp_orig, 0.05, 1.000001); // max 0.05 seconds error in RT // 1:1 mapping of experimental settings ... TEST_EQUAL(exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp_orig, true) TEST_EQUAL(exp.getSqlRunID(), 12345) } } END_SECTION START_SECTION( Size getNrSpectra() const ) { MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); TEST_EQUAL(handler.getNrSpectra(), 2) } END_SECTION START_SECTION( Size getNrChromatograms() const ) { MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); TEST_EQUAL(handler.getNrChromatograms(), 1) } END_SECTION START_SECTION( void readSpectra(std::vector<MSSpectrum> & exp, const std::vector<int> & indices, bool meta_only = false) const) { MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); MSExperiment exp2; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), exp2); // read in meta data only { std::vector<MSSpectrum> exp; std::vector<int> indices = {1}; handler.readSpectra(exp, indices, true); TEST_EQUAL(exp.size(), 1) TEST_EQUAL(exp[0].size(), 0) TEST_REAL_SIMILAR(exp[0].getRT(), 0.4738) } { std::vector<MSSpectrum> exp; std::vector<int> indices = {1}; handler.readSpectra(exp, indices, false); TEST_EQUAL(exp.size(), 1) TEST_EQUAL(exp[0].size(), 19800) TEST_REAL_SIMILAR(exp[0].getRT(), 0.4738) } { std::vector<MSSpectrum> exp; std::vector<int> indices = {0}; handler.readSpectra(exp, indices, false); TEST_EQUAL(exp.size(), 1) TEST_EQUAL(exp[0].size(), 19914) TEST_REAL_SIMILAR(exp[0].getRT(), 0.2961) } { std::vector<MSSpectrum> exp; std::vector<int> indices = {0, 1}; handler.readSpectra(exp, indices, true); TEST_EQUAL(exp.size(), 2) TEST_EQUAL(exp[0].size(), 0) TEST_EQUAL(exp[1].size(), 0) TEST_REAL_SIMILAR(exp[0].getRT(), 0.2961) TEST_REAL_SIMILAR(exp[1].getRT(), 0.4738) } { std::vector<MSSpectrum> exp; std::vector<int> indices = {0, 1}; handler.readSpectra(exp, indices, false); TEST_EQUAL(exp.size(), 2) TEST_EQUAL(exp[0].size(), 19914) TEST_EQUAL(exp[1].size(), 19800) TEST_REAL_SIMILAR(exp[0].getRT(), 0.2961) TEST_REAL_SIMILAR(exp[1].getRT(), 0.4738) } { std::vector<MSSpectrum> exp; std::vector<int> indices = {0, 1, 2}; TEST_EXCEPTION(Exception::IllegalArgument, handler.readSpectra(exp, indices, false)); } { std::vector<MSSpectrum> exp; std::vector<int> indices = {5}; TEST_EXCEPTION(Exception::IllegalArgument, handler.readSpectra(exp, indices, false)); } } END_SECTION START_SECTION(void readChromatograms(std::vector<MSChromatogram> & exp, const std::vector<int> & indices, bool meta_only = false) const) { MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); MSExperiment exp2; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), exp2); // read in meta data only { std::vector<MSChromatogram> exp; std::vector<int> indices = {0}; handler.readChromatograms(exp, indices, true); TEST_EQUAL(exp.size(), 1) TEST_EQUAL(exp[0].size(), 0) TEST_STRING_EQUAL(exp[0].getNativeID(), "TIC") } { std::vector<MSChromatogram> exp; std::vector<int> indices = {0, 1}; TEST_EXCEPTION(Exception::IllegalArgument, handler.readChromatograms(exp, indices, false)); } { std::vector<MSChromatogram> exp; std::vector<int> indices = {5}; TEST_EXCEPTION(Exception::IllegalArgument, handler.readChromatograms(exp, indices, false)); } { MSExperiment exp_orig; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), exp_orig); std::string tmp_filename; NEW_TMP_FILE(tmp_filename); // delete file if present QFile file (String(tmp_filename).toQString()); file.remove(); auto chroms = exp_orig.getChromatograms(); chroms.push_back(exp_orig.getChromatograms()[0]); chroms.back().setNativeID("second"); { MzMLSqliteHandler handler(tmp_filename, 0); handler.setConfig(true, false, 0.0001); handler.createTables(); handler.writeChromatograms(chroms); } MzMLSqliteHandler handler(tmp_filename, 0); { std::vector<MSChromatogram> exp; std::vector<int> indices = {0}; handler.readChromatograms(exp, indices, true); TEST_EQUAL(exp.size(), 1) TEST_EQUAL(exp[0].size(), 0) TEST_STRING_EQUAL(exp[0].getNativeID(), "TIC") } { std::vector<MSChromatogram> exp; std::vector<int> indices = {1}; handler.readChromatograms(exp, indices, true); TEST_EQUAL(exp.size(), 1) TEST_EQUAL(exp[0].size(), 0) TEST_STRING_EQUAL(exp[0].getNativeID(), "second") } { std::vector<MSChromatogram> exp; std::vector<int> indices = {0, 1}; handler.readChromatograms(exp, indices, true); TEST_EQUAL(exp.size(), 2) TEST_EQUAL(exp[0].size(), 0) TEST_STRING_EQUAL(exp[0].getNativeID(), "TIC") TEST_STRING_EQUAL(exp[1].getNativeID(), "second") } } } END_SECTION START_SECTION(std::vector<size_t> getSpectraIndicesbyRT(double RT, double deltaRT, const std::vector<int> & indices) const) { MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); { std::vector<int> indices = {}; auto res = handler.getSpectraIndicesbyRT(0.4738, 0.1, indices); TEST_EQUAL(res.size(), 1) TEST_EQUAL(res[0], 1) } { std::vector<int> indices = {}; auto res = handler.getSpectraIndicesbyRT(0.296, 0.1, indices); TEST_EQUAL(res.size(), 1) TEST_EQUAL(res[0], 0) } { std::vector<int> indices = {}; auto res = handler.getSpectraIndicesbyRT(0.296, 1.1, indices); TEST_EQUAL(res.size(), 2) TEST_EQUAL(res[0], 0) TEST_EQUAL(res[1], 1) } { std::vector<int> indices = {1}; auto res = handler.getSpectraIndicesbyRT(0.296, 1.1, indices); TEST_EQUAL(res.size(), 1) TEST_EQUAL(res[0], 1) } { std::vector<int> indices = {0}; auto res = handler.getSpectraIndicesbyRT(0.296, 1.1, indices); TEST_EQUAL(res.size(), 1) TEST_EQUAL(res[0], 0) } { std::vector<int> indices = {}; auto res = handler.getSpectraIndicesbyRT(0.0, 0.1, indices); TEST_EQUAL(res.size(), 0) } // negative deltaRT will simply return the first spectrum { std::vector<int> indices = {}; auto res = handler.getSpectraIndicesbyRT(0.3, -0.1, indices); TEST_EQUAL(res.size(), 1) TEST_EQUAL(res[0], 1) } { std::vector<int> indices = {}; auto res = handler.getSpectraIndicesbyRT(0.0, -0.1, indices); TEST_EQUAL(res.size(), 1) TEST_EQUAL(res[0], 0) } } END_SECTION START_SECTION(void writeExperiment(const MSExperiment & exp)) { const MSExperiment exp_orig = [](){ MSExperiment tmp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), tmp); return tmp; }(); std::string tmp_filename; NEW_TMP_FILE(tmp_filename); // delete file if present QFile file (String(tmp_filename).toQString()); file.remove(); { MzMLSqliteHandler handler(tmp_filename, 12345); // writing without creating the tables / indices won't work TEST_EXCEPTION(Exception::IllegalArgument, handler.writeExperiment(exp_orig)); // now it will work handler.createTables(); handler.createTables(); handler.writeExperiment(exp_orig); // you can createTables() twice, but it will delete all your data TEST_EQUAL(handler.getNrSpectra(), 2) handler.createTables(); TEST_EQUAL(handler.getNrSpectra(), 0) handler.writeExperiment(exp_orig); TEST_EQUAL(handler.getNrSpectra(), 2) } MzMLSqliteHandler handler(tmp_filename, 12345); // read in meta data only { MSExperiment exp; handler.readExperiment(exp, true); TEST_EQUAL(exp.getNrSpectra(), exp_orig.getSpectra().size()) TEST_EQUAL(exp.getNrChromatograms(), exp_orig.getChromatograms().size()) TEST_EQUAL(exp.getNrSpectra(), 2) TEST_EQUAL(exp.getNrChromatograms(), 1) TEST_EQUAL(exp.getSpectrum(0) == exp_orig.getSpectra()[0], false) // no exact duplicate for (Size i = 0; i < exp.getNrSpectra(); i++) { TEST_EQUAL(exp.getSpectrum(i).size(), 0) } for (Size i = 0; i < exp.getNrChromatograms(); i++) { TEST_EQUAL(exp.getChromatogram(i).size(), 0) } TEST_EQUAL(exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp_orig, true) } MSExperiment exp; handler.readExperiment(exp, false); // tmp: //MzMLFile().store(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra(), exp_orig.getSpectra().size()) TEST_EQUAL(exp.getNrChromatograms(), exp_orig.getChromatograms().size()) TEST_EQUAL(exp.getNrSpectra(), 2) TEST_EQUAL(exp.getNrChromatograms(), 1) TEST_EQUAL(exp.getSpectrum(0) == exp_orig.getSpectra()[0], false) // no exact duplicate cmpDataIntensity(exp, exp_orig, 1e-4, 1.001); cmpDataMZ(exp, exp_orig, 1e-5, 1.000001); // less than 1ppm error for m/z cmpDataRT(exp, exp_orig, 0.05, 1.000001); // max 0.05 seconds error in RT // 1:1 mapping of experimental settings ... TEST_EQUAL(exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp_orig, true) } END_SECTION START_SECTION(void writeSpectra(const std::vector<MSSpectrum>& spectra)) { MSExperiment exp_orig; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), exp_orig); std::string tmp_filename; NEW_TMP_FILE(tmp_filename); // delete file if present QFile file (String(tmp_filename).toQString()); file.remove(); { MzMLSqliteHandler handler(tmp_filename, 12345); // writing without creating the tables / indices won't work TEST_EXCEPTION(Exception::IllegalArgument, handler.writeSpectra(exp_orig.getSpectra())); // now it will work handler.createTables(); handler.createTables(); handler.writeSpectra(exp_orig.getSpectra()); TEST_EQUAL(handler.getNrSpectra(), 2) handler.writeSpectra(exp_orig.getSpectra()); TEST_EQUAL(handler.getNrSpectra(), 4) handler.writeSpectra(exp_orig.getSpectra()); TEST_EQUAL(handler.getNrSpectra(), 6) handler.writeRunLevelInformation(exp_orig, false); MSExperiment tmp; handler.readExperiment(tmp, false); TEST_EQUAL(tmp.getNrSpectra(), 6) TEST_EQUAL(tmp[0].size(), 19914) TEST_EQUAL(tmp[1].size(), 19800) TEST_EQUAL(tmp[2].size(), 19914) TEST_EQUAL(tmp[3].size(), 19800) TEST_EQUAL(tmp[4].size(), 19914) TEST_EQUAL(tmp[5].size(), 19800) TEST_REAL_SIMILAR(tmp.getSpectra()[0][100].getMZ(), 204.817) TEST_REAL_SIMILAR(tmp.getSpectra()[0][100].getIntensity(), 3857.86) // clear handler.createTables(); handler.writeSpectra(exp_orig.getSpectra()); TEST_EQUAL(handler.getNrSpectra(), 2) } } END_SECTION START_SECTION(void writeChromatograms(const std::vector<MSChromatogram>& chroms)) { MSExperiment exp_orig; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), exp_orig); std::string tmp_filename; NEW_TMP_FILE(tmp_filename); // delete file if present QFile file (String(tmp_filename).toQString()); file.remove(); { MzMLSqliteHandler handler(tmp_filename, 12345); handler.setConfig(true, false, 0.0001); // writing without creating the tables / indices won't work TEST_EXCEPTION(Exception::IllegalArgument, handler.writeChromatograms(exp_orig.getChromatograms())); // now it will work handler.createTables(); handler.createTables(); handler.writeChromatograms(exp_orig.getChromatograms()); TEST_EQUAL(handler.getNrChromatograms(), 1) handler.writeChromatograms(exp_orig.getChromatograms()); TEST_EQUAL(handler.getNrChromatograms(), 2) handler.writeChromatograms(exp_orig.getChromatograms()); TEST_EQUAL(handler.getNrChromatograms(), 3) handler.writeRunLevelInformation(exp_orig, false); MSExperiment tmp; handler.readExperiment(tmp, false); TEST_EQUAL(tmp.getNrChromatograms(), 3) TEST_EQUAL(tmp.getChromatograms()[0].size(), 48) TEST_EQUAL(tmp.getChromatograms()[1].size(), 48) TEST_EQUAL(tmp.getChromatograms()[2].size(), 48) TEST_REAL_SIMILAR(tmp.getChromatograms()[0][20].getRT(), 0.200695) TEST_REAL_SIMILAR(tmp.getChromatograms()[0][20].getIntensity(), 147414.578125) // clear handler.createTables(); handler.writeChromatograms(exp_orig.getChromatograms()); TEST_EQUAL(handler.getNrChromatograms(), 1) } // now test with numpress (accuracy is lower) TOLERANCE_RELATIVE(1+2e-4) // delete file if present file.remove(); { MzMLSqliteHandler handler(tmp_filename, 12345); handler.setConfig(true, true, 0.0001); // writing without creating the tables / indices won't work TEST_EXCEPTION(Exception::IllegalArgument, handler.writeChromatograms(exp_orig.getChromatograms())); // now it will work handler.createTables(); handler.createTables(); handler.writeChromatograms(exp_orig.getChromatograms()); TEST_EQUAL(handler.getNrChromatograms(), 1) handler.writeChromatograms(exp_orig.getChromatograms()); TEST_EQUAL(handler.getNrChromatograms(), 2) handler.writeChromatograms(exp_orig.getChromatograms()); TEST_EQUAL(handler.getNrChromatograms(), 3) handler.writeRunLevelInformation(exp_orig, false); MSExperiment tmp; handler.readExperiment(tmp, false); TEST_EQUAL(tmp.getNrChromatograms(), 3) TEST_EQUAL(tmp.getChromatograms()[0].size(), 48) TEST_EQUAL(tmp.getChromatograms()[1].size(), 48) TEST_EQUAL(tmp.getChromatograms()[2].size(), 48) TEST_REAL_SIMILAR(tmp.getChromatograms()[0][20].getRT(), 0.200695) TEST_REAL_SIMILAR(tmp.getChromatograms()[0][20].getIntensity(), 147414.578125) // clear handler.createTables(); handler.writeChromatograms(exp_orig.getChromatograms()); TEST_EQUAL(handler.getNrChromatograms(), 1) } } END_SECTION // reset error tolerances to default values TOLERANCE_ABSOLUTE(1e-5) TOLERANCE_RELATIVE(1+1e-5) ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IntegerMassDecomposer_test.cpp
.cpp
2,708
106
// 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/CHEMISTRY/MASSDECOMPOSITION/IMS/IntegerMassDecomposer.h> /////////////////////////// #include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabet.h> #include <OpenMS/CHEMISTRY/ResidueDB.h> #include <OpenMS/CHEMISTRY/Residue.h> #include <map> using namespace OpenMS; using namespace ims; using namespace std; Weights createWeights() { std::map<char, double> aa_to_weight; set<const Residue*> residues = ResidueDB::getInstance()->getResidues("Natural19WithoutI"); for (set<const Residue*>::const_iterator it = residues.begin(); it != residues.end(); ++it) { aa_to_weight[(*it)->getOneLetterCode()[0]] = (*it)->getMonoWeight(Residue::Internal); } // init mass decomposer IMSAlphabet alphabet; for (std::map<char, double>::const_iterator it = aa_to_weight.begin(); it != aa_to_weight.end(); ++it) { alphabet.push_back(String(it->first), it->second); } // initializes weights Weights weights(alphabet.getMasses(), 0.01); // optimize alphabet by dividing by gcd weights.divideByGCD(); return weights; } START_TEST(IntegerMassDecomposer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// IntegerMassDecomposer<>* ptr = nullptr; IntegerMassDecomposer<>* null_ptr = nullptr; START_SECTION((IntegerMassDecomposer(const Weights &alphabet_))) { ptr = new IntegerMassDecomposer<>(createWeights()); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~IntegerMassDecomposer()) { delete ptr; } END_SECTION START_SECTION((bool exist(value_type mass))) { // TODO } END_SECTION START_SECTION((IntegerMassDecomposer< ValueType, DecompositionValueType >::decomposition_type getDecomposition(value_type mass))) { // TODO } END_SECTION START_SECTION((IntegerMassDecomposer< ValueType, DecompositionValueType >::decompositions_type getAllDecompositions(value_type mass))) { // TODO } END_SECTION START_SECTION((IntegerMassDecomposer< ValueType, DecompositionValueType >::decomposition_value_type getNumberOfDecompositions(value_type mass))) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MapAlignmentEvaluationAlgorithmPrecision_test.cpp
.cpp
2,098
61
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Katharina Albers $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentEvaluationAlgorithmPrecision.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MapAlignmentEvaluationAlgorithmPrecision, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MapAlignmentEvaluationAlgorithmPrecision* ptr = nullptr; MapAlignmentEvaluationAlgorithmPrecision* nullPointer = nullptr; START_SECTION((MapAlignmentEvaluationAlgorithmPrecision())) ptr = new MapAlignmentEvaluationAlgorithmPrecision(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~MapAlignmentEvaluationAlgorithmPrecision())) delete ptr; END_SECTION START_SECTION((virtual void evaluate(const ConsensusMap &consensus_map_in, const ConsensusMap &consensus_map_gt, const double &rt_dev, const double &mz_dev, const Peak2D::IntensityType &int_dev, const bool use_charge, double &out))) MapAlignmentEvaluationAlgorithmPrecision maea; ConsensusMap in; ConsensusMap gt; double out; ConsensusXMLFile consensus_xml_file_in; consensus_xml_file_in.load( OPENMS_GET_TEST_DATA_PATH("MapAlignmentEvaluationAlgorithm_in.consensusXML"), in ); ConsensusXMLFile consensus_xml_file_gt; consensus_xml_file_gt.load( OPENMS_GET_TEST_DATA_PATH("MapAlignmentEvaluationAlgorithm_gt.consensusXML"), gt ); maea.evaluate(in, gt, 0.1, 0.1, 100, true, out); TEST_REAL_SIMILAR(out, 0.757143) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AScore_test.cpp
.cpp
28,603
693
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Petra Gutenbrunner $ // $Authors: David Wojnar, Petra Gutenbrunner $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/DTAFile.h> /////////////////////////// #include <OpenMS/ANALYSIS/ID/AScore.h> /////////////////////////// using namespace OpenMS; using namespace std; class AScoreTest : public AScore { public: void computeSiteDeterminingIonsTest_(const std::vector<PeakSpectrum>& th_spectra, const ProbablePhosphoSites& candidates, std::vector<PeakSpectrum>& site_determining_ions) const { return computeSiteDeterminingIons_(th_spectra, candidates, site_determining_ions); } std::vector<Size> getSitesTest_(String& without_phospho) const { return getSites_(without_phospho); } std::vector<std::vector<Size> > computePermutationsTest_(const std::vector<Size>& sites, Int n_phosphorylation_events) const { return computePermutations_(sites, n_phosphorylation_events); } Size numberOfMatchedIonsTest_(const PeakSpectrum& th, const PeakSpectrum& windows, Size depth) const { return numberOfMatchedIons_(th, windows, depth); } //double peptideScoreTest_(const std::vector<double>& scores) const; void determineHighestScoringPermutationsTest_(const std::vector<std::vector<double>>& peptide_site_scores, std::vector<ProbablePhosphoSites>& sites, const std::vector<std::vector<Size>>& permutations, std::multimap<double, Size>& ranking) const { return determineHighestScoringPermutations_(peptide_site_scores, sites, permutations, ranking); } double computeCumulativeScoreTest_(Size N, Size n, double p) const { return computeCumulativeScore_(N, n, p); } //Size numberOfPhosphoEventsTest_(const String sequence) const; AASequence removePhosphositesFromSequenceTest_(const String sequence) const { return removePhosphositesFromSequence_(sequence); } std::vector<PeakSpectrum> createTheoreticalSpectraTest_(const std::vector<std::vector<Size>>& permutations, const AASequence& seq_without_phospho) const { return createTheoreticalSpectra_(permutations, seq_without_phospho); } std::vector<PeakSpectrum> peakPickingPerWindowsInSpectrumTest_(PeakSpectrum& real_spectrum) const { return peakPickingPerWindowsInSpectrum_(real_spectrum); } //std::vector<std::vector<double>> calculatePermutationPeptideScoresTest_(std::vector<PeakSpectrum>& th_spectra, const std::vector<PeakSpectrum>& windows_top10) const; std::multimap<double, Size> rankWeightedPermutationPeptideScoresTest_(const std::vector<std::vector<double>>& peptide_site_scores) const { return rankWeightedPermutationPeptideScores_(peptide_site_scores); } }; /////////////////////////// /////////////////////////// START_TEST(AScore, "$Id$") //============================================================================= // create spectrum (see Beausoleil et al. Figure 3) //============================================================================= PeakSpectrum tmp; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("Ascore_test_input3.dta"), tmp); //============================================================================= AASequence seq_without_phospho = AASequence::fromString("QSSVTQVTEQSPK"); //============================================================================= //============================================================================= // create permutations based on sequence QSSVTQVTEQSPK //============================================================================= std::vector<std::vector<Size>> permutations = { {1}, {2}, {4}, {7}, {10} }; //============================================================================= AScore* ptr = nullptr; AScore* nullPointer = nullptr; START_SECTION(AScore()) { ptr = new AScore(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~AScore()) { delete ptr; } END_SECTION AScoreTest* ptr_test = new AScoreTest(); START_SECTION(double computeCumulativeScoreTest_(Size N, Size n, double p)) { Size n = 5; Size N = 1; double p = 0.1; TEST_PRECONDITION_VIOLATED(ptr_test->computeCumulativeScoreTest_(N, n, p)); n = 1; double score = ptr_test->computeCumulativeScoreTest_(N, n, p); TEST_REAL_SIMILAR(score, 0.1); N = 3; score = ptr_test->computeCumulativeScoreTest_(N, n, p); TEST_REAL_SIMILAR(score, 0.271); } END_SECTION START_SECTION(determineHighestScoringPermutationsTest_(const std::vector<std::vector<double>>& peptide_site_scores, std::vector<ProbablePhosphoSites>& sites, const std::vector<std::vector<Size>>& permutations)) { std::multimap<double, Size> ranking; std::vector<std::vector<double>> peptide_site_scores_1; std::vector<std::vector<double>> peptide_site_scores_2; std::vector<std::vector<double>> peptide_site_scores_3; peptide_site_scores_1.resize(4); peptide_site_scores_2.resize(4); peptide_site_scores_3.resize(4); vector<double> temp(10, 0.1); peptide_site_scores_1[0] = temp; peptide_site_scores_2[3] = temp; peptide_site_scores_3[0] = temp; temp = vector<double>(10, 0.2); peptide_site_scores_1[1] = temp; peptide_site_scores_2[0] = temp; peptide_site_scores_3[3] = temp; temp = vector<double>(10, 0.3); peptide_site_scores_1[2] = temp; peptide_site_scores_2[1] = temp; peptide_site_scores_3[2] = temp; temp = vector<double>(10, 0.4); peptide_site_scores_1[3] = temp; peptide_site_scores_2[2] = temp; peptide_site_scores_3[1] = temp; vector<vector<Size>> permutations{ {1,3,5}, {3,5,6}, {1,3,6}, {1,5,6} }; vector<ProbablePhosphoSites> sites; ranking = ptr_test->rankWeightedPermutationPeptideScoresTest_(peptide_site_scores_1); TEST_REAL_SIMILAR( ranking.rbegin()->first, .4); ptr_test->determineHighestScoringPermutationsTest_(peptide_site_scores_1, sites, permutations,ranking); TEST_EQUAL(sites.size(), 3); TEST_EQUAL(sites[0].seq_1, 3); TEST_EQUAL(sites[0].seq_2, 1); TEST_EQUAL(sites[0].second, 3); TEST_EQUAL(sites[0].first, 1); TEST_EQUAL(sites[0].peak_depth, 1); TEST_EQUAL(sites[1].first, 5); TEST_EQUAL(sites[1].second, 3); TEST_EQUAL(sites[1].seq_1, 3); TEST_EQUAL(sites[1].seq_2, 2); TEST_EQUAL(sites[1].peak_depth, 1); TEST_EQUAL(sites[2].first, 6); TEST_EQUAL(sites[2].second, 3); TEST_EQUAL(sites[2].seq_1, 3); TEST_EQUAL(sites[2].seq_2, 0); TEST_EQUAL(sites[2].peak_depth, 1); ranking = ptr_test->rankWeightedPermutationPeptideScoresTest_(peptide_site_scores_3); TEST_REAL_SIMILAR(ranking.rbegin()->first, .4); ptr_test->determineHighestScoringPermutationsTest_(peptide_site_scores_3, sites, permutations, ranking); TEST_EQUAL(sites.size(), 3); TEST_EQUAL(sites[0].seq_1, 1); TEST_EQUAL(sites[0].seq_2, 3); TEST_EQUAL(sites[0].second, 1); TEST_EQUAL(sites[0].first, 3); TEST_EQUAL(sites[0].peak_depth, 1); TEST_EQUAL(sites[1].first, 5); TEST_EQUAL(sites[1].second, 1); TEST_EQUAL(sites[1].seq_1, 1); TEST_EQUAL(sites[1].seq_2, 2); TEST_EQUAL(sites[1].peak_depth, 1); TEST_EQUAL(sites[2].first, 6); TEST_EQUAL(sites[2].second, 1); TEST_EQUAL(sites[2].seq_1, 1); TEST_EQUAL(sites[2].seq_2, 0); TEST_EQUAL(sites[2].peak_depth, 1); ranking = ptr_test->rankWeightedPermutationPeptideScoresTest_(peptide_site_scores_2); TEST_REAL_SIMILAR(ranking.rbegin()->first, .4); ptr_test->determineHighestScoringPermutationsTest_(peptide_site_scores_2, sites, permutations, ranking); TEST_EQUAL(sites.size(), 3); TEST_EQUAL(sites[0].seq_1, 2); TEST_EQUAL(sites[0].seq_2, 1); TEST_EQUAL(sites[0].second, 5); TEST_EQUAL(sites[0].first, 1); TEST_EQUAL(sites[0].peak_depth, 1); TEST_EQUAL(sites[1].first, 3); TEST_EQUAL(sites[1].second, 5); TEST_EQUAL(sites[1].seq_1, 2); TEST_EQUAL(sites[1].seq_2, 3); TEST_EQUAL(sites[1].peak_depth, 1); TEST_EQUAL(sites[2].first, 6); TEST_EQUAL(sites[2].second, 5); TEST_EQUAL(sites[2].seq_1, 2); TEST_EQUAL(sites[2].seq_2, 0); TEST_EQUAL(sites[2].peak_depth, 1) peptide_site_scores_1.clear(); temp = {55, 60, 75, 100, 90, 120, 125, 120, 100, 90}; peptide_site_scores_1.push_back(temp); temp = { 40, 50, 53, 60, 50, 53, 59, 53, 50, 40 }; peptide_site_scores_1.push_back(temp); permutations = { {3}, {6} }; ranking = ptr_test->rankWeightedPermutationPeptideScoresTest_(peptide_site_scores_1); TEST_REAL_SIMILAR(ranking.rbegin()->first, 94.10714285714287); ptr_test->determineHighestScoringPermutationsTest_(peptide_site_scores_1, sites, permutations, ranking); TEST_EQUAL(sites.size(), 1) TEST_EQUAL(sites[0].seq_1, 0) TEST_EQUAL(sites[0].seq_2, 1) TEST_EQUAL(sites[0].first, 3); TEST_EQUAL(sites[0].second, 6); TEST_EQUAL(sites[0].peak_depth, 6) permutations = { {3, 5}, {5, 6}, {3, 7}, {3, 6}, {5, 7}, {6, 7} }; peptide_site_scores_1.push_back(temp); peptide_site_scores_1.push_back(temp); peptide_site_scores_1.push_back(temp); peptide_site_scores_1.push_back(temp); ranking = ptr_test->rankWeightedPermutationPeptideScoresTest_(peptide_site_scores_1); ptr_test->determineHighestScoringPermutationsTest_(peptide_site_scores_1, sites, permutations, ranking); TEST_EQUAL(sites.size(), 2); TEST_EQUAL(sites[0].seq_1, 0); TEST_EQUAL(sites[0].seq_2, 4); TEST_EQUAL(sites[0].first, 3); TEST_EQUAL(sites[0].second, 7); TEST_EQUAL(sites[0].peak_depth, 6); TEST_EQUAL(sites[1].seq_1, 0); TEST_EQUAL(sites[1].seq_2, 3); TEST_EQUAL(sites[1].first, 5); TEST_EQUAL(sites[1].second, 6); TEST_EQUAL(sites[1].peak_depth, 6); } END_SECTION START_SECTION(computeSiteDeterminingIonsTest_(const std::vector<PeakSpectrum>& th_spectra, const ProbablePhosphoSites& candidates, std::vector<PeakSpectrum>& site_determining_ions)) { ProbablePhosphoSites candidates; PeakSpectrum temp1, temp2; vector<PeakSpectrum> site_determining_ions; AASequence seq = seq_without_phospho; vector<PeakSpectrum> th_s = ptr_test->createTheoreticalSpectraTest_(permutations, seq); candidates.seq_1 = 3; candidates.seq_2 = 4; candidates.first = 10; candidates.second = 7; ptr_test->computeSiteDeterminingIonsTest_(th_s, candidates, site_determining_ions); TEST_EQUAL(site_determining_ions.size(), 2); TEST_EQUAL(site_determining_ions[0].size(), 6); TEST_EQUAL(site_determining_ions[1].size(), 6); //============================================================================= th_s.clear(); seq = AASequence::fromString("VTEQSP"); candidates.seq_1 = 0; candidates.seq_2 = 1; candidates.first = 1; candidates.second = 4; vector<vector<Size>> p { {candidates.first}, {candidates.second} }; th_s = ptr_test->createTheoreticalSpectraTest_(p, seq); ptr_test->computeSiteDeterminingIonsTest_(th_s, candidates, site_determining_ions); TEST_EQUAL(site_determining_ions.size(), 2); TEST_EQUAL(site_determining_ions[0].size(), 6); TEST_EQUAL(site_determining_ions[1].size(), 6); TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(), 203.102); TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size() - 1].getMZ(), 538.19); TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(), 201.123); TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size() - 1].getMZ(), 540.17); candidates.first = 4; candidates.second = 1; candidates.seq_1 = 1; candidates.seq_2 = 0; ptr_test->computeSiteDeterminingIonsTest_(th_s, candidates, site_determining_ions); TEST_EQUAL(site_determining_ions.size(), 2); TEST_EQUAL(site_determining_ions[0].size(), 6); TEST_EQUAL(site_determining_ions[1].size(), 6); TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(), 203.102); TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size() - 1].getMZ(), 538.19); TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(), 201.123); TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size() - 1].getMZ(), 540.17); //============================================================================= th_s.clear(); seq = AASequence::fromString("TYQYS"); candidates.seq_1 = 0; candidates.seq_2 = 1; candidates.first = 0; candidates.second = 4; p = { { candidates.first },{ candidates.second } }; th_s = ptr_test->createTheoreticalSpectraTest_(p, seq); ptr_test->computeSiteDeterminingIonsTest_(th_s, candidates, site_determining_ions); TEST_EQUAL(site_determining_ions.size(), 2); TEST_EQUAL(site_determining_ions[0].size(), 7); TEST_EQUAL(site_determining_ions[1].size(), 7); TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(), 106.05); TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size() - 1].getMZ(), 636.206); TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(), 186.016); TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size() - 1].getMZ(), 640.201); candidates.first = 4; candidates.second = 0; candidates.seq_1 = 1; candidates.seq_2 = 0; ptr_test->computeSiteDeterminingIonsTest_(th_s, candidates, site_determining_ions); TEST_EQUAL(site_determining_ions.size(), 2); TEST_EQUAL(site_determining_ions[0].size(), 7); TEST_EQUAL(site_determining_ions[1].size(), 7); TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(), 106.05); TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size() - 1].getMZ(), 636.206); TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(), 186.016); TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size() - 1].getMZ(), 640.201); //============================================================================= th_s.clear(); seq = AASequence::fromString("TSTYQYSYPP"); candidates.seq_1 = 0; candidates.seq_2 = 1; candidates.first = 2; candidates.second = 6; p = { { candidates.first },{ candidates.second } }; th_s = ptr_test->createTheoreticalSpectraTest_(p, seq); ptr_test->computeSiteDeterminingIonsTest_(th_s, candidates, site_determining_ions); TEST_EQUAL(site_determining_ions.size(), 2); TEST_EQUAL(site_determining_ions[0].size(), 8); TEST_EQUAL(site_determining_ions[1].size(), 8); TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(), 370.101); TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size() - 1].getMZ(), 917.403); TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(), 290.135); TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size() - 1].getMZ(), 997.37); candidates.seq_1 = 1; candidates.seq_2 = 0; candidates.first = 6; candidates.second = 2; ptr_test->computeSiteDeterminingIonsTest_(th_s, candidates, site_determining_ions); TEST_EQUAL(site_determining_ions.size(), 2); TEST_EQUAL(site_determining_ions[0].size(), 8); TEST_EQUAL(site_determining_ions[1].size(), 8); TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(), 370.101); TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size() - 1].getMZ(), 917.403); TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(), 290.135); TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size() - 1].getMZ(), 997.37); //============================================================================= //ATPGNLGSSVLMY(Phospho)K; ATPGNLGSS(Phospho)VLMYK th_s.clear(); seq = AASequence::fromString("ATPGNLGSSVLMYK"); candidates.seq_1 = 0; candidates.seq_2 = 1; candidates.first = 12; candidates.second = 8; p = { { candidates.first },{ candidates.second } }; th_s = ptr_test->createTheoreticalSpectraTest_(p, seq); ptr_test->computeSiteDeterminingIonsTest_(th_s, candidates, site_determining_ions); TEST_EQUAL(site_determining_ions.size(), 2); TEST_EQUAL(site_determining_ions[0].size(), 8); TEST_EQUAL(site_determining_ions[1].size(), 4); TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(), 390.142); TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size() - 1].getMZ(), 1128.57); TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(), 310.176); TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size() - 1].getMZ(), 1208.54); candidates.seq_1 = 1; candidates.seq_2 = 0; candidates.first = 8; candidates.second = 12; ptr_test->computeSiteDeterminingIonsTest_(th_s, candidates, site_determining_ions); TEST_EQUAL(site_determining_ions.size(), 2); TEST_EQUAL(site_determining_ions[0].size(), 4); TEST_EQUAL(site_determining_ions[1].size(), 8); TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(), 390.142); TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size() - 1].getMZ(), 1128.57); TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(), 310.176); TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size() - 1].getMZ(), 1208.54); } END_SECTION START_SECTION(std::vector<Size> getSitesTest_(const AASequence& without_phospho)) { AASequence phospho = AASequence::fromString("VTQSPSSP"); String unmodified_sequence = phospho.toUniModString(); vector<Size> tupel(ptr_test->getSitesTest_(unmodified_sequence)); TEST_EQUAL(4, tupel.size()) TEST_EQUAL(1, tupel[0]) TEST_EQUAL(3, tupel[1]) TEST_EQUAL(5, tupel[2]) TEST_EQUAL(6, tupel[3]) } END_SECTION START_SECTION(std::vector<std::vector<Size>> computePermutationsTest_(const std::vector<Size>& tupel, Int number_of_phospho_sites)) { vector<Size> tupel{1, 2, 3, 4}; vector<vector<Size> > permutations; permutations = ptr_test->computePermutationsTest_(tupel, 1); TEST_EQUAL(4, permutations.size()); TEST_EQUAL(1, permutations[0][0]); TEST_EQUAL(2, permutations[1][0]); TEST_EQUAL(3, permutations[2][0]); TEST_EQUAL(4, permutations[3][0]); permutations = ptr_test->computePermutationsTest_(tupel, 2); TEST_EQUAL(6, permutations.size()); TEST_EQUAL(1, permutations[0][0]); TEST_EQUAL(2, permutations[0][1]); TEST_EQUAL(1, permutations[1][0]); TEST_EQUAL(3, permutations[1][1]); TEST_EQUAL(1, permutations[2][0]); TEST_EQUAL(4, permutations[2][1]); TEST_EQUAL(2, permutations[3][0]); TEST_EQUAL(3, permutations[3][1]); TEST_EQUAL(2, permutations[4][0]); TEST_EQUAL(4, permutations[4][1]); TEST_EQUAL(3, permutations[5][0]); TEST_EQUAL(4, permutations[5][1]); permutations = ptr_test->computePermutationsTest_(tupel, 3); TEST_EQUAL(4, permutations.size()); TEST_EQUAL(1, permutations[0][0]); TEST_EQUAL(2, permutations[0][1]); TEST_EQUAL(3, permutations[0][2]); TEST_EQUAL(1, permutations[1][0]); TEST_EQUAL(2, permutations[1][1]); TEST_EQUAL(4, permutations[1][2]); TEST_EQUAL(1, permutations[2][0]); TEST_EQUAL(3, permutations[2][1]); TEST_EQUAL(4, permutations[2][2]); TEST_EQUAL(2, permutations[3][0]); TEST_EQUAL(3, permutations[3][1]); TEST_EQUAL(4, permutations[3][2]); permutations = ptr_test->computePermutationsTest_(tupel, 4); TEST_EQUAL(1, permutations.size()); TEST_EQUAL(1, permutations[0][0]); TEST_EQUAL(2, permutations[0][1]); TEST_EQUAL(3, permutations[0][2]); TEST_EQUAL(4, permutations[0][3]); tupel.clear(); permutations = ptr_test->computePermutationsTest_(tupel, 0); TEST_EQUAL(0, permutations.size()); } END_SECTION START_SECTION(AASequence removePhosphositesFromSequenceTest_(const String sequence)) { String sequence = "QSSVTQVTEQS(Phospho)PK"; TEST_EQUAL(ptr_test->removePhosphositesFromSequenceTest_(sequence).toString(), "QSSVTQVTEQSPK"); } END_SECTION START_SECTION(std::vector<PeakSpectrum> peakPickingPerWindowsInSpectrumTest_(PeakSpectrum& real_spectrum)) { PeakSpectrum& real_spectrum = tmp; std::vector<PeakSpectrum> windows_top10 = ptr_test->peakPickingPerWindowsInSpectrumTest_(real_spectrum); TEST_EQUAL(windows_top10.size(), 8); TEST_EQUAL(windows_top10[0].size(), 1); TEST_EQUAL(windows_top10[1].size(), 1); TEST_EQUAL(windows_top10[4].size(), 0); TEST_EQUAL(windows_top10[7].size(), 1); } END_SECTION START_SECTION(Size numberOfMatchedIonsTest_(const PeakSpectrum& th, const PeakSpectrum& windows, Size depth)) { PeakSpectrum& real_spectrum = tmp; Param params; params.setValue("fragment_mass_tolerance", 0.5); ptr_test->setParameters(params); vector<PeakSpectrum> th_spectra = ptr_test->createTheoreticalSpectraTest_(permutations, seq_without_phospho); std::vector<PeakSpectrum> windows_top10 = ptr_test->peakPickingPerWindowsInSpectrumTest_(real_spectrum); //QSSVTQVTEQS(phospho)PK vector<PeakSpectrum>::iterator it = th_spectra.end() - 1; TEST_EQUAL(ptr_test->numberOfMatchedIonsTest_(*it, windows_top10[0], 1), 1); TEST_EQUAL(ptr_test->numberOfMatchedIonsTest_(*it, windows_top10[1], 1), 1); } END_SECTION // of best peptide START_SECTION(calculateCumulativeBinominalProbabilityScore) { vector<ProbablePhosphoSites> phospho_sites; phospho_sites.clear(); phospho_sites.resize(1); phospho_sites[0].seq_1 = 4; phospho_sites[0].seq_2 = 3; phospho_sites[0].peak_depth = 6; phospho_sites[0].first = 10; phospho_sites[0].second = 7; PeakSpectrum& real_spectrum = tmp; std::vector<PeakSpectrum> windows_top10 = ptr_test->peakPickingPerWindowsInSpectrumTest_(real_spectrum); vector<PeakSpectrum> th_spectra = ptr_test->createTheoreticalSpectraTest_(permutations, seq_without_phospho); for (vector<ProbablePhosphoSites>::iterator s_it = phospho_sites.begin(); s_it < phospho_sites.end(); ++s_it) { vector<PeakSpectrum> site_determining_ions; ptr_test->computeSiteDeterminingIonsTest_(th_spectra, *s_it, site_determining_ions); Size N = site_determining_ions[0].size(); // all possibilities have the same number so take the first one double p = static_cast<double>(s_it->peak_depth) / 100.0; Size n_first = 0; for (Size depth = 0; depth != windows_top10.size(); ++depth) // for each 100 m/z window { n_first += ptr_test->numberOfMatchedIonsTest_(site_determining_ions[0], windows_top10[depth], s_it->peak_depth); } double P_first = ptr_test->computeCumulativeScoreTest_(N, n_first, p); P_first = -10 * log10(P_first); TEST_REAL_SIMILAR(P_first, 53.5336889240929); } } END_SECTION START_SECTION(std::vector<PeakSpectrum> createTheoreticalSpectraTest_(const std::vector<std::vector<Size>>& permutations, const AASequence& seq_without_phospho)) { // create theoretical based on permutations vector<PeakSpectrum> th_spectra(ptr_test->createTheoreticalSpectraTest_(permutations, seq_without_phospho)); TEST_EQUAL(th_spectra.size(), 5); TEST_EQUAL(th_spectra[0].getName(), "QS(Phospho)SVTQVTEQSPK"); TEST_EQUAL(th_spectra[4].getName(), "QSSVTQVTEQS(Phospho)PK"); TEST_REAL_SIMILAR(th_spectra[4][0].getMZ(), 147.11340); TEST_REAL_SIMILAR(th_spectra[4][2].getMZ(), 244.166); TEST_REAL_SIMILAR(th_spectra[4][21].getMZ(), 1352.57723); th_spectra.clear(); } END_SECTION START_SECTION(PeptideHit AScore::compute(const PeptideHit& hit, PeakSpectrum& real_spectrum) const) { // ==================================================================================================================================== // The Ascore results differ to the results of the Ascore tool provided on the website http://ascore.med.harvard.edu/ascore.html // But it seems that the online version has some issues calculating the Ascore using the cumulative binomial probability formula. // E.g. with the values 6, 5, 0.06 for the variables N, n, p the calculated Ascore using WolframAlpha is 53.5337, which does not // conform to the result 53.57, which is mentioned in the paper (see Fig. 3c). // In addition the site determining ions calculation seems not reliable, because in some test cases more site determining ions // were calculated than it could be possible. // Another reason for the differences of the results could be the fragment ion tolerance used to match the theoretical spectra // with the real spectra. The value used in the Ascore tool provided on the website is not mentioned. // ==================================================================================================================================== PeakSpectrum real_spectrum; Param params; params.setValue("fragment_mass_tolerance", 0.6); ptr_test->setParameters(params); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("Ascore_test_input1.dta"), real_spectrum); PeptideHit hit1(1.0, 1, 1, AASequence::fromString("QSSVT(Phospho)QSK")); hit1 = ptr_test->compute(hit1, real_spectrum); // http://ascore.med.harvard.edu/ascore.html result=3.51, sequence=QSSVT*QSK TEST_REAL_SIMILAR(static_cast<double>(hit1.getMetaValue("AScore_1")), 8.65157151899052); TEST_EQUAL(hit1.getSequence().toString(), "QSS(Phospho)VTQSK"); // =========================================================================== DTAFile().load(OPENMS_GET_TEST_DATA_PATH("Ascore_test_input2.dta"), real_spectrum); PeptideHit hit2(1.0, 1, 1, AASequence::fromString("RIRLT(Phospho)ATTR")); hit2 = ptr_test->compute(hit2, real_spectrum); // http://ascore.med.harvard.edu/ascore.html result=21.3 TEST_REAL_SIMILAR(static_cast<double>(hit2.getMetaValue("AScore_1")), 18.8755623850511); TEST_EQUAL(hit2.getSequence().toString(), "RIRLT(Phospho)ATTR"); // =========================================================================== DTAFile().load(OPENMS_GET_TEST_DATA_PATH("Ascore_test_input3.dta"), real_spectrum); PeptideHit hit3(1.0, 1, 1, AASequence::fromString("QSSVTQVTEQS(Phospho)PK")); hit3 = ptr_test->compute(hit3, real_spectrum); // http://ascore.med.harvard.edu/ascore.html result=88.3 TEST_REAL_SIMILAR(static_cast<double>(hit3.getMetaValue("AScore_1")), 88.3030731386678); TEST_EQUAL(hit3.getSequence().toString(), "QSSVTQVTEQS(Phospho)PK"); // =========================================================================== params.setValue("fragment_mass_tolerance", 0.05); ptr_test->setParameters(params); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("Ascore_test_input4.dta"), real_spectrum); PeptideHit hit4(1.0, 1, 1, AASequence::fromString("ATPGNLGSSVLHS(Phospho)K")); hit4 = ptr_test->compute(hit4, real_spectrum); // http://ascore.med.harvard.edu/ascore.html result=88.3 TEST_REAL_SIMILAR(static_cast<double>(hit4.getMetaValue("AScore_1")), 49.2714597801023); TEST_EQUAL(hit4.getSequence().toString(), "ATPGNLGSSVLHS(Phospho)K"); // =========================================================================== // PPM UNIT TEST // =========================================================================== params.setValue("fragment_mass_tolerance", 700.0); // 0.6 Da were converted to ppm based on a small peptide params.setValue("fragment_mass_unit", "ppm"); ptr_test->setParameters(params); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("Ascore_test_input1.dta"), real_spectrum); PeptideHit hit5(1.0, 1, 1, AASequence::fromString("QSSVT(Phospho)QSK")); hit5 = ptr_test->compute(hit5, real_spectrum); // http://ascore.med.harvard.edu/ascore.html result=3.51, sequence=QSSVT*QSK TEST_REAL_SIMILAR(static_cast<double>(hit5.getMetaValue("AScore_1")), 6.53833235677545); TEST_EQUAL(hit5.getSequence().toString(), "QSS(Phospho)VTQSK"); params.setValue("fragment_mass_tolerance", 70.0); // 0.05 Da were converted to ppm based on a small peptide ptr_test->setParameters(params); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("Ascore_test_input4.dta"), real_spectrum); PeptideHit hit6(1.0, 1, 1, AASequence::fromString("ATPGNLGSSVLHS(Phospho)K")); hit6 = ptr_test->compute(hit6, real_spectrum); // http://ascore.med.harvard.edu/ascore.html result=88.3 TEST_REAL_SIMILAR(static_cast<double>(hit6.getMetaValue("AScore_1")), 40.6506162613816); TEST_EQUAL(hit6.getSequence().toString(), "ATPGNLGSSVLHS(Phospho)K"); // =========================================================================== // check if special score is used for unambiguous assignment: PeptideHit hit7(1.0, 1, 1, AASequence::fromString("PEPT(Phospho)IDE")); hit7 = ptr_test->compute(hit7, real_spectrum); TEST_REAL_SIMILAR(hit7.getScore(), ptr_test->getParameters().getValue("unambiguous_score")); } END_SECTION delete ptr_test; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SpectrumAccessSqMass_test.cpp
.cpp
7,315
241
// 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/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessSqMass.h> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> #include <OpenMS/FORMAT/HANDLERS/MzMLSqliteHandler.h> #include <OpenMS/FORMAT/HANDLERS/MzMLSqliteSwathHandler.h> using namespace OpenMS; using namespace std; START_TEST(SpectrumAccessSqMass, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// SpectrumAccessSqMass* ptr = nullptr; SpectrumAccessSqMass* nullPointer = nullptr; std::shared_ptr<PeakMap > exp(new PeakMap); OpenSwath::SpectrumAccessPtr expptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp); START_SECTION(SpectrumAccessSqMass(OpenMS::Internal::MzMLSqliteHandler handler)) { OpenMS::Internal::MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); ptr = new SpectrumAccessSqMass(handler); TEST_NOT_EQUAL(ptr, nullPointer) delete ptr; } END_SECTION START_SECTION(SpectrumAccessSqMass(const OpenMS::Internal::MzMLSqliteHandler& handler, const std::vector<int> & indices)) { OpenMS::Internal::MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); std::vector<int> indices; indices.push_back(1); ptr = new SpectrumAccessSqMass(handler, indices); TEST_NOT_EQUAL(ptr, nullPointer) TEST_EQUAL(ptr->getNrSpectra(), 1) delete ptr; } END_SECTION START_SECTION(SpectrumAccessSqMass(const SpectrumAccessSqMass& sp, const std::vector<int>& indices)) { OpenMS::Internal::MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); ptr = new SpectrumAccessSqMass(handler); TEST_NOT_EQUAL(ptr, nullPointer) TEST_EQUAL(ptr->getNrSpectra(), 2) delete ptr; SpectrumAccessSqMass sasm(handler); // select subset of the data (all two spectra) { std::vector<int> indices; indices.push_back(0); indices.push_back(1); ptr = new SpectrumAccessSqMass(sasm, indices); TEST_NOT_EQUAL(ptr, nullPointer) TEST_EQUAL(ptr->getNrSpectra(), 2) delete ptr; } // select subset of the data (only second spectrum) { std::vector<int> indices; indices.push_back(1); ptr = new SpectrumAccessSqMass(sasm, indices); TEST_NOT_EQUAL(ptr, nullPointer) TEST_EQUAL(ptr->getNrSpectra(), 1) } // this should not work: // selecting subset of data (only second spectrum) shouldn't work if there is only a single spectrum { std::vector<int> indices; indices.push_back(1); TEST_EXCEPTION(Exception::IllegalArgument, new SpectrumAccessSqMass(*ptr, indices)) std::vector<int> indices2; indices2.push_back(50); TEST_EXCEPTION(Exception::IllegalArgument, new SpectrumAccessSqMass(*ptr, indices)) } } END_SECTION START_SECTION(~SpectrumAccessSqMass()) { delete ptr; } END_SECTION START_SECTION(size_t getNrSpectra() const) { OpenMS::Internal::MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); ptr = new SpectrumAccessSqMass(handler); TEST_EQUAL(ptr->getNrSpectra(), 2) delete ptr; } END_SECTION START_SECTION(std::shared_ptr<OpenSwath::ISpectrumAccess> lightClone() const) { OpenMS::Internal::MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); ptr = new SpectrumAccessSqMass(handler); TEST_EQUAL(ptr->getNrSpectra(), 2) std::shared_ptr<OpenSwath::ISpectrumAccess> ptr2 = ptr->lightClone(); TEST_EQUAL(ptr2->getNrSpectra(), 2) delete ptr; } END_SECTION START_SECTION(void getAllSpectra(std::vector< OpenSwath::SpectrumPtr > & spectra, std::vector< OpenSwath::SpectrumMeta > & spectra_meta)) { OpenMS::Internal::MzMLSqliteHandler handler(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), 0); { ptr = new SpectrumAccessSqMass(handler); TEST_EQUAL(ptr->getNrSpectra(), 2) std::vector< OpenSwath::SpectrumPtr > spectra; std::vector< OpenSwath::SpectrumMeta > spectra_meta; ptr->getAllSpectra(spectra, spectra_meta); TEST_EQUAL(spectra.size(), 2) TEST_EQUAL(spectra_meta.size(), 2) TEST_EQUAL(spectra[0]->getMZArray()->data.size(), 19914) TEST_EQUAL(spectra[0]->getIntensityArray()->data.size(), 19914) TEST_EQUAL(spectra[1]->getMZArray()->data.size(), 19800) TEST_EQUAL(spectra[1]->getIntensityArray()->data.size(), 19800) delete ptr; } { std::vector<int> indices; indices.push_back(0); indices.push_back(1); ptr = new SpectrumAccessSqMass(handler, indices); TEST_EQUAL(ptr->getNrSpectra(), 2) std::vector< OpenSwath::SpectrumPtr > spectra; std::vector< OpenSwath::SpectrumMeta > spectra_meta; ptr->getAllSpectra(spectra, spectra_meta); TEST_EQUAL(spectra.size(), 2) TEST_EQUAL(spectra_meta.size(), 2) TEST_EQUAL(spectra[0]->getMZArray()->data.size(), 19914) TEST_EQUAL(spectra[0]->getIntensityArray()->data.size(), 19914) TEST_EQUAL(spectra[1]->getMZArray()->data.size(), 19800) TEST_EQUAL(spectra[1]->getIntensityArray()->data.size(), 19800) delete ptr; } // select only 2nd spectrum { std::vector<int> indices; indices.push_back(1); ptr = new SpectrumAccessSqMass(handler, indices); TEST_EQUAL(ptr->getNrSpectra(), 1) std::vector< OpenSwath::SpectrumPtr > spectra; std::vector< OpenSwath::SpectrumMeta > spectra_meta; ptr->getAllSpectra(spectra, spectra_meta); TEST_EQUAL(spectra.size(), 1) TEST_EQUAL(spectra_meta.size(), 1) TEST_EQUAL(spectra[0]->getMZArray()->data.size(), 19800) TEST_EQUAL(spectra[0]->getIntensityArray()->data.size(), 19800) delete ptr; } // select only 2nd spectrum iteratively { std::vector<int> indices; indices.push_back(1); SpectrumAccessSqMass* sasm = new SpectrumAccessSqMass(handler, indices); TEST_EQUAL(sasm->getNrSpectra(), 1) // now we have an interface with a single spectrum in it, so if we select // the first spectrum of THAT interface, it should be the 2nd spectrum from // the initial dataset indices.clear(); // indices.push_back(1); // this should not work as we now have only a single spectrum (out of bounds access!) indices.push_back(0); ptr = new SpectrumAccessSqMass(*sasm, indices); TEST_EQUAL(ptr->getNrSpectra(), 1) std::vector< OpenSwath::SpectrumPtr > spectra; std::vector< OpenSwath::SpectrumMeta > spectra_meta; ptr->getAllSpectra(spectra, spectra_meta); TEST_EQUAL(spectra.size(), 1) TEST_EQUAL(spectra_meta.size(), 1) TEST_EQUAL(spectra[0]->getMZArray()->data.size(), 19800) TEST_EQUAL(spectra[0]->getIntensityArray()->data.size(), 19800) delete ptr; delete sasm; } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ThresholdMower_test.cpp
.cpp
3,257
124
// 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, Andreas Bertsch $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/PROCESSING/FILTERING/ThresholdMower.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/DTAFile.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(ThresholdMower, "$Id$") ///////////////////////////////////////////////////////////// ThresholdMower* e_ptr = nullptr; ThresholdMower* e_nullPointer = nullptr; START_SECTION((ThresholdMower())) e_ptr = new ThresholdMower; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION((~ThresholdMower())) delete e_ptr; END_SECTION e_ptr = new ThresholdMower(); START_SECTION((ThresholdMower(const ThresholdMower& source))) ThresholdMower copy(*e_ptr); TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) TEST_EQUAL(copy.getName(), e_ptr->getName()) END_SECTION START_SECTION((ThresholdMower& operator=(const ThresholdMower& source))) ThresholdMower copy; copy = *e_ptr; TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) TEST_EQUAL(copy.getName(), e_ptr->getName()); END_SECTION START_SECTION((template<typename SpectrumType> void filterSpectrum(SpectrumType& spectrum))) DTAFile dta_file; PeakSpectrum spec; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec); TEST_EQUAL(spec.size(), 121) Param p(e_ptr->getParameters()); p.setValue("threshold", 1.0); e_ptr->setParameters(p); e_ptr->filterSpectrum(spec); TEST_EQUAL(spec.size(), 121) p.setValue("threshold", 10.0); e_ptr->setParameters(p); e_ptr->filterSpectrum(spec); TEST_EQUAL(spec.size(), 14) 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_EQUAL(pm.begin()->size(), 121) Param p(e_ptr->getParameters()); p.setValue("threshold", 1.0); e_ptr->setParameters(p); e_ptr->filterPeakMap(pm); TEST_EQUAL(pm.begin()->size(), 121) p.setValue("threshold", 10.0); e_ptr->setParameters(p); e_ptr->filterPeakMap(pm); TEST_EQUAL(pm.begin()->size(), 14) 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_EQUAL(spec.size(), 121) Param p(e_ptr->getParameters()); p.setValue("threshold", 1.0); e_ptr->setParameters(p); e_ptr->filterPeakSpectrum(spec); TEST_EQUAL(spec.size(), 121) p.setValue("threshold", 10.0); e_ptr->setParameters(p); e_ptr->filterPeakSpectrum(spec); TEST_EQUAL(spec.size(), 14) END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FASTAContainer_test.cpp
.cpp
7,399
229
// 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/DATASTRUCTURES/FASTAContainer.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(FASTAContainer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// typedef FASTAContainer<TFI_Vector> FCVec; typedef FASTAContainer<TFI_File> FCFile; FCVec* ptr = nullptr; FCVec* nullPointer = nullptr; START_SECTION(FASTAContainer()) { ptr = new FCVec(std::vector<FASTAFile::FASTAEntry>()); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~FASTAContainer()) { delete ptr; } END_SECTION std::vector<FASTAFile::FASTAEntry> fev = { {"id0", "desc0", "AAAA"},{ "id1", "desc1", "BBBB" },{ "id2", "desc2", "CCCC" },{ "id3", "desc3", "DDDD" } }; START_SECTION(FASTAContainer(const String& FASTA_file)) FCFile f(OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta")); TEST_EQUAL(f.size(), 0) END_SECTION START_SECTION(FASTAContainer(std::vector<FASTAFile::FASTAEntry>& data)) FCVec fv(fev); TEST_EQUAL(fv.size(), 4) END_SECTION START_SECTION(size_t getChunkOffset() const) // FCFile: tested below FCVec fv(fev); TEST_EQUAL(fv.getChunkOffset(), 0) END_SECTION START_SECTION(bool activateCache()) // FCFile: tested below FCVec fv(fev); TEST_EQUAL(fv.activateCache(), 1) TEST_EQUAL(fv.activateCache(), 0) END_SECTION START_SECTION(void reset()) // FCFile: tested below FCVec fv(fev); TEST_EQUAL(fv.activateCache(), 1) TEST_EQUAL(fv.activateCache(), 0) fv.reset(); TEST_EQUAL(fv.activateCache(), 1) END_SECTION START_SECTION(bool cacheChunk(int suggested_size)) // FCFile: tested below FCVec fv(fev); TEST_EQUAL(fv.cacheChunk(333), 1) TEST_EQUAL(fv.cacheChunk(333), 0) END_SECTION START_SECTION(size_t chunkSize() const) // FCFile: tested below FCVec fv(fev); TEST_EQUAL(fv.chunkSize(), 4) END_SECTION START_SECTION(const FASTAFile::FASTAEntry& chunkAt(size_t pos) const) // FCFile: tested below FCVec fv(fev); FASTAFile::FASTAEntry pe = fv.chunkAt(3); TEST_EQUAL(pe.identifier, "id3"); END_SECTION START_SECTION(bool readAt(FASTAFile::FASTAEntry& protein, size_t pos)) // FCFile: tested below FCVec fv(fev); FASTAFile::FASTAEntry pe; TEST_EQUAL(fv.readAt(pe, 3), true); TEST_EQUAL(pe.identifier, "id3"); END_SECTION START_SECTION(bool empty() const) FCFile f(OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta")); TEST_EQUAL(f.empty(), false) FCFile f2(OPENMS_GET_TEST_DATA_PATH("degenerate_cases/empty.fasta")); TEST_EQUAL(f2.empty(), true) FCVec fv(fev); TEST_EQUAL(fv.empty(), false); std::vector<FASTAFile::FASTAEntry> feve; FCVec fv2(feve); TEST_EQUAL(fv2.empty(), true); END_SECTION START_SECTION(size_t size() const) FCFile f(OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta")); TEST_EQUAL(f.cacheChunk(2), true) TEST_EQUAL(f.size(), 2) TEST_EQUAL(f.activateCache(), true) TEST_EQUAL(f.size(), 2) FASTAFile::FASTAEntry pe, pe2; TEST_EQUAL(f.readAt(pe, 0), true); pe2 = f.chunkAt(0); TEST_TRUE(pe == pe2) TEST_EQUAL(pe.description, "This is the description of the first protein") pe2 = f.chunkAt(1); TEST_EQUAL(pe == pe2, false) TEST_EQUAL(pe2.description, "This is the description of the second protein") // read next chunk, and re-read from disk again, using byte offsets TEST_EQUAL(f.cacheChunk(1), true) TEST_EQUAL(f.activateCache(), true) TEST_EQUAL(f.readAt(pe, 0), true); // third global entry TEST_EQUAL(pe.identifier, "P68509|1433F_BOVIN") TEST_EQUAL(pe.description, "This is the description of the first protein") // read until end TEST_EQUAL(f.cacheChunk(3), true) // only 2 can be read, but thats ok TEST_EQUAL(f.activateCache(), true) TEST_EQUAL(f.chunkSize(), 2) pe = f.chunkAt(1); TEST_EQUAL(pe.description, " ##0") TEST_EQUAL(f.readAt(pe2, 4), true); TEST_TRUE(pe == pe2) // reached the end after 5 entries TEST_EQUAL(f.cacheChunk(3), false) TEST_EQUAL(f.chunkSize(), 2) TEST_EQUAL(f.activateCache(), false) TEST_EQUAL(f.chunkSize(), 0) TEST_EQUAL(f.cacheChunk(3), false) TEST_EQUAL(f.activateCache(), false) // read from disk again after reaching EOF, using byte offsets TEST_EQUAL(f.readAt(pe, 0), true); TEST_EQUAL(pe.identifier, "P68509|1433F_BOVIN") TEST_EQUAL(pe.description, "This is the description of the first protein") TEST_EQUAL(f.readAt(pe, 4), true); TEST_EQUAL(pe.identifier, "test") TEST_EQUAL(pe.description, " ##0") FCVec fv(fev); TEST_EQUAL(fv.size(), 4); // read, then reset and start reading again f.reset(); TEST_EQUAL(f.cacheChunk(2), true) TEST_EQUAL(f.size(), 2) TEST_EQUAL(f.activateCache(), true) TEST_EQUAL(f.size(), 2) FASTAFile::FASTAEntry pe3, pe4; TEST_EQUAL(f.readAt(pe3, 0), true); pe4 = f.chunkAt(0); TEST_TRUE(pe3 == pe4) TEST_EQUAL(pe3.description, "This is the description of the first protein") pe4 = f.chunkAt(1); TEST_EQUAL(pe3 == pe4, false) TEST_EQUAL(pe4.description, "This is the description of the second protein") f.reset(); TEST_EQUAL(f.cacheChunk(2), true) TEST_EQUAL(f.size(), 2) TEST_EQUAL(f.activateCache(), true) TEST_EQUAL(f.size(), 2) FASTAFile::FASTAEntry pe5, pe6; TEST_EQUAL(f.readAt(pe5, 0), true); pe6 = f.chunkAt(0); TEST_TRUE(pe5 == pe6) TEST_EQUAL(pe5.description, "This is the description of the first protein") pe6 = f.chunkAt(1); TEST_EQUAL(pe5 == pe6, false) TEST_EQUAL(pe6.description, "This is the description of the second protein") END_SECTION START_SECTION(Result findDecoyString(FASTAContainer<T>& proteins)) // test without decoys in input FASTAContainer<TFI_File> f1{OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta")}; DecoyHelper::Result r1 = {false, "?", true}; TEST_EQUAL(DecoyHelper::findDecoyString(f1) == r1,true) // test with decoys in input FASTAContainer<TFI_File> f2{OPENMS_GET_TEST_DATA_PATH("FASTAContainer_test.fasta")}; DecoyHelper::Result r2 = {true, "DECOY_", true}; TEST_EQUAL(DecoyHelper::findDecoyString(f2) == r2, true); END_SECTION START_SECTION(Result countDecoys(FASTAContainer<T>& proteins)) // test without decoys in input FCFile f1{OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta")}; std::unordered_map<std::string, std::pair<Size, Size>> decoy_count; std::unordered_map<std::string, std::string> decoy_case_sensitive; DecoyHelper::DecoyStatistics ds1 = {decoy_count, decoy_case_sensitive,0,0,5}; TEST_EQUAL(DecoyHelper::countDecoys(f1) == ds1, true) // test with decoys in input FCFile f2{OPENMS_GET_TEST_DATA_PATH("FASTAContainer_test.fasta")}; decoy_case_sensitive["decoy_"] = "DECOY_"; decoy_count["decoy_"] = std::make_pair(3,0); DecoyHelper::DecoyStatistics ds2 = { decoy_count, decoy_case_sensitive, 3, 0, 6}; TEST_EQUAL(DecoyHelper::countDecoys(f2) == ds2, true) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FeatureFinderMultiplexAlgorithm_test.cpp
.cpp
2,213
80
// 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/FORMAT/MzMLFile.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/ConsensusMap.h> #include <OpenMS/FORMAT/ParamXMLFile.h> #include <OpenMS/FEATUREFINDER/FeatureFinderMultiplexAlgorithm.h> using namespace OpenMS; using namespace std; START_TEST(FeatureFinderMultiplexAlgorithm, "$Id$") FeatureFinderMultiplexAlgorithm* ptr = 0; FeatureFinderMultiplexAlgorithm* null_ptr = 0; START_SECTION(FeatureFinderMultiplexAlgorithm()) { ptr = new FeatureFinderMultiplexAlgorithm(); TEST_NOT_EQUAL(ptr, null_ptr); } END_SECTION START_SECTION(~FeatureFinderMultiplexAlgorithm()) { delete ptr; } END_SECTION START_SECTION((virtual void run())) { MzMLFile mzml_file; MSExperiment exp; ConsensusMap result; mzml_file.getOptions().addMSLevel(1); mzml_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureFinderMultiplex_1_input.mzML"), exp); exp.updateRanges(); Param param; ParamXMLFile paramFile; paramFile.load(OPENMS_GET_TEST_DATA_PATH("FeatureFinderMultiplex_1_parameters.ini"), param); param = param.copy("FeatureFinderMultiplex:1:",true); param.remove("in"); param.remove("out"); param.remove("out_multiplets"); param.remove("log"); param.remove("debug"); param.remove("threads"); param.remove("no_progress"); param.remove("force"); param.remove("test"); FeatureFinderMultiplexAlgorithm algorithm; algorithm.setParameters(param); algorithm.run(exp, true); result = algorithm.getConsensusMap(); TEST_EQUAL(result.size(), 2); double L = result[0].getFeatures().begin()->getIntensity(); double H = (++(result[0].getFeatures().begin()))->getIntensity(); // Check that the HEAVY:LIGHT ratio is close to the expected 3:1 ratio TOLERANCE_ABSOLUTE(0.2); TEST_REAL_SIMILAR(H/L, 3.0); } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ClusterProxyKD_test.cpp
.cpp
3,778
119
// 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/MAPMATCHING/FeatureGroupingAlgorithmKD.h> using namespace OpenMS; using namespace std; START_TEST(ClusterProxyKD, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ClusterProxyKD* ptr = nullptr; ClusterProxyKD* nullPointer = nullptr; START_SECTION((ClusterProxyKD())) ptr = new ClusterProxyKD(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~ClusterProxyKD())) delete ptr; END_SECTION START_SECTION((ClusterProxyKD(Size size, double avg_distance, Size center_index))) ptr = new ClusterProxyKD(1, 0.2, 3); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION ClusterProxyKD proxy_0; ClusterProxyKD proxy_1(10, 0.01, 4); ClusterProxyKD proxy_2(9, 0.001, 3); ClusterProxyKD proxy_3(9, 0.01, 2); ClusterProxyKD proxy_4(9, 0.01, 1); ClusterProxyKD proxy_5 = proxy_1; START_SECTION((ClusterProxyKD(const ClusterProxyKD& rhs))) ptr = new ClusterProxyKD(proxy_1); TEST_NOT_EQUAL(ptr, nullPointer); TEST_EQUAL(ptr->getSize(), proxy_1.getSize()); TEST_REAL_SIMILAR(ptr->getAvgDistance(), proxy_1.getAvgDistance()); TEST_EQUAL(ptr->getCenterIndex(), proxy_1.getCenterIndex()); delete ptr; END_SECTION START_SECTION((ClusterProxyKD& operator=(const ClusterProxyKD& rhs))) ClusterProxyKD proxy_5 = proxy_1; TEST_EQUAL(proxy_5.getSize(), proxy_1.getSize()); TEST_REAL_SIMILAR(proxy_5.getAvgDistance(), proxy_1.getAvgDistance()); TEST_EQUAL(proxy_5.getCenterIndex(), proxy_1.getCenterIndex()); END_SECTION START_SECTION((bool operator<(const ClusterProxyKD& rhs) const)) TEST_EQUAL(proxy_1 < proxy_2, true) TEST_EQUAL(proxy_1 < proxy_3, true) TEST_EQUAL(proxy_1 < proxy_4, true) TEST_EQUAL(proxy_2 < proxy_3, true) TEST_EQUAL(proxy_2 < proxy_4, true) TEST_EQUAL(proxy_3 < proxy_4, true) TEST_EQUAL(proxy_2 < proxy_1, false) TEST_EQUAL(proxy_3 < proxy_1, false) TEST_EQUAL(proxy_4 < proxy_1, false) TEST_EQUAL(proxy_3 < proxy_2, false) TEST_EQUAL(proxy_4 < proxy_2, false) TEST_EQUAL(proxy_4 < proxy_3, false) TEST_EQUAL(proxy_1 < proxy_1, false) END_SECTION START_SECTION((bool operator!=(const ClusterProxyKD& rhs) const)) TEST_EQUAL(proxy_0 != proxy_0, false) TEST_EQUAL(proxy_1 != proxy_1, false) TEST_EQUAL(proxy_1 != proxy_5, false) TEST_FALSE(proxy_0 == proxy_1) TEST_FALSE(proxy_1 == proxy_2) END_SECTION START_SECTION((bool operator==(const ClusterProxyKD& rhs) const)) TEST_TRUE(proxy_0 == proxy_0) TEST_TRUE(proxy_1 == proxy_1) TEST_TRUE(proxy_1 == proxy_5) TEST_EQUAL(proxy_0 == proxy_1, false) TEST_EQUAL(proxy_1 == proxy_2, false) END_SECTION START_SECTION((Size getSize() const)) TEST_EQUAL(proxy_0.getSize(), 0) TEST_EQUAL(proxy_1.getSize(), 10) END_SECTION START_SECTION((bool isValid() const)) TEST_EQUAL(proxy_0.isValid(), false) TEST_EQUAL(proxy_1.isValid(), true) END_SECTION START_SECTION((double getAvgDistance() const)) TEST_REAL_SIMILAR(proxy_0.getAvgDistance(), 0.0) TEST_REAL_SIMILAR(proxy_1.getAvgDistance(), 0.01) END_SECTION START_SECTION((Size getCenterIndex() const)) TEST_EQUAL(proxy_0.getCenterIndex(), 0) TEST_EQUAL(proxy_1.getCenterIndex(), 4) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IsobaricQuantifierStatistics_test.cpp
.cpp
4,706
141
// 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/IsobaricQuantifierStatistics.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(IsobaricQuantifierStatistics, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// IsobaricQuantifierStatistics* ptr = nullptr; IsobaricQuantifierStatistics* null_ptr = nullptr; START_SECTION(IsobaricQuantifierStatistics()) { ptr = new IsobaricQuantifierStatistics(); TEST_NOT_EQUAL(ptr, null_ptr) TEST_EQUAL(ptr->channel_count, 0) TEST_EQUAL(ptr->iso_number_ms2_negative, 0) TEST_EQUAL(ptr->iso_number_reporter_negative, 0) TEST_EQUAL(ptr->iso_number_reporter_different, 0) TEST_EQUAL(ptr->iso_solution_different_intensity, 0.0) TEST_EQUAL(ptr->iso_total_intensity_negative, 0.0) TEST_EQUAL(ptr->number_ms2_total, 0) TEST_EQUAL(ptr->number_ms2_empty, 0) TEST_EQUAL(ptr->empty_channels.empty(), true) } END_SECTION START_SECTION(~IsobaricQuantifierStatistics()) { delete ptr; } END_SECTION START_SECTION((void reset())) { IsobaricQuantifierStatistics stats; stats.channel_count = 4; stats.iso_number_ms2_negative = 10; stats.iso_number_reporter_negative = 20; stats.iso_number_reporter_different = 10; stats.iso_solution_different_intensity = 131.3; stats.iso_total_intensity_negative = 134.3; stats.number_ms2_total = 200; stats.number_ms2_empty = 3; stats.empty_channels[114] = 4; stats.reset(); // check if reset worked properly TEST_EQUAL(stats.channel_count, 0) TEST_EQUAL(stats.iso_number_ms2_negative, 0) TEST_EQUAL(stats.iso_number_reporter_negative, 0) TEST_EQUAL(stats.iso_number_reporter_different, 0) TEST_EQUAL(stats.iso_solution_different_intensity, 0.0) TEST_EQUAL(stats.iso_total_intensity_negative, 0.0) TEST_EQUAL(stats.number_ms2_total, 0) TEST_EQUAL(stats.number_ms2_empty, 0) TEST_EQUAL(stats.empty_channels.empty(), true) } END_SECTION START_SECTION((IsobaricQuantifierStatistics(const IsobaricQuantifierStatistics &other))) { IsobaricQuantifierStatistics stats; stats.channel_count = 4; stats.iso_number_ms2_negative = 10; stats.iso_number_reporter_negative = 20; stats.iso_number_reporter_different = 10; stats.iso_solution_different_intensity = 131.3; stats.iso_total_intensity_negative = 134.3; stats.number_ms2_total = 200; stats.number_ms2_empty = 3; stats.empty_channels[114] = 4; IsobaricQuantifierStatistics stats2(stats); TEST_EQUAL(stats2.channel_count, 4) TEST_EQUAL(stats2.iso_number_ms2_negative, 10) TEST_EQUAL(stats2.iso_number_reporter_negative, 20) TEST_EQUAL(stats2.iso_number_reporter_different, 10) TEST_EQUAL(stats2.iso_solution_different_intensity, 131.3) TEST_EQUAL(stats2.iso_total_intensity_negative, 134.3) TEST_EQUAL(stats2.number_ms2_total, 200) TEST_EQUAL(stats2.number_ms2_empty, 3) TEST_EQUAL(stats2.empty_channels.find(114) != stats2.empty_channels.end(), true) TEST_EQUAL(stats2.empty_channels[114], 4) } END_SECTION START_SECTION((IsobaricQuantifierStatistics& operator=(const IsobaricQuantifierStatistics &rhs))) { IsobaricQuantifierStatistics stats; stats.channel_count = 4; stats.iso_number_ms2_negative = 10; stats.iso_number_reporter_negative = 20; stats.iso_number_reporter_different = 10; stats.iso_solution_different_intensity = 131.3; stats.iso_total_intensity_negative = 134.3; stats.number_ms2_total = 200; stats.number_ms2_empty = 3; stats.empty_channels[114] = 4; IsobaricQuantifierStatistics stats2; stats2 = stats; TEST_EQUAL(stats2.channel_count, 4) TEST_EQUAL(stats2.iso_number_ms2_negative, 10) TEST_EQUAL(stats2.iso_number_reporter_negative, 20) TEST_EQUAL(stats2.iso_number_reporter_different, 10) TEST_EQUAL(stats2.iso_solution_different_intensity, 131.3) TEST_EQUAL(stats2.iso_total_intensity_negative, 134.3) TEST_EQUAL(stats2.number_ms2_total, 200) TEST_EQUAL(stats2.number_ms2_empty, 3) TEST_EQUAL(stats2.empty_channels.find(114) != stats2.empty_channels.end(), true) TEST_EQUAL(stats2.empty_channels[114], 4) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IBSpectraFile_test.cpp
.cpp
2,641
85
// 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/IBSpectraFile.h> #include <OpenMS/KERNEL/ConsensusMap.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> using namespace OpenMS; using namespace std; START_TEST(IBSpectraFile, "$Id$") IBSpectraFile* ptr = nullptr; IBSpectraFile* nullPointer = nullptr; START_SECTION((IBSpectraFile())) { ptr = new IBSpectraFile(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((IBSpectraFile(const IBSpectraFile& other))) { IBSpectraFile ibfile(*ptr); TEST_NOT_EQUAL(&ibfile, nullPointer) } END_SECTION START_SECTION((IBSpectraFile& operator=(const IBSpectraFile& rhs))) { IBSpectraFile ibfile; ibfile = *ptr; TEST_NOT_EQUAL(&ibfile, nullPointer) } END_SECTION START_SECTION((void store(const String& filename, const ConsensusMap& cm))) { // test invalid ConsensusMap ConsensusMap cm_no_ms2quant; cm_no_ms2quant.setExperimentType("labeled_MS1"); IBSpectraFile ibfile_no_ms2quant; TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidParameter, ibfile_no_ms2quant.store("not-a-file-name", cm_no_ms2quant), "Given ConsensusMap does not hold any isobaric quantification data.") // test wrong channel count ConsensusMap cm_wrong_channel_count; cm_wrong_channel_count.setExperimentType("labeled_MS2"); ConsensusMap::ColumnHeader channel1; ConsensusMap::ColumnHeader channel2; ConsensusMap::ColumnHeader channel3; cm_wrong_channel_count.getColumnHeaders()[0] = channel1; cm_wrong_channel_count.getColumnHeaders()[1] = channel2; cm_wrong_channel_count.getColumnHeaders()[2] = channel3; IBSpectraFile ibfile_wrong_channel_count; TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidParameter, ibfile_wrong_channel_count.store("not-a-file-name", cm_wrong_channel_count), "Could not guess isobaric quantification data from ConsensusMap due to non-matching number of input maps.") // test a real example ConsensusMap cm; ConsensusXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IBSpectraFile.consensusXML"),cm); std::string tmp_filename; NEW_TMP_FILE(tmp_filename); IBSpectraFile ibfile; ibfile.store(tmp_filename, cm); TEST_FILE_SIMILAR(tmp_filename.c_str(), OPENMS_GET_TEST_DATA_PATH("IBSpectraFile.ibspectra.csv")) } END_SECTION delete ptr; END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/RANSAC_test.cpp
.cpp
1,535
42
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: George Rosenberger $ // $Authors: George Rosenberger, Hannes Roest, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ML/RANSAC/RANSAC.h> /////////////////////////// using namespace std; using namespace OpenMS; /////////////////////////// START_TEST(RANSAC, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION((static std::vector<std::pair<double, double> > ransac(const std::vector<std::pair<double, double> >& pairs, size_t n, size_t k, double t, size_t d, int (*rng)(int) = NULL))) { NOT_TESTABLE // tested in the models, e.g. RANSACModelLinear } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/UniqueIdInterface_test.cpp
.cpp
8,093
300
// 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/CONCEPT/UniqueIdInterface.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(UniqueIdInterface, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// UniqueIdInterface* ptr = nullptr; UniqueIdInterface* nullPointer = nullptr; START_SECTION(UniqueIdInterface()) { ptr = new UniqueIdInterface(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~UniqueIdInterface()) { delete ptr; } END_SECTION START_SECTION((UniqueIdInterface(const UniqueIdInterface &rhs))) { UniqueIdInterface uii1; UniqueIdInterface uii2(uii1); // to be continued further below NOT_TESTABLE } END_SECTION START_SECTION((UniqueIdInterface(UniqueIdInterface &&rhs))) { // Ensure that UniqueIdInterface has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(UniqueIdInterface(std::declval<UniqueIdInterface&&>())), true) } END_SECTION START_SECTION((UniqueIdInterface& operator=(UniqueIdInterface const &rhs))) { UniqueIdInterface uii1; UniqueIdInterface uii2; uii2 = uii1; // to be continued further below NOT_TESTABLE } END_SECTION START_SECTION([EXTRA](~UniqueIdInterface())) { { UniqueIdInterface uii1; UniqueIdInterface uii2; uii2.setUniqueId(17); // destructor called when the scope is left } // to be continued further below ;-) NOT_TESTABLE } END_SECTION START_SECTION((bool operator==(UniqueIdInterface const &rhs) const )) { UniqueIdInterface uii1; UniqueIdInterface uii2; TEST_EQUAL(uii1 == uii2,true); UniqueIdInterface uii3(uii1); TEST_EQUAL(uii1 == uii3,true); uii2.setUniqueId(17); TEST_EQUAL(uii1 == uii2,false); uii1.setUniqueId(17); TEST_EQUAL(uii1 == uii2,true); } END_SECTION START_SECTION((UInt64 getUniqueId() const )) { UniqueIdInterface uii1; TEST_EQUAL(uii1.getUniqueId(),0); UniqueIdInterface uii2; uii2 = uii1; TEST_EQUAL(uii2.getUniqueId(),0); UniqueIdInterface uii3(uii1); TEST_EQUAL(uii3.getUniqueId(),0); uii1.setUniqueId(17); TEST_EQUAL(uii1.getUniqueId(),17); uii2 = uii1; TEST_EQUAL(uii2.getUniqueId(),17); UniqueIdInterface uii4(uii1); TEST_EQUAL(uii4.getUniqueId(),17); } END_SECTION START_SECTION((Size clearUniqueId())) { UniqueIdInterface uii1; uii1.clearUniqueId(); TEST_EQUAL(uii1.getUniqueId(),0) uii1.setUniqueId(17); TEST_EQUAL(uii1.getUniqueId(),17); uii1.clearUniqueId(); TEST_EQUAL(uii1.getUniqueId(),0) } END_SECTION START_SECTION((void swap(UniqueIdInterface &from))) { UniqueIdInterface u1; u1.setUniqueId(111); UniqueIdInterface u2; u2.setUniqueId(222); u1.swap(u2); TEST_EQUAL(u1.getUniqueId(),222); TEST_EQUAL(u2.getUniqueId(),111); std::swap(u1,u2); TEST_EQUAL(u1.getUniqueId(),111); TEST_EQUAL(u2.getUniqueId(),222); } END_SECTION START_SECTION((static bool isValid(UInt64 unique_id))) { TEST_EQUAL(UniqueIdInterface::isValid(UniqueIdInterface::INVALID),false); TEST_EQUAL(UniqueIdInterface::isValid(1234567890),true); } END_SECTION START_SECTION((Size hasValidUniqueId() const )) { UniqueIdInterface uii1; TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.clearUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(17); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(0); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(17); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.clearUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),false); } END_SECTION START_SECTION((Size hasInvalidUniqueId() const )) { UniqueIdInterface uii1; TEST_EQUAL(uii1.hasInvalidUniqueId(),true); uii1.clearUniqueId(); TEST_EQUAL(uii1.hasInvalidUniqueId(),true); uii1.setUniqueId(17); TEST_EQUAL(uii1.hasInvalidUniqueId(),false); uii1.setUniqueId(0); TEST_EQUAL(uii1.hasInvalidUniqueId(),true); uii1.setUniqueId(17); TEST_EQUAL(uii1.hasInvalidUniqueId(),false); uii1.clearUniqueId(); TEST_EQUAL(uii1.hasInvalidUniqueId(),true); } END_SECTION START_SECTION((Size setUniqueId())) { UniqueIdInterface uii1; TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); } END_SECTION START_SECTION((Size ensureUniqueId())) { UInt64 the_unique_id; UniqueIdInterface uii1; the_unique_id = uii1.getUniqueId(); TEST_EQUAL(the_unique_id,0); uii1.ensureUniqueId(); the_unique_id = uii1.getUniqueId(); TEST_NOT_EQUAL(the_unique_id,0); uii1.ensureUniqueId(); TEST_EQUAL(uii1.getUniqueId(),the_unique_id); } END_SECTION START_SECTION((void setUniqueId(UInt64 rhs))) { // that one was used throughout the other tests NOT_TESTABLE; } END_SECTION START_SECTION((void setUniqueId(const String &rhs))) { UniqueIdInterface uii1; TEST_EQUAL(uii1.getUniqueId(),0); uii1.setUniqueId(""); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId("_"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId("17"); TEST_EQUAL(uii1.getUniqueId(),17); uii1.setUniqueId("18"); TEST_EQUAL(uii1.getUniqueId(),18); uii1.setUniqueId("asdf_19"); TEST_EQUAL(uii1.getUniqueId(),19); uii1.setUniqueId("_20"); TEST_EQUAL(uii1.getUniqueId(),20); uii1.setUniqueId("_021"); TEST_EQUAL(uii1.getUniqueId(),21); uii1.setUniqueId("asdf_19_22"); TEST_EQUAL(uii1.getUniqueId(),22); uii1.setUniqueId("_20_23"); TEST_EQUAL(uii1.getUniqueId(),23); uii1.setUniqueId("_021_024"); TEST_EQUAL(uii1.getUniqueId(),24); uii1.setUniqueId(" _021_025 "); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId("bla"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123_ 456"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 _456"); TEST_EQUAL(uii1.getUniqueId(),456); uii1.setUniqueId(1000000); uii1.setUniqueId("123 _ 456"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456_"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456_ "); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456 _ "); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456 _"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456 ff"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("_021bla_"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("_021 bla "); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("_021 bla"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("_021_bla"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("_021_bla_"); TEST_EQUAL(uii1.hasValidUniqueId(),false); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp
.cpp
10,314
226
// 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/FORMAT/ConsensusXMLFile.h> /////////////////////////// #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/KERNEL/ConsensusMap.h> #include <OpenMS/FORMAT/FileHandler.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/DATASTRUCTURES/ListUtils.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(ConsensusXMLFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ConsensusXMLFile * ptr = nullptr; ConsensusXMLFile* nullPointer = nullptr; START_SECTION((ConsensusXMLFile())) ptr = new ConsensusXMLFile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~ConsensusXMLFile())) delete ptr; END_SECTION TOLERANCE_ABSOLUTE(0.01) START_SECTION(const PeakFileOptions& getOptions() const) ConsensusXMLFile file; TEST_EQUAL(file.getOptions().hasMSLevels(), false) END_SECTION START_SECTION(PeakFileOptions& getOptions()) ConsensusXMLFile file; file.getOptions().addMSLevel(1); TEST_EQUAL(file.getOptions().hasMSLevels(), true); END_SECTION START_SECTION((void load(const String &filename, ConsensusMap & map))) ConsensusMap map; ConsensusXMLFile file; file.load(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_1.consensusXML"), map); //test DocumentIdentifier addition TEST_STRING_EQUAL(map.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_1.consensusXML")); TEST_STRING_EQUAL(FileTypes::typeToName(map.getLoadedFileType()), "consensusXML"); //meta data TEST_EQUAL(map.getIdentifier(), "lsid") TEST_EQUAL(map.getExperimentType() == "label-free", true) TEST_EQUAL(map.getMetaValue("name1") == DataValue("value1"), true) TEST_EQUAL(map.getMetaValue("name2") == DataValue(2), true) //file descriptions TEST_EQUAL(map.getColumnHeaders()[0].filename == "data/MapAlignmentFeatureMap1.xml", true) TEST_EQUAL(map.getColumnHeaders()[0].label, "label") TEST_EQUAL(map.getColumnHeaders()[0].size, 144) TEST_EQUAL(map.getColumnHeaders()[0].getMetaValue("name3") == DataValue("value3"), true) TEST_EQUAL(map.getColumnHeaders()[0].getMetaValue("name4") == DataValue(4), true) TEST_STRING_EQUAL(map.getColumnHeaders()[1].filename, "data/MapAlignmentFeatureMap2.xml") TEST_EQUAL(map.getColumnHeaders()[1].label, "") TEST_EQUAL(map.getColumnHeaders()[1].size, 0) TEST_EQUAL(map.getColumnHeaders()[1].getMetaValue("name5") == DataValue("value5"), true) TEST_EQUAL(map.getColumnHeaders()[1].getMetaValue("name6") == DataValue(6.0), true) //data processing TEST_EQUAL(map.getDataProcessing().size(), 2) TEST_STRING_EQUAL(map.getDataProcessing()[0].getSoftware().getName(), "Software1") TEST_STRING_EQUAL(map.getDataProcessing()[0].getSoftware().getVersion(), "0.91a") TEST_EQUAL(map.getDataProcessing()[0].getProcessingActions().size(), 1) TEST_EQUAL(map.getDataProcessing()[0].getProcessingActions().count(DataProcessing::DEISOTOPING), 1) TEST_STRING_EQUAL(map.getDataProcessing()[0].getMetaValue("name"), "dataProcessing") TEST_STRING_EQUAL(map.getDataProcessing()[1].getSoftware().getName(), "Software2") TEST_STRING_EQUAL(map.getDataProcessing()[1].getSoftware().getVersion(), "0.92a") TEST_EQUAL(map.getDataProcessing()[1].getProcessingActions().size(), 2) TEST_EQUAL(map.getDataProcessing()[1].getProcessingActions().count(DataProcessing::SMOOTHING), 1) TEST_EQUAL(map.getDataProcessing()[1].getProcessingActions().count(DataProcessing::BASELINE_REDUCTION), 1) //protein identifications TEST_EQUAL(map.getProteinIdentifications().size(), 2) TEST_EQUAL(map.getProteinIdentifications()[0].getHits().size(), 2) TEST_EQUAL(map.getProteinIdentifications()[0].getHits()[0].getSequence(), "ABCDEFG") TEST_EQUAL(map.getProteinIdentifications()[0].getHits()[1].getSequence(), "HIJKLMN") TEST_EQUAL(map.getProteinIdentifications()[1].getHits().size(), 1) TEST_EQUAL(map.getProteinIdentifications()[1].getHits()[0].getSequence(), "OPQREST") //peptide identifications TEST_EQUAL(map[0].getPeptideIdentifications().size(), 2) TEST_EQUAL(map[0].getPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(map[0].getPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("A")) TEST_EQUAL(map[0].getPeptideIdentifications()[1].getHits().size(), 2) TEST_EQUAL(map[0].getPeptideIdentifications()[1].getHits()[0].getSequence(), AASequence::fromString("C")) TEST_EQUAL(map[0].getPeptideIdentifications()[1].getHits()[1].getSequence(), AASequence::fromString("D")) TEST_EQUAL(map[1].getPeptideIdentifications().size(), 1) TEST_EQUAL(map[1].getPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(map[1].getPeptideIdentifications()[0].getHits()[0].getSequence(),AASequence::fromString( "E")) //unassigned peptide identifications TEST_EQUAL(map.getUnassignedPeptideIdentifications().size(), 2) TEST_EQUAL(map.getUnassignedPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(map.getUnassignedPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("F")) TEST_EQUAL(map.getUnassignedPeptideIdentifications()[1].getHits().size(), 2) TEST_EQUAL(map.getUnassignedPeptideIdentifications()[1].getHits()[0].getSequence(), AASequence::fromString("G")) TEST_EQUAL(map.getUnassignedPeptideIdentifications()[1].getHits()[1].getSequence(), AASequence::fromString("H")) //features TEST_EQUAL(map.size(), 6) ConsensusFeature cons_feature = map[0]; TEST_REAL_SIMILAR(cons_feature.getRT(), 1273.27) TEST_REAL_SIMILAR(cons_feature.getMZ(), 904.47) TEST_REAL_SIMILAR(cons_feature.getIntensity(), 3.12539e+07) TEST_REAL_SIMILAR(cons_feature.getPositionRange().minPosition()[0], 1273.27) TEST_REAL_SIMILAR(cons_feature.getPositionRange().maxPosition()[0], 1273.27) TEST_REAL_SIMILAR(cons_feature.getPositionRange().minPosition()[1], 904.47) TEST_REAL_SIMILAR(cons_feature.getPositionRange().maxPosition()[1], 904.47) TEST_REAL_SIMILAR(cons_feature.getIntensityRange().minPosition()[0], 3.12539e+07) TEST_REAL_SIMILAR(cons_feature.getIntensityRange().maxPosition()[0], 3.12539e+07) TEST_REAL_SIMILAR(cons_feature.getQuality(), 1.1) TEST_EQUAL(cons_feature.getMetaValue("peptide_id") == DataValue("RefSeq:NC_1234"), true) ConsensusFeature::HandleSetType::const_iterator it = cons_feature.begin(); TEST_REAL_SIMILAR(it->getIntensity(), 3.12539e+07) cons_feature = map[5]; TEST_REAL_SIMILAR(cons_feature.getRT(), 1194.82) TEST_REAL_SIMILAR(cons_feature.getMZ(), 777.101) TEST_REAL_SIMILAR(cons_feature.getIntensity(), 1.78215e+07) TEST_REAL_SIMILAR(cons_feature.getPositionRange().minPosition()[0], 1194.82) TEST_REAL_SIMILAR(cons_feature.getPositionRange().maxPosition()[0], 1194.82) TEST_REAL_SIMILAR(cons_feature.getPositionRange().minPosition()[1], 777.101) TEST_REAL_SIMILAR(cons_feature.getPositionRange().maxPosition()[1], 777.101) TEST_REAL_SIMILAR(cons_feature.getIntensityRange().minPosition()[0], 1.78215e+07) TEST_REAL_SIMILAR(cons_feature.getIntensityRange().maxPosition()[0], 1.78215e+07) TEST_REAL_SIMILAR(cons_feature.getQuality(), 0.0) it = cons_feature.begin(); TEST_REAL_SIMILAR(it->getIntensity(), 1.78215e+07) ++ it; TEST_REAL_SIMILAR(it->getIntensity(), 1.78215e+07) // test meta values: TEST_EQUAL(map[0].getMetaValue("myIntList") == ListUtils::create<Int>("1,10,12"), true); TEST_EQUAL(map[0].getMetaValue("myDoubleList") == ListUtils::create<double>("1.111,10.999,12.45"), true); std::cout << "list: " << map[0].getMetaValue("myStringList") << "\n"; TEST_EQUAL(map[0].getMetaValue("myStringList") == ListUtils::create<String>("myABC1,Stuff,12"), true); TEST_EQUAL(map[4].getMetaValue("myDoubleList") == ListUtils::create<double>("6.442"), true); //PeakFileOptions tests file.getOptions().setRTRange(makeRange(815, 818)); file.load(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_2_options.consensusXML"), map); TEST_EQUAL(map.size(), 1) TEST_REAL_SIMILAR(map[0].getRT(), 817.266) file.getOptions() = PeakFileOptions(); file.getOptions().setMZRange(makeRange(944, 945)); file.load(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_2_options.consensusXML"), map); TEST_EQUAL(map.size(), 1) TEST_REAL_SIMILAR(map[0].getMZ(), 944.96) file.getOptions() = PeakFileOptions(); file.getOptions().setIntensityRange(makeRange(15000, 24000)); file.load(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_2_options.consensusXML"), map); TEST_EQUAL(map.size(), 1) TEST_REAL_SIMILAR(map[0].getIntensity(), 23000.238) END_SECTION START_SECTION((void store(const String &filename, const ConsensusMap &consensus_map))) std::string tmp_filename; NEW_TMP_FILE(tmp_filename); ConsensusMap map; ConsensusXMLFile f; f.load(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_1.consensusXML"), map); // make protIDs non-unique map.getProteinIdentifications().push_back(map.getProteinIdentifications()[0]); TEST_EXCEPTION(Exception::ParseError, f.store(tmp_filename, map)) map.getProteinIdentifications().pop_back(); // undo f.store(tmp_filename, map); WHITELIST("?xml-stylesheet") TEST_FILE_SIMILAR(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_1.consensusXML"), tmp_filename) END_SECTION START_SECTION([EXTRA](bool isValid(const String &filename))) ConsensusXMLFile f; TEST_EQUAL(f.isValid(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_1.consensusXML"), std::cerr), true); TEST_EQUAL(f.isValid(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_2_options.consensusXML"), std::cerr), true); //test if written empty file // - this is invalid, so it is not tested :) //test if written full file is valid ConsensusMap m; String tmp_filename; NEW_TMP_FILE(tmp_filename); f.load(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_1.consensusXML"), m); f.store(tmp_filename, m); TEST_EQUAL(f.isValid(tmp_filename, std::cerr), true); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IsotopeDistribution_test.cpp
.cpp
9,484
266
// 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 $ // -------------------------------------------------------------------------- // /////////////////////////// #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h> /////////////////////////// // More headers #include <iostream> #include <iterator> #include <utility> #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h> #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> ///////////////////////////////////////////////////////////// START_TEST(IsotopeDistribution, "$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()) IsotopeDistribution* ptr = nullptr; ptr = new IsotopeDistribution(); Size container_size = ptr->size(); TEST_EQUAL(container_size, 1) TEST_NOT_EQUAL(ptr, nullPointer) delete ptr; // Ensure that IsotopeDistribution has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(IsotopeDistribution(std::declval<IsotopeDistribution&&>())), true) END_SECTION IsotopeDistribution* iso = new IsotopeDistribution(); START_SECTION(IsotopeDistribution(const IsotopeDistribution& isotope_distribution)) IsotopeDistribution copy; copy = *iso; for (Size i = 0; i != copy.getContainer().size(); ++i) { TEST_EQUAL(copy.getContainer()[i].getMZ(), iso->getContainer()[i].getMZ()) TEST_EQUAL(copy.getContainer()[i].getIntensity(), iso->getContainer()[i].getIntensity()) } TEST_EQUAL(copy.getMin(), iso->getMin()) TEST_EQUAL(copy.getMax(), iso->getMax()) TEST_EQUAL(copy.size(), iso->size()) END_SECTION START_SECTION(~IsotopeDistribution()) IsotopeDistribution* ptr = new IsotopeDistribution(); delete ptr; END_SECTION START_SECTION(IsotopeDistribution& operator = (const CoarseIsotopePatternGenerator& isotope_distribution)) IsotopeDistribution copy; copy = *iso; for (Size i = 0; i != copy.getContainer().size(); ++i) { TEST_EQUAL(copy.getContainer()[i].getMZ(), iso->getContainer()[i].getMZ()) TEST_EQUAL(copy.getContainer()[i].getIntensity(), iso->getContainer()[i].getIntensity()) } TEST_EQUAL(copy.getMin(), iso->getMin()) TEST_EQUAL(copy.getMax(), iso->getMax()) TEST_EQUAL(copy.size(), iso->size()) END_SECTION START_SECTION(IsotopeDistribution& operator < (const CoarseIsotopePatternGenerator& isotope_distribution)) IsotopeDistribution iso1, iso2; TEST_EQUAL(iso1 < iso2, false) IsotopeDistribution iso3(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))), iso4(EmpiricalFormula("C5").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); TEST_EQUAL(iso3 < iso4, true) IsotopeDistribution iso5(EmpiricalFormula("C5").getIsotopeDistribution(CoarseIsotopePatternGenerator(1))); IsotopeDistribution iso6(EmpiricalFormula("C5").getIsotopeDistribution(CoarseIsotopePatternGenerator(1000))); TEST_EQUAL(iso5 < iso6, true) IsotopeDistribution iso7(EmpiricalFormula("C5").getIsotopeDistribution(CoarseIsotopePatternGenerator(11, true))); IsotopeDistribution iso8(EmpiricalFormula("C5").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); // iso7 should be less because its second isotope's mass is 61 (atomic number), while for iso8 it is 61.003 (expected mass) TEST_EQUAL(iso7 < iso8, true) END_SECTION START_SECTION(bool operator==(const IsotopeDistribution &isotope_distribution) const) IsotopeDistribution iso1, iso2; TEST_TRUE(iso1 == iso2) IsotopeDistribution iso3(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))), iso4(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); TEST_TRUE(iso3 == iso4) IsotopeDistribution iso5(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11, true))), iso6(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); // the masses should be different TEST_EQUAL(iso5 == iso6, false) END_SECTION START_SECTION(void set(const ContainerType &distribution)) IsotopeDistribution iso1(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))), iso2; TEST_EQUAL(iso1 == iso2, false) IsotopeDistribution::ContainerType container = iso1.getContainer(); iso2.set(container); TEST_EQUAL(iso1.getContainer() == iso2.getContainer(), true) TEST_TRUE(iso1 == iso2) END_SECTION START_SECTION(const ContainerType& getContainer() const) NOT_TESTABLE END_SECTION START_SECTION(Size getMax() const) IsotopeDistribution iso(EmpiricalFormula("H2").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); TEST_REAL_SIMILAR(iso.getMax(), 6.02907) IsotopeDistribution iso2(EmpiricalFormula("H2").getIsotopeDistribution(CoarseIsotopePatternGenerator(11, true))); TEST_EQUAL(iso2.getMax(), 6) iso.insert(11.2, 2.0); iso.insert(10.2, 2.0); TEST_REAL_SIMILAR(iso.getMax(), 11.2) END_SECTION START_SECTION(Size getMin() const) IsotopeDistribution iso(EmpiricalFormula("H2").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); TEST_REAL_SIMILAR(iso.getMin(), 2.01565) IsotopeDistribution iso2(EmpiricalFormula("H2").getIsotopeDistribution(CoarseIsotopePatternGenerator(11, true))); TEST_EQUAL(iso2.getMin(), 2) IsotopeDistribution iso3(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); TEST_REAL_SIMILAR(iso3.getMin(), 48) IsotopeDistribution iso4(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11, true))); TEST_EQUAL(iso4.getMin(), 48) iso.insert(1.2, 2.0); iso.insert(10.2, 2.0); TEST_REAL_SIMILAR(iso.getMin(), 1.2) END_SECTION START_SECTION(Size getMostAbundant() const) IsotopeDistribution iso(EmpiricalFormula("C1").getIsotopeDistribution(CoarseIsotopePatternGenerator(11, true))); // The most abundant isotope is the monoisotope TEST_EQUAL(iso.getMostAbundant().getMZ(), 12) IsotopeDistribution iso2(EmpiricalFormula("C100").getIsotopeDistribution(CoarseIsotopePatternGenerator(11, true))); // In this case, the most abundant isotope isn't the monoisotope TEST_EQUAL(iso2.getMostAbundant().getMZ(), 1201) // Empty distribution iso2.clear(); TEST_EQUAL(iso2.getMostAbundant().getMZ(), 0); TEST_EQUAL(iso2.getMostAbundant().getIntensity(), 1); END_SECTION START_SECTION(Size size() const) IsotopeDistribution iso1, iso2(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); TEST_EQUAL(iso1.size(), 1) TEST_EQUAL(iso2.size(), 5) END_SECTION START_SECTION(void clear()) IsotopeDistribution iso2(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); TEST_EQUAL(iso2.size(), 5) iso2.clear(); TEST_EQUAL(iso2.size(), 0) END_SECTION START_SECTION(void trimRight(double cutoff)) IsotopeDistribution iso(EmpiricalFormula("C160").getIsotopeDistribution(CoarseIsotopePatternGenerator(10))); TEST_NOT_EQUAL(iso.size(),3) iso.trimRight(0.2); TEST_EQUAL(iso.size(),3) END_SECTION START_SECTION(void trimLeft(double cutoff)) IsotopeDistribution iso(EmpiricalFormula("C160").getIsotopeDistribution(CoarseIsotopePatternGenerator(10))); iso.trimRight(0.2); iso.trimLeft(0.2); TEST_EQUAL(iso.size(),2) END_SECTION START_SECTION(void renormalize()) IsotopeDistribution iso(EmpiricalFormula("C160").getIsotopeDistribution(CoarseIsotopePatternGenerator(10))); iso.trimRight(0.2); iso.trimLeft(0.2); iso.renormalize(); double sum = 0; for (IsotopeDistribution::ConstIterator it = iso.begin(); it != iso.end(); ++it) { sum += it->getIntensity(); } TEST_REAL_SIMILAR(sum, 1.0) END_SECTION START_SECTION(bool operator!=(const IsotopeDistribution &isotope_distribution) const) IsotopeDistribution iso1; IsotopeDistribution iso2; TEST_EQUAL(iso1 != iso2, false) IsotopeDistribution iso3(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))), iso4(EmpiricalFormula("C4").getIsotopeDistribution(CoarseIsotopePatternGenerator(11))); TEST_EQUAL(iso3 != iso4, false) TEST_FALSE(iso2 == iso3) END_SECTION START_SECTION(Iterator begin()) NOT_TESTABLE END_SECTION START_SECTION(Iterator end()) NOT_TESTABLE END_SECTION START_SECTION(ConstIterator begin() const) NOT_TESTABLE END_SECTION START_SECTION(ConstIterator end() const) NOT_TESTABLE END_SECTION START_SECTION(ReverseIterator rbegin()) NOT_TESTABLE END_SECTION START_SECTION(ReverseIterator rend()) NOT_TESTABLE END_SECTION START_SECTION(ConstReverseIterator rbegin() const) NOT_TESTABLE END_SECTION START_SECTION(ConstReverseIterator rend() const) NOT_TESTABLE END_SECTION delete iso; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST #ifdef __clang__ #pragma clang diagnostic pop #endif
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/EmgFitter1D_test.cpp
.cpp
5,048
147
// 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/EmgFitter1D.h> #include <OpenMS/FEATUREFINDER/EmgModel.h> #include <boost/random/normal_distribution.hpp> #include <boost/random/mersenne_twister.hpp> #include <algorithm> /////////////////////////// using namespace OpenMS; using namespace std; using boost::normal_distribution; START_TEST(EmgFitter1D, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// EmgFitter1D* ptr = nullptr; EmgFitter1D* nullPointer = nullptr; START_SECTION(EmgFitter1D()) { ptr = new EmgFitter1D(); TEST_EQUAL(ptr->getName(), "EmgFitter1D") TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((EmgFitter1D(const EmgFitter1D &source))) EmgFitter1D emgf1; 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 ); param.setValue( "max_iteration", 500 ); param.setValue( "deltaAbsError", 0.0001 ); param.setValue( "deltaRelError", 0.0001 ); emgf1.setParameters(param); EmgFitter1D emgf2(emgf1); EmgFitter1D emgf3; emgf3.setParameters(param); emgf1 = EmgFitter1D(); TEST_EQUAL(emgf3.getParameters(), emgf2.getParameters()) END_SECTION START_SECTION((virtual ~EmgFitter1D())) delete ptr; END_SECTION START_SECTION((virtual EmgFitter1D& operator=(const EmgFitter1D &source))) EmgFitter1D emgf1; 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 ); param.setValue( "max_iteration", 500 ); param.setValue( "deltaAbsError", 0.0001 ); param.setValue( "deltaRelError", 0.0001 ); emgf1.setParameters(param); EmgFitter1D emgf2; emgf2 = emgf1; EmgFitter1D emgf3; emgf3.setParameters(param); emgf1 = EmgFitter1D(); TEST_EQUAL(emgf3.getParameters(), emgf2.getParameters()) END_SECTION START_SECTION((QualityType fit1d(const RawDataArrayType &range, InterpolationModel *&model))) //create data via a model EmgModel em; em.setInterpolationStep(0.2); Param tmp; tmp.setValue("bounding_box:min", 678.9); tmp.setValue("bounding_box:max", 789.0); tmp.setValue("statistics:mean", 680.1 ); tmp.setValue("statistics:variance", 2.0); tmp.setValue("emg:height",100000.0); tmp.setValue("emg:width",5.0); tmp.setValue("emg:symmetry",5.0); tmp.setValue("emg:retention",725.0); em.setParameters(tmp); EmgModel::SamplesType samples; em.getSamples(samples); //fit the data EmgFitter1D ef = EmgFitter1D(); std::unique_ptr<InterpolationModel> em_fitted; EmgFitter1D::QualityType correlation = ef.fit1d(samples, em_fitted); //check the fitted model on the exact data TEST_REAL_SIMILAR(correlation, 1); TEST_REAL_SIMILAR((double)em_fitted->getParameters().getValue("emg:height"), 100000.0); TEST_REAL_SIMILAR((double)em_fitted->getParameters().getValue("emg:width"), 5.0); TEST_REAL_SIMILAR((double)em_fitted->getParameters().getValue("emg:symmetry"), 5.0); TEST_REAL_SIMILAR((double)em_fitted->getParameters().getValue("emg:retention"), 725.0); //shake the samples a little with varying variance (difficult test for fitter) EmgModel::SamplesType unexact_samples; boost::mt19937 rng;//random number generator for(unsigned i=0; i<samples.size(); ++i) { boost::normal_distribution<double> distInt (samples.at(i).getIntensity(), samples.at(i).getIntensity()/100); //use sample intensity as mean Peak1D p (samples.at(i).getPosition()[0], distInt(rng)); std::cout << "point: (" << samples.at(i).getPosition()[0] << ", " << samples.at(i).getIntensity() << ") -> (" << p.getPosition()[0] << ", " << p.getIntensity() << ")" << std::endl; unexact_samples.push_back(p); } //fit the data EmgFitter1D ef1 = EmgFitter1D(); std::unique_ptr<InterpolationModel> em_fitted1; EmgFitter1D::QualityType correlation1 = ef1.fit1d(unexact_samples, em_fitted1); TOLERANCE_RELATIVE(1.01) TEST_REAL_SIMILAR(correlation1, 1); TEST_REAL_SIMILAR((double)em_fitted1->getParameters().getValue("emg:height"), 100000.0); TEST_REAL_SIMILAR((double)em_fitted1->getParameters().getValue("emg:width"), 5.0); TEST_REAL_SIMILAR((double)em_fitted1->getParameters().getValue("emg:symmetry"), 5.0); TEST_REAL_SIMILAR((double)em_fitted1->getParameters().getValue("emg:retention"), 725.0); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MatchedIterator_test.cpp
.cpp
5,890
256
// 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/DATASTRUCTURES/MatchedIterator.h> /////////////////////////// #include <OpenMS/KERNEL/MSSpectrum.h> #include <vector> #include <ostream> using namespace OpenMS; using namespace std; using MIV = MatchedIterator<vector<double>, ValueTrait, true>; std::ostream& operator<<(std::ostream& os, const MIV& m) { os << (*m) << "\n"; return os; } START_TEST(MatchedIterator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MIV* ptr = nullptr; MIV* null_ptr = nullptr; START_SECTION(MatchedIterator()) { ptr = new MIV(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~MatchedIterator()) { delete ptr; } END_SECTION vector<double> ref = { 0, 1, 2, 3, 4, 5, 6, 7, 13 }; vector<double> target = { -0.01, 2.5, 3.5, 7, 11 }; vector<double> empty; START_SECTION((explicit MatchedIterator(const CONT& ref, const CONT& target, float tolerance))) { { // empty reference container MIV mi(empty, target, 0.001); TEST_EQUAL(mi == mi.end(), true); } { // empty target container MIV mi(ref, empty, 0.001); TEST_EQUAL(mi == mi.end(), true); } { // actual data MIV mi(ref, target, 0.001); // only a single hit TEST_EQUAL(mi.ref(), 7); TEST_EQUAL(*mi, 7); TEST_EQUAL(mi.refIdx(), 7) TEST_EQUAL(mi.tgtIdx(), 3) ++mi; // advance to end TEST_EQUAL(mi == mi.end(), true); } { // actual data MIV mi_src; MIV mi(ref, target, 0.5); TEST_EQUAL(mi.ref(), 0); TEST_EQUAL(*mi, -0.01); TEST_EQUAL(mi.refIdx(), 0) TEST_EQUAL(mi.tgtIdx(), 0) ++mi; TEST_EQUAL(mi.ref(), 2); TEST_EQUAL(*mi, 2.5); TEST_EQUAL(mi.refIdx(), 2) TEST_EQUAL(mi.tgtIdx(), 1) mi_src = mi++; // throw in some post-increment TEST_EQUAL(mi.ref(), 3); TEST_EQUAL(*mi, 2.5); TEST_EQUAL(mi.refIdx(), 3) TEST_EQUAL(mi.tgtIdx(), 1) mi_src = mi++; // throw in some post-increment TEST_EQUAL(mi.ref(), 4); TEST_EQUAL(*mi, 3.5); TEST_EQUAL(mi.refIdx(), 4) TEST_EQUAL(mi.tgtIdx(), 2) *mi_src; // just to use it once; ++mi; TEST_EQUAL(mi.ref(), 7); TEST_EQUAL(*mi, 7); TEST_EQUAL(mi.refIdx(), 7) TEST_EQUAL(mi.tgtIdx(), 3) ++mi; TEST_EQUAL(mi == mi.end(), true); TEST_EQUAL(mi.refIdx(), 9) // points to ref.end() TEST_EQUAL(mi.tgtIdx(), 4) // points to last element of target } // test ppm MSSpectrum s, s2; s.emplace_back(90.0, 0.0); s.emplace_back(100.0, 0.0); s.emplace_back(200.0, 0.0); s.emplace_back(300.0, 0.0); s.emplace_back(400.0, 0.0); s2 = s; // add a constant to all peaks for (auto& p : s2) p.setMZ(p.getMZ() + Math::ppmToMass(2.5, 250.0)); MatchedIterator<MSSpectrum, PpmTrait, true> it(s, s2, 2.5); // the first 3 peaks (90, 100, 200) should not match (since 2.5ppm is smaller than the offset we added) TEST_EQUAL(it.refIdx(), 3) // match 300.x TEST_EQUAL(it.tgtIdx(), 3) ++it; TEST_EQUAL(it.refIdx(), 4) // match 400.x TEST_EQUAL(it.tgtIdx(), 4) ++it; TEST_EQUAL(it.refIdx(), 5) // end TEST_EQUAL(it == it.end(), true) TEST_EQUAL(it.tgtIdx(), 4) // target is always valid } END_SECTION START_SECTION(explicit MatchedIterator()) { MIV it; TEST_EQUAL(it != it.end(), true) it = MIV(empty, empty, 1.0); // assigment is the only valid thing... TEST_EQUAL(it == it.end(), true) } END_SECTION START_SECTION(bool operator==(const MatchedIterator& rhs) const) { MIV mi(ref, target, 0.5); TEST_EQUAL(mi.ref(), 0); TEST_EQUAL(*mi, -0.01); TEST_EQUAL(mi.refIdx(), 0) ++mi; MIV mi2(mi); TEST_TRUE(mi == mi2) TEST_EQUAL(mi.ref(), mi2.ref()); TEST_EQUAL(*mi, *mi2); TEST_EQUAL(mi.refIdx(), mi2.refIdx()) TEST_EQUAL(mi.ref(), 2); TEST_EQUAL(*mi, 2.5); TEST_EQUAL(mi.refIdx(), 2) } END_SECTION START_SECTION(bool operator!=(const MatchedIterator& rhs) const) { MIV mi(ref, target, 0.5); MIV mi2(mi); TEST_EQUAL(mi != mi2, false) ++mi; TEST_FALSE(mi == mi2) MIV mi3(mi); TEST_EQUAL(mi != mi3, false) } END_SECTION START_SECTION(const value_type& operator*() const) { NOT_TESTABLE // tested above } END_SECTION typedef pair<double, bool> PDB; /// Trait for MatchedIterator to find pairs with a certain Th/Da distance in m/z struct PairTrait { static float allowedTol(float tol, const PDB& /*mz_ref*/) { return tol; } /// just use fabs on the value directly static float getDiffAbsolute(const PDB& elem_ref, const PDB& elem_tgt) { return fabs(elem_ref.first - elem_tgt.first); } }; START_SECTION(const value_type& operator->() const) { vector<PDB> ref = { {1, true}, {2, false} }; MatchedIterator<vector<pair<double, bool>>, PairTrait> it(ref, ref, 0.1); ++it; TEST_EQUAL(it->first, 2.0) } END_SECTION START_SECTION(const value_type& ref() const) { NOT_TESTABLE // tested above } END_SECTION START_SECTION(size_t refIdx() const) { NOT_TESTABLE // tested above } END_SECTION START_SECTION(size_t tgtIdx() const) { NOT_TESTABLE // tested above } END_SECTION START_SECTION(MatchedIterator& operator++()) { NOT_TESTABLE // tested above } END_SECTION START_SECTION(MatchedIterator operator++(int) const) { NOT_TESTABLE // tested above } END_SECTION START_SECTION(static MatchedIterator end()) { NOT_TESTABLE // tested above } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ParamCTDFile_test.cpp
.cpp
15,935
400
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Ruben Grünberg $ // $Authors: Ruben Grünberg $ // -------------------------------------------------------------------------- #include <fstream> #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/ParamCTDFile.h> #include <OpenMS/FORMAT/ParamXMLFile.h> #include <OpenMS/FORMAT/TextFile.h> #include <OpenMS/DATASTRUCTURES/Param.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> /////////////////////////// #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshadow" #endif using namespace OpenMS; using namespace std; START_TEST(ParamCTDFile, "$Id") ParamCTDFile* ptr = nullptr; ParamCTDFile* nullPtr = nullptr; START_SECTION((ParamCTDFile())) { ptr = new ParamCTDFile(); TEST_NOT_EQUAL(ptr, nullPtr) delete ptr; } 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)) ParamCTDFile paramFile; ParamXMLFile paramXML; 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; ToolInfo info = {"a", "a", "a", "a", "a", std::vector<std::string>()}; TEST_EXCEPTION(std::ios::failure, paramFile.store("/does/not/exist/FileDoesNotExist.ctd",p300,info)) String filename; NEW_TMP_FILE(filename); paramFile.store(filename,p2, info); Param p3; paramXML.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) //advanced NEW_TMP_FILE(filename); Param p7; p7.setValue("true",5,"",{"advanced"}); p7.setValue("false",5,""); paramFile.store(filename,p7, info); Param p8; paramXML.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, info); Param p6; paramXML.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, info); Param p_nan2; paramXML.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() + 7)->hasSubstring("value=\"NaN\"")) TEST_TRUE((tf.begin() + 8)->hasSubstring("value=\"NaN\"")) END_SECTION START_SECTION((void writeCTDToStream(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("outdir_parameter", "", "This is a outdir parameter."); p.addTag("outdir_parameter", "output dir"); 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); ParamCTDFile paramFile; ToolInfo info = {"2.6.0-pre-STL-ParamCTD-2021-06-02", "AccurateMassSearch", "http://www.openms.de/doxygen/nightly/html/TOPP_AccurateMassSearch.html", "Utilities", "Match MS signals to molecules from a database by mass.", {"10.1038/s41592-024-02197-7"}}; paramFile.writeCTDToStream(&s,p, info); s.close(); TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("ParamCTDFile_test_writeCTDToStream.ctd")) } END_SECTION START_SECTION([EXTRA] storing of lists) ParamCTDFile paramFile; ParamXMLFile paramXML; 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); ToolInfo info = {"a", "b", "c", "d", "e", {"f"}}; paramFile.store(filename,p,info); //load Param p2; paramXML.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; ParamCTDFile paramFile; ParamXMLFile paramXML; 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) ToolInfo info = {"a", "a", "a", "a", "a", {"a"}}; paramFile.store(filename,p,info); Param p2; paramXML.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 ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST #ifdef __clang__ #pragma clang diagnostic pop #endif
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Gradient_test.cpp
.cpp
9,108
329
// 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/Gradient.h> #include <OpenMS/DATASTRUCTURES/String.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(Gradient, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Gradient* ptr = nullptr; Gradient* nullPointer = nullptr; START_SECTION((Gradient())) ptr = new Gradient(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~Gradient())) delete ptr; END_SECTION START_SECTION((const std::vector<String>& getEluents() const)) Gradient tmp; TEST_EQUAL(tmp.getEluents().size(),0); END_SECTION START_SECTION((void addEluent(const String& eluent) )) Gradient tmp; tmp.addEluent("A"); TEST_EQUAL(tmp.getEluents().size(),1); TEST_EQUAL(tmp.getEluents()[0],"A"); tmp.addEluent("B"); TEST_EQUAL(tmp.getEluents().size(),2); TEST_EQUAL(tmp.getEluents()[0],"A"); TEST_EQUAL(tmp.getEluents()[1],"B"); TEST_EXCEPTION(Exception::InvalidValue,tmp.addEluent("B")) END_SECTION START_SECTION((void clearEluents())) Gradient tmp; tmp.addEluent("A"); tmp.clearEluents(); TEST_EQUAL(tmp.getEluents().size(),0); END_SECTION START_SECTION((const std::vector<Int>& getTimepoints() const)) Gradient tmp; TEST_EQUAL(tmp.getTimepoints().size(),0); END_SECTION START_SECTION((void addTimepoint(Int timepoint) )) Gradient tmp; tmp.addTimepoint(5); TEST_EQUAL(tmp.getTimepoints().size(),1); TEST_EQUAL(tmp.getTimepoints()[0],5); tmp.addTimepoint(7); TEST_EQUAL(tmp.getTimepoints().size(),2); TEST_EQUAL(tmp.getTimepoints()[0],5); TEST_EQUAL(tmp.getTimepoints()[1],7); TEST_EXCEPTION(Exception::OutOfRange,tmp.addTimepoint(6)); TEST_EXCEPTION(Exception::OutOfRange,tmp.addTimepoint(7)); tmp.addTimepoint(8); END_SECTION START_SECTION((void clearTimepoints())) Gradient tmp; tmp.addTimepoint(5); tmp.clearTimepoints(); TEST_EQUAL(tmp.getTimepoints().size(),0); END_SECTION START_SECTION((const std::vector< std::vector< UInt > > & getPercentages() const)) Gradient tmp; tmp.addTimepoint(5); tmp.addTimepoint(7); tmp.addEluent("A"); tmp.addEluent("B"); tmp.addEluent("C"); TEST_EQUAL(tmp.getPercentages().size(),3); TEST_EQUAL(tmp.getPercentages()[0].size(),2); TEST_EQUAL(tmp.getPercentages()[1].size(),2); TEST_EQUAL(tmp.getPercentages()[2].size(),2); TEST_EQUAL(tmp.getPercentages()[0][0],0); TEST_EQUAL(tmp.getPercentages()[0][1],0); TEST_EQUAL(tmp.getPercentages()[1][0],0); TEST_EQUAL(tmp.getPercentages()[1][1],0); TEST_EQUAL(tmp.getPercentages()[2][0],0); TEST_EQUAL(tmp.getPercentages()[2][1],0); END_SECTION START_SECTION((void setPercentage(const String& eluent, Int timepoint, UInt percentage) )) Gradient tmp; tmp.addTimepoint(5); tmp.addTimepoint(7); tmp.addEluent("A"); tmp.addEluent("B"); tmp.addEluent("C"); tmp.setPercentage("A",5,90); tmp.setPercentage("B",5,10); tmp.setPercentage("C",5,0); tmp.setPercentage("A",7,30); tmp.setPercentage("B",7,50); tmp.setPercentage("C",7,20); TEST_EQUAL(tmp.getPercentages().size(),3); TEST_EQUAL(tmp.getPercentages()[0].size(),2); TEST_EQUAL(tmp.getPercentages()[1].size(),2); TEST_EQUAL(tmp.getPercentages()[2].size(),2); TEST_EQUAL(tmp.getPercentages()[0][0],90); TEST_EQUAL(tmp.getPercentages()[0][1],30); TEST_EQUAL(tmp.getPercentages()[1][0],10); TEST_EQUAL(tmp.getPercentages()[1][1],50); TEST_EQUAL(tmp.getPercentages()[2][0],0); TEST_EQUAL(tmp.getPercentages()[2][1],20); TEST_EXCEPTION(Exception::InvalidValue,tmp.setPercentage("D",7,20)); TEST_EXCEPTION(Exception::InvalidValue,tmp.setPercentage("C",9,20)); TEST_EXCEPTION(Exception::InvalidValue,tmp.setPercentage("C",7,101)); END_SECTION START_SECTION((UInt getPercentage(const String& eluent, Int timepoint) const )) Gradient tmp; tmp.addTimepoint(5); tmp.addTimepoint(7); tmp.addEluent("A"); tmp.addEluent("B"); tmp.addEluent("C"); tmp.setPercentage("A",5,90); tmp.setPercentage("B",5,10); tmp.setPercentage("C",5,0); tmp.setPercentage("A",7,30); tmp.setPercentage("B",7,50); tmp.setPercentage("C",7,20); TEST_EQUAL(tmp.getPercentage("A",5),90); TEST_EQUAL(tmp.getPercentage("A",7),30); TEST_EQUAL(tmp.getPercentage("B",5),10); TEST_EQUAL(tmp.getPercentage("B",7),50); TEST_EQUAL(tmp.getPercentage("C",5),0); TEST_EQUAL(tmp.getPercentage("C",7),20); TEST_EXCEPTION(Exception::InvalidValue,tmp.getPercentage("D",7)); TEST_EXCEPTION(Exception::InvalidValue,tmp.getPercentage("C",9)); END_SECTION START_SECTION((void clearPercentages())) Gradient tmp; tmp.addTimepoint(5); tmp.addTimepoint(7); tmp.addEluent("A"); tmp.addEluent("B"); tmp.addEluent("C"); tmp.setPercentage("A",5,90); tmp.setPercentage("B",5,10); tmp.setPercentage("C",5,0); tmp.setPercentage("A",7,30); tmp.setPercentage("B",7,50); tmp.setPercentage("C",7,20); tmp.clearPercentages(); TEST_EQUAL(tmp.getPercentages().size(),3); TEST_EQUAL(tmp.getPercentages()[0].size(),2); TEST_EQUAL(tmp.getPercentages()[1].size(),2); TEST_EQUAL(tmp.getPercentages()[2].size(),2); TEST_EQUAL(tmp.getPercentages()[0][0],0); TEST_EQUAL(tmp.getPercentages()[0][1],0); TEST_EQUAL(tmp.getPercentages()[1][0],0); TEST_EQUAL(tmp.getPercentages()[1][1],0); TEST_EQUAL(tmp.getPercentages()[2][0],0); TEST_EQUAL(tmp.getPercentages()[2][1],0); END_SECTION START_SECTION((bool isValid() const)) Gradient tmp; TEST_EQUAL(tmp.isValid(),true); tmp.addTimepoint(5); tmp.addTimepoint(7); TEST_EQUAL(tmp.isValid(),false); tmp.addEluent("A"); tmp.addEluent("B"); tmp.addEluent("C"); TEST_EQUAL(tmp.isValid(),false); tmp.setPercentage("A",5,90); tmp.setPercentage("B",5,10); tmp.setPercentage("C",5,0); tmp.setPercentage("A",7,30); tmp.setPercentage("B",7,50); tmp.setPercentage("C",7,20); TEST_EQUAL(tmp.isValid(),true); tmp.setPercentage("A",5,91); TEST_EQUAL(tmp.isValid(),false); tmp.setPercentage("B",5,9); TEST_EQUAL(tmp.isValid(),true); tmp.setPercentage("A",7,29); TEST_EQUAL(tmp.isValid(),false); tmp.setPercentage("B",7,51); TEST_EQUAL(tmp.isValid(),true); tmp.setPercentage("C",5,1); TEST_EQUAL(tmp.isValid(),false); tmp.setPercentage("A",5,90); TEST_EQUAL(tmp.isValid(),true); tmp.setPercentage("C",7,19); TEST_EQUAL(tmp.isValid(),false); tmp.setPercentage("A",7,30); TEST_EQUAL(tmp.isValid(),true); END_SECTION START_SECTION((Gradient(const Gradient& source))) Gradient tmp; tmp.addTimepoint(5); tmp.addEluent("A"); tmp.addEluent("B"); tmp.setPercentage("A",5,90); tmp.setPercentage("B",5,10); Gradient tmp2(tmp); TEST_EQUAL(tmp2.getPercentages().size(),2); TEST_EQUAL(tmp2.getPercentages()[0].size(),1); TEST_EQUAL(tmp2.getPercentages()[1].size(),1); TEST_EQUAL(tmp2.getPercentage("A",5),90); TEST_EQUAL(tmp2.getPercentage("B",5),10); END_SECTION START_SECTION((Gradient& operator = (const Gradient& source))) Gradient tmp; tmp.addTimepoint(5); tmp.addEluent("A"); tmp.addEluent("B"); tmp.setPercentage("A",5,90); tmp.setPercentage("B",5,10); Gradient tmp2; tmp2 = tmp; TEST_EQUAL(tmp2.getPercentages().size(),2); TEST_EQUAL(tmp2.getPercentages()[0].size(),1); TEST_EQUAL(tmp2.getPercentages()[1].size(),1); TEST_EQUAL(tmp2.getPercentage("A",5),90); TEST_EQUAL(tmp2.getPercentage("B",5),10); tmp2 = Gradient(); TEST_EQUAL(tmp2.getPercentages().size(),0); TEST_EQUAL(tmp2.getTimepoints().size(),0); TEST_EQUAL(tmp2.getEluents().size(),0); END_SECTION START_SECTION((bool operator == (const Gradient& source) const)) Gradient base; base.addTimepoint(5); base.addEluent("A"); base.addEluent("B"); base.setPercentage("A",5,90); base.setPercentage("B",5,10); Gradient edit(base); TEST_EQUAL(edit==base,true); edit.addEluent("C"); TEST_EQUAL(edit==base,false); edit = base; edit.addTimepoint(7); TEST_EQUAL(edit==base,false); edit = base; edit.setPercentage("B",5,11); TEST_EQUAL(edit==base,false); END_SECTION START_SECTION((bool operator != (const Gradient& source) const)) Gradient base; base.addTimepoint(5); base.addEluent("A"); base.addEluent("B"); base.setPercentage("A",5,90); base.setPercentage("B",5,10); Gradient edit(base); TEST_EQUAL(edit!=base,false); edit.addEluent("C"); TEST_EQUAL(edit!=base,true); edit = base; edit.addTimepoint(7); TEST_EQUAL(edit!=base,true); edit = base; edit.setPercentage("B",5,11); TEST_EQUAL(edit!=base,true); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DataFilters_test.cpp
.cpp
18,248
588
// 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/PROCESSING/MISC/DataFilters.h> #include <OpenMS/KERNEL/Feature.h> #include <OpenMS/KERNEL/ConsensusFeature.h> #include <OpenMS/KERNEL/Peak1D.h> /////////////////////////// START_TEST(DataFilters, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; typedef BaseFeature::QualityType QualityType; ///constructor and destructor test DataFilters* ptr; DataFilters* nullPointer = nullptr; START_SECTION((DataFilters())) ptr = new DataFilters(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(([EXTRA]~DataFilters())) delete ptr; END_SECTION DataFilters::DataFilter* ptr2 = nullptr; DataFilters::DataFilter* nullPointer2 = nullptr; START_SECTION(([EXTRA]DataFilters::DataFilter())) ptr2 = new DataFilters::DataFilter(); TEST_NOT_EQUAL(ptr2, nullPointer2) END_SECTION START_SECTION(([EXTRA]~DataFilters::DataFilter())) delete ptr2; END_SECTION DataFilters::DataFilter filter_1; DataFilters::DataFilter filter_2; DataFilters::DataFilter filter_3; DataFilters::DataFilter filter_4; DataFilters::DataFilter filter_5; DataFilters::DataFilter filter_6; DataFilters::DataFilter filter_7; DataFilters::DataFilter filter_8; DataFilters::DataFilter filter_9; DataFilters::DataFilter filter_10; DataFilters::DataFilter filter_11; DataFilters::DataFilter filter_12; START_SECTION(([EXTRA]void DataFilter::fromString(const String& filter))) TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidValue, filter_1.fromString(""), "the value '' was used but is not valid; invalid filter format") TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidValue, filter_1.fromString("not_enough_arguments"), "the value 'not_enough_arguments' was used but is not valid; invalid filter format") TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidValue, filter_1.fromString("invalid_fieldname = 0"), "the value 'invalid_fieldname' was used but is not valid; invalid field name") TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidValue, filter_1.fromString("Intensity invalid_operator 5"), "the value 'invalid_operator' was used but is not valid; invalid operator") TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidValue, filter_1.fromString("Meta::test = string without enclosing quotation marks"), "the value 'string without enclosing quotation marks' was used but is not valid; invalid value") //second argument of binary relation missing: TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidValue, filter_1.fromString("Charge = "), "the value '=' was used but is not valid; invalid filter format") //string value and non-meta field: TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidValue, filter_1.fromString("Quality = \"a string\""), "the value 'a string' was used but is not valid; invalid value") //operation "exists" and non-meta field: TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidValue, filter_1.fromString("Intensity exists"), "the value 'exists' was used but is not valid; invalid operator") filter_1.fromString("Intensity <= 201.334"); filter_2.fromString("Intensity >= 1000"); filter_3.fromString("Charge = 4"); filter_4.fromString("Quality <= 1.0"); filter_5.fromString("Meta::test_int <= 0"); filter_6.fromString("Meta::test_double = 0"); filter_7.fromString("Meta::test_string = \"hello world 2\""); filter_8.fromString("Meta::test_dummy exists"); //valid, but nonsense (nothing will pass this filter): filter_9.fromString("Meta::test_string >= \"a string\""); filter_10.fromString("Meta::test_string = \"hello world 2\""); filter_11.fromString("Meta::unknown_metavalue = 5"); filter_12.fromString("Meta::test_dummy2 exists"); END_SECTION START_SECTION(([EXTRA]String DataFilter::toString() const)) TEST_STRING_EQUAL(filter_1.toString(), "Intensity <= 201.334000000000003") TEST_STRING_EQUAL(filter_2.toString(), "Intensity >= 1000.0") TEST_STRING_EQUAL(filter_3.toString(), "Charge = 4.0") TEST_STRING_EQUAL(filter_4.toString(), "Quality <= 1.0") TEST_STRING_EQUAL(filter_5.toString(), "Meta::test_int <= 0.0") TEST_STRING_EQUAL(filter_6.toString(), "Meta::test_double = 0.0") TEST_STRING_EQUAL(filter_7.toString(), "Meta::test_string = \"hello world 2\"") TEST_STRING_EQUAL(filter_8.toString(), "Meta::test_dummy exists") TEST_STRING_EQUAL(filter_9.toString(), "Meta::test_string >= \"a string\"") END_SECTION START_SECTION(([EXTRA]bool DataFilter::operator==(const DataFilter& rhs) const)) TEST_TRUE(filter_10 == filter_7) TEST_EQUAL(filter_1 == filter_2, false) TEST_TRUE(filter_3 == filter_3) END_SECTION START_SECTION(([EXTRA]bool DataFilter::operator!=(const DataFilter& rhs) const)) TEST_EQUAL(filter_10 != filter_7, false) TEST_FALSE(filter_3 == filter_4) TEST_EQUAL(filter_4 != filter_4, false) END_SECTION START_SECTION((bool isActive() const)) DataFilters tmp; TEST_EQUAL(tmp.isActive(), false) END_SECTION START_SECTION((void setActive(bool is_active))) DataFilters tmp; tmp.setActive(true); TEST_EQUAL(tmp.isActive(), true) END_SECTION DataFilters filters; START_SECTION((void add(const DataFilter& filter))) filters.add(filter_1); filters.add(filter_2); filters.add(filter_3); TEST_EQUAL(filters[0] == filter_1, true) TEST_EQUAL(filters[1] == filter_2, true) TEST_EQUAL(filters[2] == filter_3, true) END_SECTION START_SECTION((const DataFilter& operator[](Size index) const )) TEST_EXCEPTION(Exception::IndexOverflow, filters[3]) filters.add(filter_1); TEST_EQUAL(filters[0] == filters[3], true) filters.remove(3); END_SECTION START_SECTION((Size size() const)) TEST_EQUAL(filters.size(), 3) filters.add(filter_4); TEST_EQUAL(filters.size(), 4) filters.add(filter_5); filters.add(filter_6); filters.add(filter_7); filters.add(filter_8); filters.add(filter_9); TEST_EQUAL(filters.size(), 9) filters.remove(0); TEST_EQUAL(filters.size(), 8) filters.remove(0); TEST_EQUAL(filters.size(), 7) END_SECTION START_SECTION((void remove(Size index))) TEST_EXCEPTION(Exception::IndexOverflow, filters.remove(7)) filters.remove(0); TEST_EQUAL(filters[0] == filter_4, true) filters.remove(0); TEST_EQUAL(filters[0] == filter_5, true) END_SECTION START_SECTION((void replace(Size index, const DataFilter &filter))) TEST_EXCEPTION(Exception::IndexOverflow, filters.replace(10, filter_1)) //at the moment: filters[0] == filter_5, ..., filters[4] == filter_9 filters.replace(0, filter_1); filters.replace(1, filter_2); filters.replace(2, filter_3); filters.replace(3, filter_4); filters.replace(4, filter_5); TEST_EQUAL(filters[0] == filter_1, true) TEST_EQUAL(filters[1] == filter_2, true) TEST_EQUAL(filters[2] == filter_3, true) TEST_EQUAL(filters[3] == filter_4, true) TEST_EQUAL(filters[4] == filter_5, true) TEST_EQUAL(filters.size(), 5) END_SECTION START_SECTION((void clear())) filters.clear(); TEST_EQUAL(filters.size(), 0) END_SECTION ///construct some test features Feature feature_1; feature_1.setIntensity(1000.00f); feature_1.setCharge(4); feature_1.setOverallQuality((QualityType)31.3334); feature_1.setMetaValue(String("test_int"), 5); feature_1.setMetaValue(String("test_double"), 23.42); feature_1.setMetaValue(String("test_string"), String("hello world 1")); Feature feature_2; feature_2.setIntensity(122.01f); feature_2.setCharge(3); feature_2.setOverallQuality((QualityType)0.002); feature_2.setMetaValue(String("test_int"), 10); feature_2.setMetaValue(String("test_double"), 0.042); feature_2.setMetaValue(String("test_string"), String("hello world 2")); Feature feature_3; feature_3.setIntensity(55.0f); feature_3.setCharge(4); feature_3.setOverallQuality((QualityType) 1.); feature_3.setMetaValue(String("test_int"), 0); feature_3.setMetaValue(String("test_double"), 100.01); feature_3.setMetaValue(String("test_string"), String("hello world 3")); ///construct some test consensus features ConsensusFeature c_feature_1; c_feature_1.setIntensity(1000.00f); c_feature_1.setCharge(4); c_feature_1.setQuality((QualityType) 31.3334); ConsensusFeature c_feature_2; c_feature_2.setIntensity(122.01f); c_feature_2.setCharge(3); c_feature_2.setQuality((QualityType) 0.002); ConsensusFeature c_feature_3; c_feature_3.setIntensity(55.0f); c_feature_3.setCharge(4); c_feature_3.setQuality((QualityType) 1.); ///construct some test peaks MSSpectrum spec; Peak1D peak; peak.setIntensity(201.334f); spec.push_back(peak); peak.setIntensity(2008.2f); spec.push_back(peak); peak.setIntensity(0.001f); spec.push_back(peak); MSSpectrum::FloatDataArrays& mdas = spec.getFloatDataArrays(); mdas.resize(3); mdas[0].setName("test_int"); mdas[0].resize(3); mdas[0][0] = 5; mdas[0][1] = 10; mdas[0][2] = 0; mdas[1].setName("test_double"); mdas[1].resize(3); mdas[1][0] = 23.42f; mdas[1][1] = 0.0f; mdas[1][2] = 100.01f; mdas[2].setName("test_dummy"); mdas[2].resize(3); START_SECTION((template < class PeakType > bool passes(const MSSpectrum &spectrum, Size peak_index) const )) filters.add(filter_1); // "Intensity <= 201.334" TEST_EQUAL(filters.passes(spec,0), true) // 201.334 TEST_EQUAL(filters.passes(spec,1), false) // 2008.2 TEST_EQUAL(filters.passes(spec,2), true) // 0.001 filters.add(filter_2); // "Intensity <= 201.334" && "Intensity >= 1000" TEST_EQUAL(filters.passes(spec,0), false) // 201.334 TEST_EQUAL(filters.passes(spec,1), false) // 2008.2 TEST_EQUAL(filters.passes(spec,2), false) // 0.001 filters.remove(0); // "Intensity >= 1000" TEST_EQUAL(filters.passes(spec,0), false) // 201.334 TEST_EQUAL(filters.passes(spec,1), true) // 2008.2 TEST_EQUAL(filters.passes(spec,2), false) // 0.001 filters.clear(); filters.add(filter_5); // "Meta::test_int <= 0" TEST_EQUAL(filters.passes(spec,0), false) // 5 TEST_EQUAL(filters.passes(spec,1), false) // 10 TEST_EQUAL(filters.passes(spec,2), true) // 0 filters.clear(); filters.add(filter_8); // Meta::test_dummy exists TEST_EQUAL(filters.passes(spec,0), true) TEST_EQUAL(filters.passes(spec,1), true) TEST_EQUAL(filters.passes(spec,2), true) filters.clear(); filters.add(filter_12); // Meta::test_dummy2 exists TEST_EQUAL(filters.passes(spec,0), false) TEST_EQUAL(filters.passes(spec,1), false) TEST_EQUAL(filters.passes(spec,2), false) filters.clear(); filters.add(filter_6); // Meta::test_double = 0 TEST_EQUAL(filters.passes(spec,0), false) TEST_EQUAL(filters.passes(spec,1), true) TEST_EQUAL(filters.passes(spec,2), false) END_SECTION START_SECTION((bool passes(const Feature& feature) const)) filters.clear(); filters.add(filter_3); // "Charge = 4" TEST_EQUAL(filters.passes(feature_1), true) // 4 TEST_EQUAL(filters.passes(feature_2), false) // 3 TEST_EQUAL(filters.passes(feature_3), true) // 4 filters.add(filter_4); // "Quality <= 1.0" && "Charge = 4" TEST_EQUAL(filters.passes(feature_1), false) // Quality = 31.3334; Charge = 4 TEST_EQUAL(filters.passes(feature_2), false) // Quality = 0.002; Charge = 3 TEST_EQUAL(filters.passes(feature_3), true) // Quality = 1; Charge = 4 filters.remove(0); // "Quality <= 1.0" TEST_EQUAL(filters.passes(feature_1), false) // Quality = 31.3334 TEST_EQUAL(filters.passes(feature_2), true) // Quality = 0.002 TEST_EQUAL(filters.passes(feature_3), true) // Quality = 1 filters.clear(); filters.add(filter_2); // "Intensity >= 1000" TEST_EQUAL(filters.passes(feature_1), true) // 1000.00 TEST_EQUAL(filters.passes(feature_2), false) // 122.01 TEST_EQUAL(filters.passes(feature_3), false) // 55.0 filters.clear(); filters.add(filter_7); // "Meta::test_string = \"hello world 2\"" TEST_EQUAL(filters.passes(feature_1), false) TEST_EQUAL(filters.passes(feature_2), true) TEST_EQUAL(filters.passes(feature_3), false) filters.add(filter_8); // "Meta::test_dummy exists" TEST_EQUAL(filters.passes(feature_1), false) TEST_EQUAL(filters.passes(feature_2), false) TEST_EQUAL(filters.passes(feature_3), false) filters.clear(); filters.add(filter_5); // "Meta::test_int <= 0" TEST_EQUAL(filters.passes(feature_1), false) // 5 TEST_EQUAL(filters.passes(feature_2), false) // 10 TEST_EQUAL(filters.passes(feature_3), true) // 0 END_SECTION START_SECTION((bool passes(const ConsensusFeature& consensus_feature) const)) filters.clear(); filters.add(filter_3); // "Charge = 4" TEST_EQUAL(filters.passes(c_feature_1), true) // 4 TEST_EQUAL(filters.passes(c_feature_2), false) // 3 TEST_EQUAL(filters.passes(c_feature_3), true) // 4 filters.add(filter_4); // "Quality <= 1.0" && "Charge = 4" TEST_EQUAL(filters.passes(c_feature_1), false) // Quality = 31.3334; Charge = 4 TEST_EQUAL(filters.passes(c_feature_2), false) // Quality = 0.002; Charge = 3 TEST_EQUAL(filters.passes(c_feature_3), true) // Quality = 1; Charge = 4 filters.remove(0); // "Quality <= 1.0" TEST_EQUAL(filters.passes(c_feature_1), false) // Quality = 31.3334 TEST_EQUAL(filters.passes(c_feature_2), true) // Quality = 0.002 TEST_EQUAL(filters.passes(c_feature_3), true) // Quality = 1 filters.clear(); filters.add(filter_2); // "Intensity >= 1000" TEST_EQUAL(filters.passes(c_feature_1), true) // 1000.00 TEST_EQUAL(filters.passes(c_feature_2), false) // 122.01 TEST_EQUAL(filters.passes(c_feature_3), false) // 55.0 END_SECTION DataFilters::DataFilter* df_ptr; START_SECTION(([DataFilters::DataFilter] DataFilter())) { df_ptr = new DataFilters::DataFilter(); TEST_NOT_EQUAL(df_ptr, nullPointer2) delete df_ptr; } END_SECTION START_SECTION(([DataFilters::DataFilter] String toString() const )) { DataFilters::DataFilter df1; df1.field = DataFilters::INTENSITY; df1.op = DataFilters::LESS_EQUAL; df1.value = 25.5; TEST_EQUAL(df1.toString(), "Intensity <= 25.5") df1.field = DataFilters::META_DATA; df1.meta_name = "meta-value"; df1.op = DataFilters::EXISTS; df1.value_is_numerical = false; TEST_EQUAL(df1.toString(), "Meta::meta-value exists") df1.op = DataFilters::EQUAL; df1.value_string = "value"; TEST_EQUAL(df1.toString(), "Meta::meta-value = \"value\"") } END_SECTION START_SECTION(([DataFilters::DataFilter] void fromString(const String &filter))) { DataFilters::DataFilter df1; df1.fromString("Intensity <= 25.3"); TEST_EQUAL(df1.field, DataFilters::INTENSITY) TEST_EQUAL(df1.op, DataFilters::LESS_EQUAL) TEST_EQUAL(df1.value, 25.3) TEST_EQUAL(df1.value_is_numerical, true) DataFilters::DataFilter df2; df2.fromString("Meta::meta-value exists"); TEST_EQUAL(df2.field, DataFilters::META_DATA) TEST_EQUAL(df2.op, DataFilters::EXISTS) TEST_EQUAL(df2.meta_name, "meta-value") DataFilters::DataFilter df3; df3.fromString("Meta::meta-value = \"value\""); TEST_EQUAL(df3.field, DataFilters::META_DATA) TEST_EQUAL(df3.op, DataFilters::EQUAL) TEST_EQUAL(df3.meta_name, "meta-value") TEST_EQUAL(df3.value_string, "value") TEST_EQUAL(df3.value_is_numerical, false) // test some wrong cases DataFilters::DataFilter exception_filter; TEST_EXCEPTION(Exception::InvalidValue, exception_filter.fromString("Intensity <> 24.5")) TEST_EXCEPTION(Exception::InvalidValue, exception_filter.fromString("Intensity < 24.5")) TEST_EXCEPTION(Exception::InvalidValue, exception_filter.fromString("Insenity = 2.0")) TEST_EXCEPTION(Exception::InvalidValue, exception_filter.fromString("Charge = text-value")) } END_SECTION START_SECTION(([DataFilters::DataFilter] bool operator==(const DataFilter &rhs) const )) { DataFilters::DataFilter df1,df2,df3; TEST_TRUE(df1 == df2) // field df1.field = DataFilters::CHARGE; df2.field = DataFilters::CHARGE; df3.field = DataFilters::INTENSITY; TEST_EQUAL(df1==df2,true) TEST_EQUAL(df1==df3,false) df3.field = DataFilters::CHARGE; // op df1.op = DataFilters::EQUAL; df2.op = DataFilters::EQUAL; df3.op = DataFilters::GREATER_EQUAL; TEST_EQUAL(df1==df2,true) TEST_EQUAL(df1==df3,false) df3.op = DataFilters::EQUAL; // value_is_numerical df1.value = 0.0; df2.value = 0.0; df3.value = 0.2; TEST_EQUAL(df1==df2,true) TEST_EQUAL(df1==df3,false) df1.meta_name = "df1"; df2.meta_name = "df1"; TEST_EQUAL(df1==df2,true) df2.meta_name = "df2"; TEST_EQUAL(df1==df2,false) df2.meta_name = "df1"; df1.value_string = "df1"; df2.value_string = "df1"; TEST_EQUAL(df1==df2,true) df2.value_string = "df2"; TEST_EQUAL(df1==df2,false) df2.value_string = "df1"; df1.value_is_numerical = true; df2.value_is_numerical = true; TEST_EQUAL(df1==df2,true) df2.value_is_numerical = false; TEST_EQUAL(df1==df2,false) } END_SECTION START_SECTION(([DataFilters::DataFilter] bool operator!=(const DataFilter &rhs) const )) { DataFilters::DataFilter df1,df2,df3; TEST_TRUE(df1 == df2) // field df1.field = DataFilters::CHARGE; df2.field = DataFilters::CHARGE; df3.field = DataFilters::INTENSITY; TEST_EQUAL(df1!=df2,false) TEST_EQUAL(df1!=df3,true) df3.field = DataFilters::CHARGE; // op df1.op = DataFilters::EQUAL; df2.op = DataFilters::EQUAL; df3.op = DataFilters::GREATER_EQUAL; TEST_EQUAL(df1!=df2,false) TEST_EQUAL(df1!=df3,true) df3.op = DataFilters::EQUAL; // value_is_numerical df1.value = 0.0; df2.value = 0.0; df3.value = 0.2; TEST_EQUAL(df1!=df2,false) TEST_EQUAL(df1!=df3,true) df1.meta_name = "df1"; df2.meta_name = "df1"; TEST_EQUAL(df1!=df2,false) df2.meta_name = "df2"; TEST_EQUAL(df1!=df2,true) df2.meta_name = "df1"; df1.value_string = "df1"; df2.value_string = "df1"; TEST_EQUAL(df1!=df2,false) df2.value_string = "df2"; TEST_EQUAL(df1!=df2,true) df2.value_string = "df1"; df1.value_is_numerical = true; df2.value_is_numerical = true; TEST_EQUAL(df1!=df2,false) df2.value_is_numerical = false; TEST_EQUAL(df1!=df2,true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SpectrumAlignment_test.cpp
.cpp
5,171
173
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <iostream> #include <OpenMS/COMPARISON/SpectrumAlignment.h> #include <OpenMS/PROCESSING/SCALING/Normalizer.h> #include <OpenMS/FORMAT/DTAFile.h> /////////////////////////// START_TEST(SpectrumAlignment, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; SpectrumAlignment* ptr = nullptr; SpectrumAlignment* nullPointer = nullptr; START_SECTION(SpectrumAlignment()) ptr = new SpectrumAlignment(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(virtual ~SpectrumAlignment()) delete ptr; END_SECTION START_SECTION(SpectrumAlignment(const SpectrumAlignment &source)) SpectrumAlignment sas1; Param p(sas1.getParameters()); p.setValue("tolerance", 0.2); sas1.setParameters(p); SpectrumAlignment sas2(sas1); TEST_EQUAL(sas1.getName(), sas2.getName()) TEST_EQUAL(sas1.getParameters(), sas2.getParameters()) END_SECTION START_SECTION(SpectrumAlignment& operator=(const SpectrumAlignment &source)) SpectrumAlignment sas1; Param p(sas1.getParameters()); p.setValue("tolerance", 0.2); sas1.setParameters(p); SpectrumAlignment sas2; sas2 = sas1; TEST_EQUAL(sas1.getName(), sas2.getName()) TEST_EQUAL(p, sas2.getParameters()) END_SECTION START_SECTION(template <typename SpectrumType> void getSpectrumAlignment(std::vector< std::pair< Size, Size > > &alignment, const SpectrumType &s1, const SpectrumType &s2) 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); TOLERANCE_ABSOLUTE(0.01) SpectrumAlignment sas1; vector<pair<Size, Size > > alignment; sas1.getSpectrumAlignment(alignment, s1, s2); for (vector<pair<Size, Size > >::const_iterator it = alignment.begin(); it != alignment.end(); ++it) { // cerr << it->first << " " << it->second << endl; } TEST_EQUAL(alignment.size(), s1.size()) s2.resize(100); alignment.clear(); sas1.getSpectrumAlignment(alignment, s1, s2); TEST_EQUAL(alignment.size(), 100) // TODO: write better test scenario PeakSpectrum s3, s4; Param p; p.setValue("tolerance", 1.01); sas1.setParameters(p); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("SpectrumAlignment_in1.dta"), s3); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("SpectrumAlignment_in2.dta"), s4); sas1.getSpectrumAlignment(alignment, s3, s4); TEST_EQUAL(alignment.size(), 5) ABORT_IF(alignment.size()!=5) vector<pair<Size, Size > > alignment_result; alignment_result.push_back(std::make_pair(0,0)); alignment_result.push_back(std::make_pair(1,1)); alignment_result.push_back(std::make_pair(3,3)); alignment_result.push_back(std::make_pair(4,5)); alignment_result.push_back(std::make_pair(6,6)); for (Size i=0;i<5;++i) { TEST_EQUAL(alignment[i].first, alignment_result[i].first) TEST_EQUAL(alignment[i].second, alignment_result[i].second) } // test relative tolerance alignment alignment.clear(); p.setValue("is_relative_tolerance", "true"); p.setValue("tolerance", 10.0); // 10 ppm tolerance sas1.setParameters(p); sas1.getSpectrumAlignment(alignment, s3, s4); TEST_EQUAL(alignment.size(), 1) ABORT_IF(alignment.size()!=1) alignment_result.clear(); alignment_result.push_back(std::make_pair(6,6)); for (Size i=0;i<alignment.size();++i) { TEST_EQUAL(alignment[i].first, alignment_result[i].first) TEST_EQUAL(alignment[i].second, alignment_result[i].second) } alignment.clear(); p.setValue("is_relative_tolerance", "true"); p.setValue("tolerance", 1e4); // one percent tolerance sas1.setParameters(p); sas1.getSpectrumAlignment(alignment, s3, s4); for (vector<pair<Size, Size > >::const_iterator it = alignment.begin(); it != alignment.end(); ++it) { // cerr << it->first << " " << it->second << endl; } TEST_EQUAL(alignment.size(), 7) ABORT_IF(alignment.size()!=7) alignment_result.clear(); alignment_result.push_back(std::make_pair(0,0)); alignment_result.push_back(std::make_pair(1,1)); alignment_result.push_back(std::make_pair(2,2)); alignment_result.push_back(std::make_pair(3,3)); alignment_result.push_back(std::make_pair(4,5)); alignment_result.push_back(std::make_pair(5,5)); alignment_result.push_back(std::make_pair(6,6)); for (Size i=0;i<7;++i) { TEST_EQUAL(alignment[i].first, alignment_result[i].first) TEST_EQUAL(alignment[i].second, alignment_result[i].second) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TargetedExperiment_test.cpp
.cpp
11,239
495
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(TargetedExperiment, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TargetedExperiment* ptr = nullptr; TargetedExperiment* nullPointer = nullptr; START_SECTION(TargetedExperiment()) { ptr = new TargetedExperiment(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~TargetedExperiment()) { delete ptr; } END_SECTION TargetedExperiment te; START_SECTION((TargetedExperiment(const TargetedExperiment &rhs))) { TargetedExperiment t; ReactionMonitoringTransition tr; t.addTransition(tr); { TargetedExperiment::Peptide p; p.id = "myPep"; t.addPeptide(p); } { TargetedExperiment::Protein p; p.id = "myProtein"; t.addProtein(p); } { TargetedExperiment::Compound c; c.id = "myCompound"; t.addCompound(c); } TargetedExperiment t2(t); TEST_TRUE(t2 == t) } END_SECTION START_SECTION((bool operator==(const TargetedExperiment &rhs) const )) { TargetedExperiment t; ReactionMonitoringTransition tr; t.addTransition(tr); { TargetedExperiment::Peptide p; p.id = "myPep"; t.addPeptide(p); } { TargetedExperiment::Protein p; p.id = "myProtein"; t.addProtein(p); } { TargetedExperiment::Compound c; c.id = "myCompound"; t.addCompound(c); } TargetedExperiment t2; t2 = t; TEST_TRUE(t2 == t) } END_SECTION START_SECTION((void setCVs(const std::vector< CV > &cvs))) { // TODO } END_SECTION START_SECTION((const std::vector<CV>& getCVs() const )) { // TODO } END_SECTION START_SECTION((void addCV(const CV &cv))) { // TODO } END_SECTION START_SECTION(( void setContacts(const std::vector< CVTermList > &contacts))) { // TODO } END_SECTION START_SECTION(const std::vector<CVTermList>& getContacts() const) { // TODO } END_SECTION START_SECTION( void addContact(const CVTermList &contact)) { // TODO } END_SECTION START_SECTION( void setPublications(const std::vector< CVTermList > &publications)) { // TODO } END_SECTION START_SECTION( const std::vector<CVTermList>& getPublications() const) { // TODO } END_SECTION START_SECTION(void addPublication(const CVTermList &publication)) { // TODO } END_SECTION START_SECTION( void setInstruments(const std::vector< CVTermList > &instruments)) { // TODO } END_SECTION START_SECTION(const std::vector<CVTermList>& getInstruments() const) { // TODO } END_SECTION START_SECTION(void addInstrument(const CVTermList &instrument)) { // TODO } END_SECTION START_SECTION((void setSoftware(const std::vector< Software > &software))) { // TODO } END_SECTION START_SECTION((const std::vector<Software>& getSoftware() const )) { // TODO } END_SECTION START_SECTION((void addSoftware(const Software &software))) { // TODO } END_SECTION START_SECTION((void setProteins(const std::vector< Protein > &proteins))) { TargetedExperiment t; TargetedExperiment::Protein p; std::vector<TargetedExperiment::Protein> proteins; proteins.push_back(p); t.setProteins(proteins); TEST_EQUAL(t.getProteins().size(), 1) } END_SECTION START_SECTION((const std::vector<Protein>& getProteins() const )) { TEST_EQUAL(te.getProteins().size(), 0) } END_SECTION START_SECTION((bool hasProtein(const String & ref) const)) { TargetedExperiment t; TargetedExperiment::Protein p; p.id = "myProtein"; t.addProtein(p); TEST_EQUAL(t.hasProtein("myProtein"), true) } END_SECTION START_SECTION((void addProtein(const Protein &protein))) { TargetedExperiment t; TargetedExperiment::Protein p; t.addProtein(p); TEST_EQUAL(t.getProteins().size(), 1) } END_SECTION START_SECTION((void setCompounds(const std::vector< Compound > &rhs))) { TargetedExperiment t; TargetedExperiment::Compound c; std::vector<TargetedExperiment::Compound> compounds; compounds.push_back(c); t.setCompounds(compounds); TEST_EQUAL(t.getCompounds().size(), 1) } END_SECTION START_SECTION((const std::vector<Compound>& getCompounds() const )) { TEST_EQUAL(te.getCompounds().size(), 0) } END_SECTION START_SECTION((bool hasCompound(const String & ref) const)) { TargetedExperiment t; TargetedExperiment::Compound c; c.id = "myCompound"; t.addCompound(c); TEST_EQUAL(t.hasCompound("myCompound"), true) } END_SECTION START_SECTION((void addCompound(const Compound &rhs))) { TargetedExperiment t; TargetedExperiment::Compound c; t.addCompound(c); TEST_EQUAL(t.getCompounds().size(), 1) } END_SECTION START_SECTION((void setPeptides(const std::vector< Peptide > &rhs))) { TargetedExperiment t; TargetedExperiment::Peptide p; std::vector<TargetedExperiment::Peptide> peptides; peptides.push_back(p); t.setPeptides(peptides); TEST_EQUAL(t.getPeptides().size(), 1) } END_SECTION START_SECTION((const std::vector<Peptide>& getPeptides() const )) { TEST_EQUAL(te.getPeptides().size(), 0) } END_SECTION START_SECTION((void addPeptide(const Peptide &rhs))) { TargetedExperiment t; TargetedExperiment::Peptide p; t.addPeptide(p); TEST_EQUAL(t.getPeptides().size(), 1) } END_SECTION START_SECTION((bool hasPeptide(const String & ref) const)) { TargetedExperiment t; TargetedExperiment::Peptide p; p.id = "myPep"; t.addPeptide(p); TEST_EQUAL(t.hasPeptide("myPep"), true) } END_SECTION START_SECTION((void setTransitions(const std::vector< ReactionMonitoringTransition > &transitions))) { TargetedExperiment t; ReactionMonitoringTransition tr; std::vector<ReactionMonitoringTransition> transitions; transitions.push_back(tr); t.setTransitions(transitions); TEST_EQUAL(t.getTransitions().size(), 1) } END_SECTION START_SECTION((const std::vector<ReactionMonitoringTransition>& getTransitions() const )) { TEST_EQUAL(te.getTransitions().size(), 0) } END_SECTION START_SECTION((void addTransition(const ReactionMonitoringTransition &transition))) { TargetedExperiment t; ReactionMonitoringTransition tr; t.addTransition(tr); TEST_EQUAL(t.getTransitions().size(), 1) } END_SECTION START_SECTION((TargetedExperiment& operator=(const TargetedExperiment &rhs))) { TargetedExperiment t; ReactionMonitoringTransition tr; t.addTransition(tr); { TargetedExperiment::Peptide p; p.id = "myPep"; t.addPeptide(p); } { TargetedExperiment::Protein p; p.id = "myProtein"; t.addProtein(p); } { TargetedExperiment::Compound c; c.id = "myCompound"; t.addCompound(c); } TargetedExperiment t2; t2 = t; TEST_TRUE(t2 == t) } END_SECTION START_SECTION( bool TargetedExperiment::containsInvalidReferences() ) { // wrong references { TargetedExperiment tr; TEST_EQUAL(tr.containsInvalidReferences(), false) OpenMS::TargetedExperiment::Peptide peptide; peptide.id = "peptide1"; peptide.protein_refs.push_back("protein1"); tr.addPeptide(peptide); // now should be invalid due to a missing protein TEST_EQUAL(tr.containsInvalidReferences(), true) OpenMS::TargetedExperiment::Protein protein; protein.id = "protein1"; tr.addProtein(protein); // now should be valid again TEST_EQUAL(tr.containsInvalidReferences(), false) OpenMS::ReactionMonitoringTransition t; t.setNativeID("tr1"); t.setPeptideRef("peptide1"); tr.addTransition(t); TEST_EQUAL(tr.containsInvalidReferences(), false) OpenMS::ReactionMonitoringTransition t2; t2.setNativeID("tr2"); t2.setCompoundRef("compound1"); tr.addTransition(t2); TEST_EQUAL(tr.containsInvalidReferences(), true) OpenMS::TargetedExperiment::Compound comp; comp.id = "compound1"; tr.addCompound(comp); // now should be valid again TEST_EQUAL(tr.containsInvalidReferences(), false) } // duplications { TargetedExperiment tr; TEST_EQUAL(tr.containsInvalidReferences(), false) OpenMS::TargetedExperiment::Peptide peptide; peptide.id = "peptide1"; tr.addPeptide(peptide); TEST_EQUAL(tr.containsInvalidReferences(), false) tr.addPeptide(peptide); TEST_EQUAL(tr.containsInvalidReferences(), true) } { TargetedExperiment tr; TEST_EQUAL(tr.containsInvalidReferences(), false) OpenMS::ReactionMonitoringTransition t; t.setNativeID("tr1"); tr.addTransition(t); TEST_EQUAL(tr.containsInvalidReferences(), false) tr.addTransition(t); TEST_EQUAL(tr.containsInvalidReferences(), true) } { TargetedExperiment tr; TEST_EQUAL(tr.containsInvalidReferences(), false) OpenMS::TargetedExperiment::Protein protein; protein.id = "protein1"; tr.addProtein(protein); TEST_EQUAL(tr.containsInvalidReferences(), false) tr.addProtein(protein); TEST_EQUAL(tr.containsInvalidReferences(), true) } } END_SECTION START_SECTION(OpenMS::AASequence getAASequence(const OpenMS::TargetedExperiment::Peptide &peptide)) { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification modification; modification.avg_mass_delta = 79.9799; modification.location = 2; modification.mono_mass_delta = 79.966331; peptide.mods.push_back(modification); OpenMS::AASequence aas = TargetedExperimentHelper::getAASequence(peptide); OpenMS::String modified_sequence = "TES(Phospho)TPEPTIDE"; TEST_EQUAL(aas.toUnmodifiedString(),peptide.sequence) //TEST_EQUAL(aas.toString(),modified_sequence) OpenMS::TargetedExperiment::Peptide peptide2; peptide2.sequence = "TESTPEPTIDER"; OpenMS::TargetedExperiment::Peptide::Modification modification2; modification2.avg_mass_delta = 9.9296; modification2.location = 11; modification2.mono_mass_delta = 10.008269; peptide2.mods.push_back(modification2); OpenMS::AASequence aas2 = TargetedExperimentHelper::getAASequence(peptide2); OpenMS::String modified_sequence2 = "TESTPEPTIDER(Label:13C(6)15N(4))"; TEST_EQUAL(aas2.toUnmodifiedString(),peptide2.sequence) OpenMS::TargetedExperiment::Peptide peptide3; peptide3.sequence = "TESTMPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification modification3; modification3.avg_mass_delta = 15.9994; modification3.location = 4; modification3.mono_mass_delta = 15.994915; peptide3.mods.push_back(modification3); OpenMS::AASequence aas3 = TargetedExperimentHelper::getAASequence(peptide3); OpenMS::String modified_sequence3 = "TESTM(Oxidation)PEPTIDE"; TEST_EQUAL(aas3.toUnmodifiedString(),peptide3.sequence) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TargetedSpectraExtractor_test.cpp
.cpp
54,426
1,245
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $ // $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/TargetedSpectraExtractor.h> #include <OpenMS/ANALYSIS/OPENSWATH/TransitionTSVFile.h> #include <OpenMS/FORMAT/MSPGenericFile.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/FORMAT/TraMLFile.h> /////////////////////////// using namespace OpenMS; using namespace std; vector<MSSpectrum>::const_iterator findSpectrumByName(const vector<MSSpectrum>& spectra, const String& name) { vector<MSSpectrum>::const_iterator it; it = std::find_if(spectra.cbegin(), spectra.cend(), [&name] (const MSSpectrum& s) { return s.getName() == name; }); if (it == spectra.cend()) { throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, name); } return it; } namespace std { std::ostream& operator<<(ostream& os, const std::vector<OpenMS::String> string_list) { os << "["; std::string separator = ""; for (const auto& string_item : string_list) { os << separator << string_item; separator = ", "; } os << "])"; return os; } }// namespace std START_TEST(TargetedSpectraExtractor, "$Id$") ///////////////////////////////////////////////////////////// // Raw spectrum data acquired in DDA mode (i.e., product ion full spectrum scan) // measured on a QTRAP 5500 corresponding to C-Aconitate // taken from E. coli grown on glucose M9 during steady-state // for flux analysis. const vector<double> mz = { 61.92, 68.88, 71.4, 79.56, 84.6, 84.72, 84.84, 84.96, 85.08, 85.2, 85.32, 85.44, 85.68, 85.8, 85.92, 86.04, 86.16, 86.28, 86.4, 87.72, 87.96, 88.08, 90.36, 94.44, 99.84, 100.8, 101.04, 101.88, 102, 102.96, 110.16, 110.88, 111, 111.12, 111.24, 111.84, 111.96, 112.08, 112.2, 112.32, 112.44, 112.56, 112.68, 114, 128.16, 128.4, 128.88, 129, 129.12, 129.84, 129.96, 130.08, 130.2, 130.32, 130.44, 130.56, 132.12, 138, 139.08, 140.16, 144.12, 146.04, 146.16, 156, 156.12, 156.36, 173.76, 174, 174.12, 174.24, 174.36, 174.6, 175.08 }; const vector<double> intensity = { 6705.41660838088, 1676.35415209522, 1676.35415209522, 1676.35415209522, 3352.70830419044, 5029.06245628566, 8381.7707604761, 53643.332867047, 51966.9787149518, 6705.41660838088, 8381.7707604761, 1676.35415209522, 11734.4790646665, 25145.3122814283, 68730.520235904, 112315.72819038, 6705.41660838088, 6705.41660838088, 3352.70830419044, 1676.35415209522, 1676.35415209522, 1676.35415209522, 3352.70830419044, 1676.35415209522, 1676.35415209522, 1676.35415209522, 5029.06245628566, 3352.70830419044, 3352.70830419044, 3352.70830419044, 1676.35415209522, 5029.06245628566, 3352.70830419044, 5029.06245628566, 3352.70830419044, 5029.06245628566, 18439.8956730474, 20116.2498251426, 5029.06245628566, 1676.35415209522, 1676.35415209522, 3352.70830419044, 3352.70830419044, 3352.70830419044, 6705.41660838088, 1676.35415209522, 3352.70830419044, 3352.70830419044, 6705.41660838088, 5029.06245628566, 10058.1249125713, 31850.7288898092, 10058.1249125713, 1676.35415209522, 1676.35415209522, 3352.70830419044, 1676.35415209522, 1676.35415209522, 1676.35415209522, 3352.70830419044, 1676.35415209522, 3352.70830419044, 1676.35415209522, 1676.35415209522, 5029.06245628566, 1676.35415209522, 1676.35415209522, 1676.35415209522, 6705.41660838088, 11734.4790646665, 6705.41660838088, 1676.35415209522, 1676.35415209522 }; MSSpectrum s; for (Size i = 0; i != mz.size(); ++i) { s.push_back(Peak1D(mz[i],intensity[i])); } const MSSpectrum spectrum = s; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TargetedSpectraExtractor* ptr = nullptr; TargetedSpectraExtractor* null_ptr = nullptr; const String experiment_path = OPENMS_GET_TEST_DATA_PATH("TargetedSpectraExtractor_13C1_spectra0to100.mzML"); const String target_list_path = OPENMS_GET_TEST_DATA_PATH("TargetedSpectraExtractor_13CFlux_TraML.csv"); MzMLFile mzml; MSExperiment experiment; TransitionTSVFile tsv_reader; TargetedExperiment targeted_exp; mzml.load(experiment_path, experiment); Param tsv_params = tsv_reader.getParameters(); tsv_params.setValue("retentionTimeInterpretation", "minutes"); tsv_reader.setParameters(tsv_params); tsv_reader.convertTSVToTargetedExperiment(target_list_path.c_str(), FileTypes::CSV, targeted_exp); START_SECTION(TargetedSpectraExtractor()) { ptr = new TargetedSpectraExtractor(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~TargetedSpectraExtractor()) { delete ptr; } END_SECTION START_SECTION(const Param& getParameters() const) { TargetedSpectraExtractor tse; const Param& params = tse.getParameters(); TEST_EQUAL(params.getValue("rt_window"), 30.0) TEST_EQUAL(params.getValue("min_select_score"), 0.7) TEST_EQUAL(params.getValue("mz_tolerance"), 0.1) TEST_EQUAL(params.getValue("mz_unit_is_Da"), "true") TEST_EQUAL(params.getValue("SavitzkyGolayFilter:frame_length"), 15) TEST_EQUAL(params.getValue("SavitzkyGolayFilter:polynomial_order"), 3) TEST_EQUAL(params.getValue("GaussFilter:gaussian_width"), 0.2) TEST_EQUAL(params.getValue("use_gauss"), "true") TEST_EQUAL(params.getValue("PeakPickerHiRes:signal_to_noise"), 1.0) TEST_EQUAL(params.getValue("peak_height_min"), 0.0) TEST_EQUAL(params.getValue("peak_height_max"), std::numeric_limits<double>::max()) TEST_EQUAL(params.getValue("fwhm_threshold"), 0.0) TEST_EQUAL(params.getValue("tic_weight"), 1.0) TEST_EQUAL(params.getValue("fwhm_weight"), 1.0) TEST_EQUAL(params.getValue("snr_weight"), 1.0) TEST_EQUAL(params.getValue("top_matches_to_report"), 5) TEST_EQUAL(params.getValue("min_match_score"), 0.8) } END_SECTION START_SECTION(void getDefaultParameters(Param& params) const) { TargetedSpectraExtractor tse; Param params; tse.getDefaultParameters(params); TEST_EQUAL(params.getValue("rt_window"), 30.0) TEST_EQUAL(params.getValue("min_select_score"), 0.7) TEST_EQUAL(params.getValue("mz_tolerance"), 0.1) TEST_EQUAL(params.getValue("mz_unit_is_Da"), "true") TEST_EQUAL(params.getValue("use_gauss"), "true") TEST_EQUAL(params.getValue("peak_height_min"), 0.0) TEST_EQUAL(params.getValue("peak_height_max"), std::numeric_limits<double>::max()) TEST_EQUAL(params.getValue("fwhm_threshold"), 0.0) TEST_EQUAL(params.getValue("tic_weight"), 1.0) TEST_EQUAL(params.getValue("fwhm_weight"), 1.0) TEST_EQUAL(params.getValue("snr_weight"), 1.0) TEST_EQUAL(params.getValue("top_matches_to_report"), 5) TEST_EQUAL(params.getValue("min_match_score"), 0.8) } END_SECTION START_SECTION(void annotateSpectra( const std::vector<MSSpectrum>& spectra, const TargetedExperiment& targeted_exp, std::vector<MSSpectrum>& annotated_spectra, FeatureMap& features, const bool compute_features = true ) const) { TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("GaussFilter:gaussian_width", 0.25); params.setValue("peak_height_min", 15000.0); params.setValue("peak_height_max", 110000.0); params.setValue("fwhm_threshold", 0.23); tse.setParameters(params); const vector<MSSpectrum>& spectra = experiment.getSpectra(); vector<MSSpectrum> annotated_spectra; FeatureMap features; tse.annotateSpectra(spectra, targeted_exp, annotated_spectra, features); TEST_EQUAL(annotated_spectra.size(), 30) TEST_EQUAL(annotated_spectra.size(), features.size()) TEST_EQUAL(annotated_spectra[0].getName(), "met-L.met-L_m0-0") TEST_EQUAL(annotated_spectra[0].size(), 121) TEST_EQUAL(annotated_spectra[4].getName(), "met-L.met-L_m1-0") TEST_EQUAL(annotated_spectra[4].size(), 135) TEST_EQUAL(annotated_spectra[8].getName(), "asp-L.asp-L_m0-0") TEST_EQUAL(annotated_spectra[8].size(), 55) TEST_EQUAL(annotated_spectra[12].getName(), "asp-L.asp-L_m1-0") TEST_EQUAL(annotated_spectra[12].size(), 389) TEST_EQUAL(annotated_spectra[16].getName(), "asp-L.asp-L_m2-1") TEST_EQUAL(annotated_spectra[16].size(), 143) TEST_EQUAL(annotated_spectra[20].getName(), "glu-L.glu-L_m5-5") TEST_EQUAL(annotated_spectra[20].size(), 82) TEST_EQUAL(annotated_spectra[24].getName(), "glu-L.glu-L_m2-2") TEST_EQUAL(annotated_spectra[24].size(), 94) TEST_EQUAL(annotated_spectra[29].getName(), "skm.skm_m4-4") TEST_EQUAL(annotated_spectra[29].size(), 552) TEST_EQUAL(features[0].getMetaValue("transition_name"), "met-L.met-L_m0-0") TEST_REAL_SIMILAR(features[0].getRT(), 80.22100000002) TEST_REAL_SIMILAR(features[0].getMZ(), 148.052001953125) TEST_EQUAL(features[4].getMetaValue("transition_name"), "met-L.met-L_m1-0") TEST_REAL_SIMILAR(features[4].getRT(), 87.927) TEST_REAL_SIMILAR(features[4].getMZ(), 149.054992675781) TEST_EQUAL(features[8].getMetaValue("transition_name"), "asp-L.asp-L_m0-0") TEST_REAL_SIMILAR(features[8].getRT(), 126.37699999998) TEST_REAL_SIMILAR(features[8].getMZ(), 132.029998779297) TEST_EQUAL(features[12].getMetaValue("transition_name"), "asp-L.asp-L_m1-0") TEST_REAL_SIMILAR(features[12].getRT(), 131.73100000002) TEST_REAL_SIMILAR(features[12].getMZ(), 133.033004760742) TEST_EQUAL(features[16].getMetaValue("transition_name"), "asp-L.asp-L_m2-1") TEST_REAL_SIMILAR(features[16].getRT(), 138.29599999998) TEST_REAL_SIMILAR(features[16].getMZ(), 134.035995483398) TEST_EQUAL(features[20].getMetaValue("transition_name"), "glu-L.glu-L_m5-5") TEST_REAL_SIMILAR(features[20].getRT(), 141.70399999998) TEST_REAL_SIMILAR(features[20].getMZ(), 151.061996459961) TEST_EQUAL(features[24].getMetaValue("transition_name"), "glu-L.glu-L_m2-2") TEST_REAL_SIMILAR(features[24].getRT(), 148.473) TEST_REAL_SIMILAR(features[24].getMZ(), 148.052001953125) TEST_EQUAL(features[29].getMetaValue("transition_name"), "skm.skm_m4-4") TEST_REAL_SIMILAR(features[29].getRT(), 166.95400000002) TEST_REAL_SIMILAR(features[29].getMZ(), 177.057998657227) } END_SECTION START_SECTION(void annotateSpectra( const std::vector<MSSpectrum>& spectra, const TargetedExperiment& targeted_exp, std::vector<MSSpectrum>& annotated_spectra ) const) { TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("GaussFilter:gaussian_width", 0.25); params.setValue("peak_height_min", 15000.0); params.setValue("peak_height_max", 110000.0); params.setValue("fwhm_threshold", 0.23); tse.setParameters(params); const vector<MSSpectrum>& spectra = experiment.getSpectra(); vector<MSSpectrum> annotated_spectra; tse.annotateSpectra(spectra, targeted_exp, annotated_spectra); TEST_EQUAL(annotated_spectra.size(), 30) TEST_EQUAL(annotated_spectra[0].getName(), "met-L.met-L_m0-0") TEST_EQUAL(annotated_spectra[0].size(), 121) TEST_EQUAL(annotated_spectra[4].getName(), "met-L.met-L_m1-0") TEST_EQUAL(annotated_spectra[4].size(), 135) TEST_EQUAL(annotated_spectra[20].getName(), "glu-L.glu-L_m5-5") TEST_EQUAL(annotated_spectra[20].size(), 82) TEST_EQUAL(annotated_spectra[24].getName(), "glu-L.glu-L_m2-2") TEST_EQUAL(annotated_spectra[24].size(), 94) TEST_EQUAL(annotated_spectra[29].getName(), "skm.skm_m4-4") TEST_EQUAL(annotated_spectra[29].size(), 552) } END_SECTION START_SECTION(void pickSpectrum(const MSSpectrum& spectrum, MSSpectrum& picked_spectrum) const) { MSSpectrum picked_spectrum; TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("GaussFilter:gaussian_width", 0.25); params.setValue("peak_height_min", 0.0); params.setValue("peak_height_max", 200000.0); params.setValue("fwhm_threshold", 0.0); tse.setParameters(params); tse.pickSpectrum(spectrum, picked_spectrum); TEST_NOT_EQUAL(spectrum.size(), picked_spectrum.size()) TEST_EQUAL(picked_spectrum.size(), 6) MSSpectrum::Iterator it = picked_spectrum.begin(); TEST_REAL_SIMILAR(it->getMZ(), 85.014) TEST_REAL_SIMILAR(it->getIntensity(), 60754.7) ++it; TEST_REAL_SIMILAR(it->getMZ(), 86.0196) TEST_REAL_SIMILAR(it->getIntensity(), 116036.0) ++it; TEST_REAL_SIMILAR(it->getMZ(), 112.033) TEST_REAL_SIMILAR(it->getIntensity(), 21941.9) ++it; TEST_REAL_SIMILAR(it->getMZ(), 129.396) TEST_REAL_SIMILAR(it->getIntensity(), 10575.5) ++it; TEST_REAL_SIMILAR(it->getMZ(), 130.081) TEST_REAL_SIMILAR(it->getIntensity(), 31838.1) ++it; TEST_REAL_SIMILAR(it->getMZ(), 174.24) TEST_REAL_SIMILAR(it->getIntensity(), 11731.3) params.setValue("peak_height_min", 15000.0); params.setValue("peak_height_max", 110000.0); tse.setParameters(params); tse.pickSpectrum(spectrum, picked_spectrum); // With the new filters on peaks' heights, less peaks get picked. TEST_EQUAL(picked_spectrum.size(), 3) it = picked_spectrum.begin(); TEST_REAL_SIMILAR(it->getMZ(), 85.014) TEST_REAL_SIMILAR(it->getIntensity(), 60754.7) ++it; TEST_REAL_SIMILAR(it->getMZ(), 112.033) TEST_REAL_SIMILAR(it->getIntensity(), 21941.9) ++it; TEST_REAL_SIMILAR(it->getMZ(), 130.081) TEST_REAL_SIMILAR(it->getIntensity(), 31838.1) params.setValue("fwhm_threshold", 0.23); tse.setParameters(params); tse.pickSpectrum(spectrum, picked_spectrum); // Filtering also on fwhm, even less peaks get picked. TEST_EQUAL(picked_spectrum.size(), 2) it = picked_spectrum.begin(); TEST_REAL_SIMILAR(it->getMZ(), 85.014) TEST_REAL_SIMILAR(it->getIntensity(), 60754.7) ++it; TEST_REAL_SIMILAR(it->getMZ(), 112.033) TEST_REAL_SIMILAR(it->getIntensity(), 21941.9) MSSpectrum unordered; unordered.emplace_back(Peak1D(10.0, 100.0)); unordered.emplace_back(Peak1D(9.0, 100.0)); TEST_EXCEPTION(Exception::IllegalArgument, tse.pickSpectrum(unordered, picked_spectrum)); } END_SECTION START_SECTION(void scoreSpectra( const std::vector<MSSpectrum>& annotated_spectra, const std::vector<MSSpectrum>& picked_spectra, FeatureMap& features, std::vector<MSSpectrum>& scored_spectra, const bool compute_features = true ) const) { TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("GaussFilter:gaussian_width", 0.25); params.setValue("peak_height_min", 15000.0); params.setValue("peak_height_max", 110000.0); params.setValue("fwhm_threshold", 0.23); tse.setParameters(params); vector<MSSpectrum> annotated_spectra; FeatureMap features; const vector<MSSpectrum>& spectra = experiment.getSpectra(); tse.annotateSpectra(spectra, targeted_exp, annotated_spectra, features); vector<MSSpectrum> picked_spectra(annotated_spectra.size()); for (Size i = 0; i < annotated_spectra.size(); ++i) { tse.pickSpectrum(annotated_spectra[i], picked_spectra[i]); } for (Int i = annotated_spectra.size() - 1; i >= 0; --i) { if (picked_spectra[i].empty()) { annotated_spectra.erase(annotated_spectra.begin() + i); picked_spectra.erase(picked_spectra.begin() + i); features.erase(features.begin() + i); } } TEST_EQUAL(annotated_spectra.size(), 20) TEST_EQUAL(annotated_spectra.size(), features.size()) TEST_EQUAL(picked_spectra.size(), features.size()) vector<MSSpectrum> scored_spectra; tse.scoreSpectra(annotated_spectra, picked_spectra, features, scored_spectra); TEST_EQUAL(scored_spectra.size(), 20) TEST_EQUAL(scored_spectra.size(), annotated_spectra.size()) TEST_EQUAL(scored_spectra.size(), features.size()) TEST_EQUAL(scored_spectra[0].getName(), "met-L.met-L_m0-0") TEST_REAL_SIMILAR(scored_spectra[0].getFloatDataArrays()[1][0], 15.2046270370483) // score TEST_REAL_SIMILAR(scored_spectra[0].getFloatDataArrays()[2][0], 5.3508939743042) // total tic TEST_REAL_SIMILAR(scored_spectra[0].getFloatDataArrays()[3][0], 3.96267318725586) // inverse average fwhm TEST_REAL_SIMILAR(scored_spectra[0].getFloatDataArrays()[4][0], 5.89106035232544) // average snr TEST_EQUAL(scored_spectra[4].getName(), "asp-L.asp-L_m1-0") TEST_REAL_SIMILAR(scored_spectra[4].getFloatDataArrays()[1][0], 10.8893) TEST_REAL_SIMILAR(scored_spectra[4].getFloatDataArrays()[2][0], 6.49946) TEST_REAL_SIMILAR(scored_spectra[4].getFloatDataArrays()[3][0], 2.65215) TEST_REAL_SIMILAR(scored_spectra[4].getFloatDataArrays()[4][0], 1.73772) TEST_EQUAL(scored_spectra[8].getName(), "asp-L.asp-L_m2-1") TEST_REAL_SIMILAR(scored_spectra[8].getFloatDataArrays()[1][0], 16.1929) TEST_REAL_SIMILAR(scored_spectra[8].getFloatDataArrays()[2][0], 5.52142) TEST_REAL_SIMILAR(scored_spectra[8].getFloatDataArrays()[3][0], 3.44492) TEST_REAL_SIMILAR(scored_spectra[8].getFloatDataArrays()[4][0], 7.22662) TEST_EQUAL(scored_spectra[11].getName(), "asp-L.asp-L_m2-2") TEST_REAL_SIMILAR(scored_spectra[11].getFloatDataArrays()[1][0], 17.4552) TEST_REAL_SIMILAR(scored_spectra[11].getFloatDataArrays()[2][0], 5.48532) TEST_REAL_SIMILAR(scored_spectra[11].getFloatDataArrays()[3][0], 3.78555) TEST_REAL_SIMILAR(scored_spectra[11].getFloatDataArrays()[4][0], 8.18436) TEST_EQUAL(scored_spectra[15].getName(), "glu-L.glu-L_m1-1") TEST_REAL_SIMILAR(scored_spectra[15].getFloatDataArrays()[1][0], 13.5799) TEST_REAL_SIMILAR(scored_spectra[15].getFloatDataArrays()[2][0], 5.49089) TEST_REAL_SIMILAR(scored_spectra[15].getFloatDataArrays()[3][0], 3.53584) TEST_REAL_SIMILAR(scored_spectra[15].getFloatDataArrays()[4][0], 4.55314) TEST_EQUAL(scored_spectra[19].getName(), "skm.skm_m4-4") TEST_REAL_SIMILAR(scored_spectra[19].getFloatDataArrays()[1][0], 10.5746) TEST_REAL_SIMILAR(scored_spectra[19].getFloatDataArrays()[2][0], 6.60354) TEST_REAL_SIMILAR(scored_spectra[19].getFloatDataArrays()[3][0], 2.02869) TEST_REAL_SIMILAR(scored_spectra[19].getFloatDataArrays()[4][0], 1.94236) TEST_EQUAL(features[0].getMetaValue("transition_name"), "met-L.met-L_m0-0") TEST_REAL_SIMILAR(features[0].getIntensity(), 15.2046270370483) // score TEST_REAL_SIMILAR(features[0].getMetaValue("log10_total_tic"), 5.3508939743042) // total tic TEST_REAL_SIMILAR(features[0].getMetaValue("inverse_avgFWHM"), 3.96267318725586) // inverse average fwhm TEST_REAL_SIMILAR(features[0].getMetaValue("avgSNR"), 5.89106035232544) // average snr TEST_REAL_SIMILAR(features[0].getMetaValue("avgFWHM"), 0.252354895075162) // average fwhm TEST_EQUAL(features[4].getMetaValue("transition_name"), "asp-L.asp-L_m1-0") TEST_REAL_SIMILAR(features[4].getIntensity(), 10.8893) TEST_REAL_SIMILAR(features[4].getMetaValue("log10_total_tic"), 6.49945796336373) TEST_REAL_SIMILAR(features[4].getMetaValue("inverse_avgFWHM"), 2.65214624318674) TEST_REAL_SIMILAR(features[4].getMetaValue("avgSNR"), 1.73772000291411) TEST_REAL_SIMILAR(features[4].getMetaValue("avgFWHM"), 0.377053114084097) TEST_EQUAL(features[8].getMetaValue("transition_name"), "asp-L.asp-L_m2-1") TEST_REAL_SIMILAR(features[8].getIntensity(), 16.1929) TEST_REAL_SIMILAR(features[8].getMetaValue("log10_total_tic"), 5.52141560620828) TEST_REAL_SIMILAR(features[8].getMetaValue("inverse_avgFWHM"), 3.44491858720322) TEST_REAL_SIMILAR(features[8].getMetaValue("avgSNR"), 7.22661551261844) TEST_REAL_SIMILAR(features[8].getMetaValue("avgFWHM"), 0.290282621979713) TEST_EQUAL(features[11].getMetaValue("transition_name"), "asp-L.asp-L_m2-2") TEST_REAL_SIMILAR(features[11].getIntensity(), 17.4552) TEST_REAL_SIMILAR(features[11].getMetaValue("log10_total_tic"), 5.48531541983726) TEST_REAL_SIMILAR(features[11].getMetaValue("inverse_avgFWHM"), 3.78554915619634) TEST_REAL_SIMILAR(features[11].getMetaValue("avgSNR"), 8.18435900228459) TEST_REAL_SIMILAR(features[11].getMetaValue("avgFWHM"), 0.264162465929985) TEST_EQUAL(features[15].getMetaValue("transition_name"), "glu-L.glu-L_m1-1") TEST_REAL_SIMILAR(features[15].getIntensity(), 13.5799) TEST_REAL_SIMILAR(features[15].getMetaValue("log10_total_tic"), 5.49089446225569) TEST_REAL_SIMILAR(features[15].getMetaValue("inverse_avgFWHM"), 3.53583924309525) TEST_REAL_SIMILAR(features[15].getMetaValue("avgSNR"), 4.55314284068408) TEST_REAL_SIMILAR(features[15].getMetaValue("avgFWHM"), 0.282818287611008) TEST_EQUAL(features[19].getMetaValue("transition_name"), "skm.skm_m4-4") TEST_REAL_SIMILAR(features[19].getIntensity(), 10.5746) TEST_REAL_SIMILAR(features[19].getMetaValue("log10_total_tic"), 6.60354130105922) TEST_REAL_SIMILAR(features[19].getMetaValue("inverse_avgFWHM"), 2.02868912178847) TEST_REAL_SIMILAR(features[19].getMetaValue("avgSNR"), 1.94235549504842) TEST_REAL_SIMILAR(features[19].getMetaValue("avgFWHM"), 0.492929147822516) features.pop_back(); TEST_EXCEPTION(Exception::InvalidSize, tse.scoreSpectra(annotated_spectra, picked_spectra, features, scored_spectra)); } END_SECTION START_SECTION(void scoreSpectra( const std::vector<MSSpectrum>& annotated_spectra, const std::vector<MSSpectrum>& picked_spectra, std::vector<MSSpectrum>& scored_spectra ) const) { TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("GaussFilter:gaussian_width", 0.25); params.setValue("peak_height_min", 15000.0); params.setValue("peak_height_max", 110000.0); params.setValue("fwhm_threshold", 0.23); tse.setParameters(params); vector<MSSpectrum> annotated_spectra; const vector<MSSpectrum>& spectra = experiment.getSpectra(); tse.annotateSpectra(spectra, targeted_exp, annotated_spectra); vector<MSSpectrum> picked_spectra(annotated_spectra.size()); for (Size i = 0; i < annotated_spectra.size(); ++i) { tse.pickSpectrum(annotated_spectra[i], picked_spectra[i]); } for (Int i = annotated_spectra.size() - 1; i >= 0; --i) { if (picked_spectra[i].empty()) { annotated_spectra.erase(annotated_spectra.begin() + i); picked_spectra.erase(picked_spectra.begin() + i); } } TEST_EQUAL(annotated_spectra.size(), 20) TEST_EQUAL(annotated_spectra.size(), picked_spectra.size()) vector<MSSpectrum> scored_spectra; tse.scoreSpectra(annotated_spectra, picked_spectra, scored_spectra); TEST_EQUAL(scored_spectra.size(), 20) TEST_EQUAL(scored_spectra.size(), annotated_spectra.size()) TEST_EQUAL(scored_spectra[0].getName(), "met-L.met-L_m0-0") TEST_REAL_SIMILAR(scored_spectra[0].getFloatDataArrays()[1][0], 15.2046270370483) // score TEST_REAL_SIMILAR(scored_spectra[0].getFloatDataArrays()[2][0], 5.3508939743042) // total tic TEST_REAL_SIMILAR(scored_spectra[0].getFloatDataArrays()[3][0], 3.96267318725586) // inverse average fwhm TEST_REAL_SIMILAR(scored_spectra[0].getFloatDataArrays()[4][0], 5.89106035232544) // average snr TEST_EQUAL(scored_spectra[4].getName(), "asp-L.asp-L_m1-0") TEST_REAL_SIMILAR(scored_spectra[4].getFloatDataArrays()[1][0], 10.8893) TEST_REAL_SIMILAR(scored_spectra[4].getFloatDataArrays()[2][0], 6.49946) TEST_REAL_SIMILAR(scored_spectra[4].getFloatDataArrays()[3][0], 2.65215) TEST_REAL_SIMILAR(scored_spectra[4].getFloatDataArrays()[4][0], 1.73772) TEST_EQUAL(scored_spectra[8].getName(), "asp-L.asp-L_m2-1") TEST_REAL_SIMILAR(scored_spectra[8].getFloatDataArrays()[1][0], 16.1929) TEST_REAL_SIMILAR(scored_spectra[8].getFloatDataArrays()[2][0], 5.52142) TEST_REAL_SIMILAR(scored_spectra[8].getFloatDataArrays()[3][0], 3.44492) TEST_REAL_SIMILAR(scored_spectra[8].getFloatDataArrays()[4][0], 7.22662) TEST_EQUAL(scored_spectra[11].getName(), "asp-L.asp-L_m2-2") TEST_REAL_SIMILAR(scored_spectra[11].getFloatDataArrays()[1][0], 17.4552) TEST_REAL_SIMILAR(scored_spectra[11].getFloatDataArrays()[2][0], 5.48532) TEST_REAL_SIMILAR(scored_spectra[11].getFloatDataArrays()[3][0], 3.78555) TEST_REAL_SIMILAR(scored_spectra[11].getFloatDataArrays()[4][0], 8.18436) TEST_EQUAL(scored_spectra[15].getName(), "glu-L.glu-L_m1-1") TEST_REAL_SIMILAR(scored_spectra[15].getFloatDataArrays()[1][0], 13.5799) TEST_REAL_SIMILAR(scored_spectra[15].getFloatDataArrays()[2][0], 5.49089) TEST_REAL_SIMILAR(scored_spectra[15].getFloatDataArrays()[3][0], 3.53584) TEST_REAL_SIMILAR(scored_spectra[15].getFloatDataArrays()[4][0], 4.55314) TEST_EQUAL(scored_spectra[19].getName(), "skm.skm_m4-4") TEST_REAL_SIMILAR(scored_spectra[19].getFloatDataArrays()[1][0], 10.5746) TEST_REAL_SIMILAR(scored_spectra[19].getFloatDataArrays()[2][0], 6.60354) TEST_REAL_SIMILAR(scored_spectra[19].getFloatDataArrays()[3][0], 2.02869) TEST_REAL_SIMILAR(scored_spectra[19].getFloatDataArrays()[4][0], 1.94236) } END_SECTION START_SECTION(void selectSpectra( const std::vector<MSSpectrum>& scored_spectra, const FeatureMap& features, std::vector<MSSpectrum>& selected_spectra, FeatureMap& selected_features, const bool compute_features = true ) const) { const double min_select_score = 15.0; TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("min_select_score", min_select_score); params.setValue("GaussFilter:gaussian_width", 0.25); params.setValue("peak_height_min", 15000.0); params.setValue("peak_height_max", 110000.0); params.setValue("fwhm_threshold", 0.23); tse.setParameters(params); const std::vector<MSSpectrum>& spectra = experiment.getSpectra(); std::vector<MSSpectrum> annotated; FeatureMap features; tse.annotateSpectra(spectra, targeted_exp, annotated, features); std::vector<MSSpectrum> picked(annotated.size()); for (Size i = 0; i < annotated.size(); ++i) { tse.pickSpectrum(annotated[i], picked[i]); } for (Int i = annotated.size() - 1; i >= 0; --i) { if (picked[i].empty()) { annotated.erase(annotated.begin() + i); picked.erase(picked.begin() + i); features.erase(features.begin() + i); } } std::vector<MSSpectrum> scored; tse.scoreSpectra(annotated, picked, features, scored); std::vector<MSSpectrum> selected_spectra; FeatureMap selected_features; tse.selectSpectra(scored, features, selected_spectra, selected_features); TEST_EQUAL(selected_spectra.size(), 3) TEST_EQUAL(selected_spectra.size(), selected_features.size()) for (Size i = 0; i < selected_spectra.size(); ++i) { TEST_NOT_EQUAL(selected_spectra[i].getName(), "") TEST_EQUAL(selected_spectra[i].getName(), selected_features[i].getMetaValue("transition_name")) TEST_EQUAL(selected_spectra[i].getFloatDataArrays()[1][0], selected_features[i].getIntensity()) TEST_EQUAL(selected_spectra[i].getFloatDataArrays()[1][0] >= min_select_score, true) } vector<MSSpectrum>::const_iterator it; it = findSpectrumByName(selected_spectra, "asp-L.asp-L_m2-1"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 17.4552230834961) it = findSpectrumByName(selected_spectra, "met-L.met-L_m0-0"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 16.0294418334961) it = findSpectrumByName(selected_spectra, "asp-L.asp-L_m2-2"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 17.4552) features.pop_back(); TEST_EXCEPTION(Exception::InvalidSize, tse.selectSpectra(scored, features, selected_spectra, selected_features)); } END_SECTION START_SECTION(void selectSpectra( const std::vector<MSSpectrum>& scored_spectra, std::vector<MSSpectrum>& selected_spectra ) const) { const double min_select_score = 15.0; TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("min_select_score", min_select_score); params.setValue("GaussFilter:gaussian_width", 0.25); params.setValue("peak_height_min", 15000.0); params.setValue("peak_height_max", 110000.0); params.setValue("fwhm_threshold", 0.23); tse.setParameters(params); const std::vector<MSSpectrum>& spectra = experiment.getSpectra(); std::vector<MSSpectrum> annotated; tse.annotateSpectra(spectra, targeted_exp, annotated); std::vector<MSSpectrum> picked(annotated.size()); for (Size i = 0; i < annotated.size(); ++i) { tse.pickSpectrum(annotated[i], picked[i]); } for (Int i = annotated.size() - 1; i >= 0; --i) { if (picked[i].empty()) { annotated.erase(annotated.begin() + i); picked.erase(picked.begin() + i); } } std::vector<MSSpectrum> scored; tse.scoreSpectra(annotated, picked, scored); std::vector<MSSpectrum> selected_spectra; tse.selectSpectra(scored, selected_spectra); TEST_EQUAL(selected_spectra.size(), 3) for (Size i = 0; i < selected_spectra.size(); ++i) { TEST_NOT_EQUAL(selected_spectra[i].getName(), "") TEST_EQUAL(selected_spectra[i].getFloatDataArrays()[1][0] >= min_select_score, true) } vector<MSSpectrum>::const_iterator it; it = findSpectrumByName(selected_spectra, "asp-L.asp-L_m2-1"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 17.4552230834961) it = findSpectrumByName(selected_spectra, "met-L.met-L_m0-0"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 16.0294418334961) it = findSpectrumByName(selected_spectra, "asp-L.asp-L_m2-2"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 17.4552) } END_SECTION START_SECTION(void extractSpectra( const MSExperiment& experiment, const TargetedExperiment& targeted_exp, std::vector<MSSpectrum>& extracted_spectra, FeatureMap& extracted_features, const bool compute_features = true ) const) { TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("min_select_score", 15.0); params.setValue("GaussFilter:gaussian_width", 0.25); params.setValue("peak_height_min", 15000.0); params.setValue("peak_height_max", 110000.0); params.setValue("fwhm_threshold", 0.23); tse.setParameters(params); vector<MSSpectrum> extracted_spectra; FeatureMap extracted_features; tse.extractSpectra(experiment, targeted_exp, extracted_spectra, extracted_features); TEST_EQUAL(extracted_spectra.size(), extracted_features.size()) TEST_EQUAL(extracted_spectra.size(), 3) vector<MSSpectrum>::const_iterator it; it = findSpectrumByName(extracted_spectra, "asp-L.asp-L_m2-1"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 17.4552230834961) it = findSpectrumByName(extracted_spectra, "met-L.met-L_m0-0"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 16.0294418334961) it = findSpectrumByName(extracted_spectra, "asp-L.asp-L_m2-2"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 17.4552) } END_SECTION START_SECTION(void extractSpectra( const MSExperiment& experiment, const TargetedExperiment& targeted_exp, std::vector<MSSpectrum>& extracted_spectra ) const) { TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("min_select_score", 15.0); params.setValue("GaussFilter:gaussian_width", 0.25); params.setValue("peak_height_min", 15000.0); params.setValue("peak_height_max", 110000.0); params.setValue("fwhm_threshold", 0.23); tse.setParameters(params); vector<MSSpectrum> extracted_spectra; tse.extractSpectra(experiment, targeted_exp, extracted_spectra); TEST_EQUAL(extracted_spectra.size(), 3) vector<MSSpectrum>::const_iterator it; it = findSpectrumByName(extracted_spectra, "asp-L.asp-L_m2-1"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 17.4552230834961) it = findSpectrumByName(extracted_spectra, "met-L.met-L_m0-0"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 16.0294418334961) it = findSpectrumByName(extracted_spectra, "asp-L.asp-L_m2-2"); TEST_REAL_SIMILAR(it->getFloatDataArrays()[1][0], 17.4552) } END_SECTION START_SECTION(void extractSpectra( const MSExperiment& experiment, const FeatureMap& ms1_features, std::vector<MSSpectrum>& extracted_spectra, FeatureMap& extracted_features, const bool compute_features) const) { TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("min_select_score", 15.0); params.setValue("GaussFilter:gaussian_width", 0.25); params.setValue("peak_height_min", 15000.0); params.setValue("peak_height_max", 110000.0); params.setValue("fwhm_threshold", 0.23); tse.setParameters(params); const String msp_path = OPENMS_GET_TEST_DATA_PATH("Germicidin_A_standard.msp"); MSExperiment spectrum; MSPGenericFile mse(msp_path, spectrum); for (OpenMS::MSSpectrum& spec : spectrum) { spec.setMSLevel(2); } const String featurexml_path = OPENMS_GET_TEST_DATA_PATH("Germicidin_A_standard.featureXML"); OpenMS::FeatureXMLFile featurexml; OpenMS::FeatureMap ms1_features; featurexml.load(featurexml_path, ms1_features); std::vector<OpenMS::MSSpectrum> annotated_spectra; OpenMS::FeatureMap extracted_features; tse.extractSpectra(spectrum, ms1_features, annotated_spectra, extracted_features); TEST_EQUAL(annotated_spectra.size(), 1) TEST_EQUAL(annotated_spectra.front().getName(), "HMDB:HMDB0000001") TEST_EQUAL(extracted_features.size(), 1) const auto& extracted_feature = extracted_features[0]; TEST_EQUAL(extracted_feature.getRT(), 391.75) TEST_REAL_SIMILAR(extracted_feature.getIntensity(), 90780.0f) } END_SECTION START_SECTION(void matchSpectrum( const MSSpectrum& input_spectrum, const MSExperiment& library, Comparator& cmp, std::vector<Match>& matches )) { // MS Library offered by: MoNa - MassBank of North America // Title: GC-MS Spectra // http://mona.fiehnlab.ucdavis.edu/downloads // https://creativecommons.org/licenses/by/4.0/legalcode // Changes made: Only a very small subset of spectra is reproduced const String msp_path = OPENMS_GET_TEST_DATA_PATH("MoNA-export-GC-MS_Spectra_reduced_TSE_matchSpectrum.msp"); const String gcms_fullscan_path = OPENMS_GET_TEST_DATA_PATH("TargetedSpectraExtractor_matchSpectrum_GCMS.mzML"); const String target_list_path = OPENMS_GET_TEST_DATA_PATH("TargetedSpectraExtractor_matchSpectrum_traML.csv"); MzMLFile mzml; MSExperiment gcms_experiment; TransitionTSVFile tsv_reader; TargetedExperiment targeted_exp; mzml.load(gcms_fullscan_path, gcms_experiment); Param tsv_params = tsv_reader.getParameters(); tsv_params.setValue("retentionTimeInterpretation", "seconds"); tsv_reader.setParameters(tsv_params); tsv_reader.convertTSVToTargetedExperiment(target_list_path.c_str(), FileTypes::CSV, targeted_exp); TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("rt_window", 2.0); params.setValue("min_select_score", 0.1); params.setValue("GaussFilter:gaussian_width", 0.1); params.setValue("PeakPickerHiRes:signal_to_noise", 0.01); params.setValue("top_matches_to_report", 2); params.setValue("min_match_score", 0.51); tse.setParameters(params); TEST_EQUAL(gcms_experiment.getSpectra().size(), 11) vector<MSSpectrum> extracted_spectra; FeatureMap extracted_features; tse.extractSpectra(gcms_experiment, targeted_exp, extracted_spectra, extracted_features); TEST_EQUAL(extracted_spectra.size(), 18) MSExperiment library; MSPGenericFile mse(msp_path, library); TEST_EQUAL(library.getSpectra().size(), 21) vector<TargetedSpectraExtractor::Match> matches; TargetedSpectraExtractor::BinnedSpectrumComparator cmp; std::map<String,DataValue> options = { {"bin_size", 1.0}, {"peak_spread", 0}, {"bin_offset", 0.4} }; cmp.init(library.getSpectra(), options); tse.matchSpectrum(extracted_spectra[0], cmp, matches); TEST_EQUAL(matches.size() >= 2, true) TEST_EQUAL(matches[0].score >= matches[1].score, true) tse.matchSpectrum(extracted_spectra[4], cmp, matches); TEST_EQUAL(matches.size() >= 2, true) TEST_EQUAL(matches[0].score >= matches[1].score, true) tse.matchSpectrum(extracted_spectra[8], cmp, matches); TEST_EQUAL(matches.size() >= 2, true) TEST_EQUAL(matches[0].score >= matches[1].score, true) tse.matchSpectrum(extracted_spectra[9], cmp, matches); TEST_EQUAL(matches.size() >= 2, true) TEST_EQUAL(matches[0].score >= matches[1].score, true) tse.matchSpectrum(extracted_spectra[13], cmp, matches); TEST_EQUAL(matches.size() >= 2, true) TEST_EQUAL(matches[0].score >= matches[1].score, true) tse.matchSpectrum(extracted_spectra[17], cmp, matches); TEST_EQUAL(matches.size() >= 2, true) TEST_EQUAL(matches[0].score >= matches[1].score, true) } END_SECTION START_SECTION(void targetedMatching( const std::vector<MSSpectrum>& spectra, Comparator& cmp, FeatureMap& features )) { // MS Library offered by: MoNa - MassBank of North America // Title: GC-MS Spectra // http://mona.fiehnlab.ucdavis.edu/downloads // https://creativecommons.org/licenses/by/4.0/legalcode // Changes made: Only a very small subset of spectra is reproduced const String msp_path = OPENMS_GET_TEST_DATA_PATH("MoNA-export-GC-MS_Spectra_reduced_TSE_matchSpectrum.msp"); const String gcms_fullscan_path = OPENMS_GET_TEST_DATA_PATH("TargetedSpectraExtractor_matchSpectrum_GCMS.mzML"); const String target_list_path = OPENMS_GET_TEST_DATA_PATH("TargetedSpectraExtractor_matchSpectrum_traML.csv"); MzMLFile mzml; MSExperiment gcms_experiment; TransitionTSVFile tsv_reader; TargetedExperiment targeted_exp; mzml.load(gcms_fullscan_path, gcms_experiment); Param tsv_params = tsv_reader.getParameters(); tsv_params.setValue("retentionTimeInterpretation", "seconds"); tsv_reader.setParameters(tsv_params); tsv_reader.convertTSVToTargetedExperiment(target_list_path.c_str(), FileTypes::CSV, targeted_exp); TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("rt_window", 2.0); params.setValue("min_select_score", 0.1); params.setValue("GaussFilter:gaussian_width", 0.1); params.setValue("PeakPickerHiRes:signal_to_noise", 0.01); params.setValue("top_matches_to_report", 2); params.setValue("min_match_score", 0.51); tse.setParameters(params); TEST_EQUAL(gcms_experiment.getSpectra().size(), 11) vector<MSSpectrum> extracted_spectra; FeatureMap extracted_features; tse.extractSpectra(gcms_experiment, targeted_exp, extracted_spectra, extracted_features); TEST_EQUAL(extracted_spectra.size(), 18) MSExperiment library; MSPGenericFile mse(msp_path, library); TEST_EQUAL(library.getSpectra().size(), 21) TargetedSpectraExtractor::BinnedSpectrumComparator cmp; std::map<String,DataValue> options = { {"bin_size", 1.0}, {"peak_spread", 0}, {"bin_offset", 0.4} }; cmp.init(library.getSpectra(), options); tse.targetedMatching(extracted_spectra, cmp, extracted_features); TEST_STRING_EQUAL(extracted_features[0].getMetaValue("spectral_library_name"), "beta-D-(+)-Glucose") TEST_REAL_SIMILAR(extracted_features[0].getMetaValue("spectral_library_score"), 0.946971) String comments = R"("accession=PR010079" "author=Kusano M, Fukushima A, Plant Science Center, RIKEN." "license=CC BY-SA" "exact mass=180.06339" "instrument=Pegasus III TOF-MS system, Leco; GC 6890, Agilent Technologies" "instrument type=GC-EI-TOF" "ms level=MS1" "retention index=1882.4" "retention time=459.562 sec" "derivative formula=C22H55NO6Si5" "derivative mass=569.28757" "derivatization type=5 TMS; 1 MEOX" "ionization mode=positive" "compound class=Natural Product" "SMILES=OCC(O1)C(O)C(O)C(O)C(O)1" "cas=492-61-5" "chebi=15903" "kegg=C00221" "pubchem=3521" "InChI=InChI=1S/C6H12O6/c7-1-2-3(8)4(9)5(10)6(11)12-2/h2-11H,1H2/t2-,3-,4+,5-,6-/m1/s1" "molecular formula=C6H12O6" "total exact mass=180.06338810399998" "SMILES=C(C1C(C(C(C(O)O1)O)O)O)O" "InChIKey=WQZGKKKJIJFFOK-VFUOTHLCSA-N")"; TEST_STRING_EQUAL(extracted_features[0].getMetaValue("spectral_library_comments"), comments) TEST_STRING_EQUAL(extracted_features[5].getMetaValue("spectral_library_name"), "Adonitol") TEST_REAL_SIMILAR(extracted_features[5].getMetaValue("spectral_library_score"), 0.891443) comments = R"("accession=PR010134" "author=Kusano M, Fukushima A, Plant Science Center, RIKEN." "license=CC BY-SA" "exact mass=152.06847" "instrument=Pegasus III TOF-MS system, Leco; GC 6890, Agilent Technologies" "instrument type=GC-EI-TOF" "ms level=MS1" "retention index=1710.9" "retention time=416.034 sec" "derivative formula=C20H52O5Si5" "derivative mass=512.26611" "derivatization type=5 TMS" "ionization mode=positive" "compound class=Natural Product" "SMILES=OCC([H])(O)C([H])(O)C([H])(O)CO" "cas=488-81-3" "chebi=15963" "kegg=C00474" "pubchem=3757" "InChI=InChI=1S/C5H12O5/c6-1-3(8)5(10)4(9)2-7/h3-10H,1-2H2/t3-,4+,5-" "molecular formula=C5H12O5" "total exact mass=152.06847348399998" "SMILES=C(C(C(C(CO)O)O)O)O" "InChIKey=HEBKCHPVOIAQTA-ZXFHETKHSA-N")"; TEST_STRING_EQUAL(extracted_features[5].getMetaValue("spectral_library_comments"), comments) TEST_STRING_EQUAL(extracted_features[10].getMetaValue("spectral_library_name"), "BENZENE-1,2,4,5-TETRACARBOXYLIC ACID TETRA(TRIMETHYLSILYL) ESTER") TEST_REAL_SIMILAR(extracted_features[10].getMetaValue("spectral_library_score"), 0.887661) comments = R"("accession=JP000601" "author=KOGA M, UNIV. OF OCCUPATIONAL AND ENVIRONMENTAL HEALTH" "license=CC BY-NC-SA" "exact mass=542.16437" "instrument=JEOL JMS-01-SG" "instrument type=EI-B" "ms level=MS1" "ionization energy=70 eV" "ion type=[M]+*" "ionization mode=positive" "SMILES=C[Si](C)(C)OC(=O)c(c1)c(C(=O)O[Si](C)(C)C)cc(C(=O)O[Si](C)(C)C)c(C(=O)O[Si](C)(C)C)1" "InChI=InChI=1S/C22H38O8Si4/c1-31(2,3)27-19(23)15-13-17(21(25)29-33(7,8)9)18(22(26)30-34(10,11)12)14-16(15)20(24)28-32(4,5)6/h13-14H,1-12H3" "molecular formula=C22H38O8Si4" "total exact mass=542.164374296" "SMILES=C[Si](C)(C)OC(C1=CC(=C(C=C1C(=O)O[Si](C)(C)C)C(=O)O[Si](C)(C)C)C(=O)O[Si](C)(C)C)=O" "InChIKey=BKFGZLAJFGESBT-UHFFFAOYSA-N")"; TEST_STRING_EQUAL(extracted_features[10].getMetaValue("spectral_library_comments"), comments) } END_SECTION START_SECTION(void untargetedMatching( const std::vector<MSSpectrum>& spectra, Comparator& cmp, FeatureMap& features )) { // MS Library offered by: MoNa - MassBank of North America // Title: GC-MS Spectra // http://mona.fiehnlab.ucdavis.edu/downloads // https://creativecommons.org/licenses/by/4.0/legalcode // Changes made: Only a very small subset of spectra is reproduced const String msp_path = OPENMS_GET_TEST_DATA_PATH("MoNA-export-GC-MS_Spectra_reduced_TSE_matchSpectrum.msp"); const String gcms_fullscan_path = OPENMS_GET_TEST_DATA_PATH("TargetedSpectraExtractor_matchSpectrum_GCMS.mzML"); MzMLFile mzml; MSExperiment gcms_experiment; TargetedExperiment targeted_exp; mzml.load(gcms_fullscan_path, gcms_experiment); TargetedSpectraExtractor tse; Param params = tse.getParameters(); params.setValue("top_matches_to_report", 2); params.setValue("min_match_score", 0.51); tse.setParameters(params); TEST_EQUAL(gcms_experiment.getSpectra().size(), 11) MSExperiment library; MSPGenericFile mse(msp_path, library); TEST_EQUAL(library.getSpectra().size(), 21) TargetedSpectraExtractor::BinnedSpectrumComparator cmp; std::map<String,DataValue> options = { {"bin_size", 1.0}, {"peak_spread", 0}, {"bin_offset", 0.4} }; cmp.init(library.getSpectra(), options); FeatureMap features; tse.untargetedMatching(gcms_experiment.getSpectra(), cmp, features); TEST_STRING_EQUAL(features[0].getMetaValue("spectral_library_name"), "") TEST_REAL_SIMILAR(features[0].getMetaValue("spectral_library_score"), 0.0) TEST_STRING_EQUAL(features[0].getMetaValue("spectral_library_comments"), "") TEST_STRING_EQUAL(features[1].getMetaValue("spectral_library_name"), "D-Glucose-6-phosphate") TEST_REAL_SIMILAR(features[1].getMetaValue("spectral_library_score"), 0.691226) String comments = R"("accession=PR010050" "author=Kusano M, Fukushima A, Plant Science Center, RIKEN." "license=CC BY-SA" "exact mass=260.02972" "instrument=Pegasus III TOF-MS system, Leco; GC 6890, Agilent Technologies" "instrument type=GC-EI-TOF" "ms level=MS1" "retention index=2300.2" "retention time=538.069 sec" "derivative formula=C25H64NO9PSi6" "derivative mass=721.29343" "derivatization type=6 TMS; 1 MEOX" "ionization mode=positive" "compound class=Natural Product" "SMILES=OC(O1)[C@H](O)[C@@H](O)[C@H](O)[C@H]1COP(O)(O)=O" "cas=54010-71-8" "InChI=InChI=1S/C6H13O9P/c7-3-2(1-14-16(11,12)13)15-6(10)5(9)4(3)8/h2-10H,1H2,(H2,11,12,13)/t2-,3-,4+,5-,6?/m1/s1" "molecular formula=C6H13O9P" "total exact mass=260.029718626" "SMILES=C(C1C(C(C(C(O)O1)O)O)O)OP(O)(O)=O" "InChIKey=NBSCHQHZLSJFNQ-GASJEMHNSA-N")"; TEST_STRING_EQUAL(features[1].getMetaValue("spectral_library_comments"), comments) TEST_STRING_EQUAL(features[6].getMetaValue("spectral_library_name"), "2,3-Pyridinedicarboxylic acid") TEST_REAL_SIMILAR(features[6].getMetaValue("spectral_library_score"), 0.54155) comments = R"lit("accession=PR010082" "author=Kusano M, Fukushima A, Plant Science Center, RIKEN." "license=CC BY-SA" "exact mass=167.02186" "instrument=Pegasus III TOF-MS system, Leco; GC 6890, Agilent Technologies" "instrument type=GC-EI-TOF" "ms level=MS1" "retention index=1721.2" "retention time=422.998 sec" "derivative formula=C13H21NO4Si2" "derivative mass=311.10091" "derivatization type=2 TMS" "ionization mode=positive" "compound class=Natural Product" "SMILES=OC(=O)c(c1)c(ncc1)C(O)=O" "cas=89-00-9" "chebi=16675" "kegg=C03722" "pubchem=6487" "InChI=InChI=1S/C7H5NO4/c9-6(10)4-2-1-3-8-5(4)7(11)12/h1-3H,(H,9,10)(H,11,12)" "molecular formula=C7H5NO4" "total exact mass=167.02185764" "SMILES=C1=CC(=C(C(=O)O)N=C1)C(=O)O" "InChIKey=GJAWHXHKYYXBSV-UHFFFAOYSA-N")lit"; TEST_STRING_EQUAL(features[6].getMetaValue("spectral_library_comments"), comments) TEST_STRING_EQUAL(features[10].getMetaValue("spectral_library_name"), "D-Glucose-6-phosphate") TEST_REAL_SIMILAR(features[10].getMetaValue("spectral_library_score"), 0.922175) comments = R"("accession=PR010050" "author=Kusano M, Fukushima A, Plant Science Center, RIKEN." "license=CC BY-SA" "exact mass=260.02972" "instrument=Pegasus III TOF-MS system, Leco; GC 6890, Agilent Technologies" "instrument type=GC-EI-TOF" "ms level=MS1" "retention index=2300.2" "retention time=538.069 sec" "derivative formula=C25H64NO9PSi6" "derivative mass=721.29343" "derivatization type=6 TMS; 1 MEOX" "ionization mode=positive" "compound class=Natural Product" "SMILES=OC(O1)[C@H](O)[C@@H](O)[C@H](O)[C@H]1COP(O)(O)=O" "cas=54010-71-8" "InChI=InChI=1S/C6H13O9P/c7-3-2(1-14-16(11,12)13)15-6(10)5(9)4(3)8/h2-10H,1H2,(H2,11,12,13)/t2-,3-,4+,5-,6?/m1/s1" "molecular formula=C6H13O9P" "total exact mass=260.029718626" "SMILES=C(C1C(C(C(C(O)O1)O)O)O)OP(O)(O)=O" "InChIKey=NBSCHQHZLSJFNQ-GASJEMHNSA-N")"; TEST_STRING_EQUAL(features[10].getMetaValue("spectral_library_comments"), comments) } END_SECTION START_SECTION(mergeFeatures(const OpenMS::FeatureMap& fmap_input, OpenMS::FeatureMap& fmap_output) const) { TargetedSpectraExtractor targeted_spectra_extractor; OpenMS::FeatureMap features; OpenMS::Feature f1; f1.setUniqueId(); std::vector<String> identifier1{"ident1"}; f1.setMetaValue("identifier", identifier1); f1.setMetaValue("PeptideRef", "PeptideRef1"); f1.setIntensity(1); f1.setMZ(10); f1.setRT(100); features.push_back(f1); OpenMS::Feature f2; f2.setUniqueId(); std::vector<String> identifier2{"ident1", "ident2"}; f2.setMetaValue("identifier", identifier2); f2.setMetaValue("PeptideRef", "PeptideRef1"); f2.setIntensity(2); f2.setMZ(20); f2.setRT(100); features.push_back(f2); OpenMS::Feature f3; f3.setUniqueId(); std::vector<String> identifier3{"ident3"}; f3.setMetaValue("identifier", identifier3); f3.setMetaValue("PeptideRef", "PeptideRef3"); f3.setIntensity(3); f3.setMZ(30); f3.setRT(300); features.push_back(f3); OpenMS::FeatureMap merged_features; targeted_spectra_extractor.mergeFeatures(features, merged_features); TEST_EQUAL(merged_features.size(), 2) const auto& merged_f1 = merged_features[0]; TEST_EQUAL(merged_f1.getMetaValue("PeptideRef"), "PeptideRef1"); TEST_REAL_SIMILAR(merged_f1.getMZ(), 16.6667); TEST_REAL_SIMILAR(merged_f1.getRT(), 100.00); TEST_EQUAL(merged_f1.getSubordinates().size(), 2); const auto& merged_f1_sub1 = merged_f1.getSubordinates().at(0); TEST_EQUAL(merged_f1_sub1.getMetaValue("identifier"), identifier1); TEST_REAL_SIMILAR(merged_f1_sub1.getMZ(), 10.0); TEST_REAL_SIMILAR(merged_f1_sub1.getRT(), 100.0); const auto& merged_f1_sub2 = merged_f1.getSubordinates().at(1); TEST_EQUAL(merged_f1_sub2.getMetaValue("identifier"), identifier2); TEST_REAL_SIMILAR(merged_f1_sub2.getMZ(), 20.0); TEST_REAL_SIMILAR(merged_f1_sub2.getRT(), 100.0); const auto& merged_f2 = merged_features[1]; TEST_EQUAL(merged_f2.getMetaValue("PeptideRef"), "PeptideRef3"); TEST_REAL_SIMILAR(merged_f2.getMZ(), 30.0); TEST_REAL_SIMILAR(merged_f2.getRT(), 300.0); TEST_EQUAL(merged_f2.getSubordinates().size(), 1); const auto& merged_f2_sub1 = merged_f2.getSubordinates().at(0); TEST_EQUAL(merged_f2_sub1.getMetaValue("identifier"), identifier3); TEST_REAL_SIMILAR(merged_f2_sub1.getMZ(), 30.0); TEST_REAL_SIMILAR(merged_f2_sub1.getRT(), 300.0); } END_SECTION START_SECTION(annotateSpectra(const std::vector<MSSpectrum>& spectra, const FeatureMap& ms1_features, FeatureMap& ms2_features, std::vector<MSSpectrum>& annotated_spectra) const) { OpenMS::FeatureMap ms1_features; OpenMS::Feature f1; f1.setUniqueId(); std::vector<String> identifier1{"ident1"}; f1.setMetaValue("identifier", identifier1); f1.setIntensity(1); f1.setMZ(10); f1.setRT(100); std::vector<OpenMS::Feature> subs1; OpenMS::Feature f1_sub1; f1_sub1.setUniqueId(); f1_sub1.setMetaValue("PeptideRef", "ident1"); f1_sub1.setIntensity(2); f1_sub1.setMZ(9); f1_sub1.setRT(110); subs1.push_back(f1_sub1); OpenMS::Feature f1_sub2; // this one will not be used in the annotation f1_sub2.setUniqueId(); f1_sub2.setMetaValue("PeptideRef", "ident1"); f1_sub2.setIntensity(2); f1_sub2.setMZ(29); f1_sub2.setRT(210); subs1.push_back(f1_sub2); f1.setSubordinates(subs1); ms1_features.push_back(f1); std::vector<MSSpectrum> spectra; MSSpectrum spectr1; spectr1.setMSLevel(2); spectr1.setRT(100); spectra.push_back(spectr1); TargetedSpectraExtractor targeted_spectra_extractor; FeatureMap ms2_features; std::vector<MSSpectrum> annotated_spectra; targeted_spectra_extractor.annotateSpectra(spectra, ms1_features, ms2_features, annotated_spectra); TEST_EQUAL(ms2_features.size(), 1) const auto& ms2_f1 = ms2_features[0]; TEST_REAL_SIMILAR(ms2_f1.getMZ(), 0.0) TEST_REAL_SIMILAR(ms2_f1.getRT(), 100.0) TEST_EQUAL(ms2_f1.getMetaValue("PeptideRef"), "ident1") TEST_EQUAL(ms2_f1.getSubordinates().size(), 0) TEST_EQUAL(annotated_spectra.size(), 1) const auto& annotated_spectr1 = annotated_spectra[0]; TEST_EQUAL(annotated_spectr1.getName(), "ident1") TEST_REAL_SIMILAR(annotated_spectr1.getRT(), 100.0) } END_SECTION START_SECTION(constructTransitionsList(const String& filename, const OpenMS::FeatureMap& ms1_features, const OpenMS::FeatureMap& ms2_features) const) { OpenMS::FeatureMap ms1_features; OpenMS::Feature ms1_f1; ms1_f1.setUniqueId(); ms1_f1.setMetaValue("PeptideRef", "ident1"); ms1_f1.setIntensity(1); ms1_f1.setMZ(10); ms1_f1.setRT(100); ms1_features.push_back(ms1_f1); OpenMS::FeatureMap ms2_features; OpenMS::Feature ms2_f1; ms2_f1.setUniqueId(); ms2_f1.setIntensity(1); ms2_f1.setMZ(10); ms2_f1.setRT(100); std::vector<OpenMS::Feature> ms2_subs1; OpenMS::Feature ms2_f1_sub1; ms2_f1_sub1.setUniqueId(); ms2_f1_sub1.setMetaValue("PeptideRef", "ident1"); ms2_f1_sub1.setMetaValue("native_id", "ms2_f1_sub1"); ms2_f1_sub1.setIntensity(2); ms2_f1_sub1.setMZ(9); ms2_f1_sub1.setRT(110); ms2_subs1.push_back(ms2_f1_sub1); OpenMS::Feature ms2_f1_sub2; ms2_f1_sub2.setUniqueId(); ms2_f1_sub2.setMetaValue("PeptideRef", "ident1"); ms2_f1_sub2.setMetaValue("native_id", "ms2_f1_sub2"); ms2_f1_sub2.setIntensity(2); ms2_f1_sub2.setMZ(29); ms2_f1_sub2.setRT(210); ms2_subs1.push_back(ms2_f1_sub2); ms2_f1.setSubordinates(ms2_subs1); ms2_features.push_back(ms2_f1); TargetedSpectraExtractor targeted_spectra_extractor; TargetedExperiment t_exp; targeted_spectra_extractor.constructTransitionsList(ms1_features, ms2_features, t_exp); TEST_EQUAL(t_exp.getTransitions().size(), 1) const auto& transition = t_exp.getTransitions()[0]; TEST_EQUAL(transition.getPeptideRef(), "ident1"); TEST_EQUAL(transition.getMetaValue("PeptideRef"), "ident1"); TEST_EQUAL(transition.getMetaValue("native_id"), "ms2_f1_sub1"); } END_SECTION START_SECTION(void TargetedSpectraExtractor::storeSpectraMSP(const String& filename, MSExperiment& experiment) const) { MSExperiment experiment; std::vector<MSSpectrum> spectra; MSSpectrum spectr1; spectr1.setMSLevel(2); spectr1.setRT(100); spectr1.setName("spectr1"); Precursor precursor1; precursor1.setMZ(100); spectr1.setPrecursors({precursor1}); Peak1D peak1; peak1.setMZ(100); peak1.setIntensity(10); spectr1.push_back(peak1); Peak1D peak2; spectr1.push_back(peak2); peak2.setMZ(200); peak2.setIntensity(20); spectra.push_back(spectr1); String output_filepath; NEW_TMP_FILE_EXT(output_filepath, ".msp") experiment.setSpectra(spectra); TargetedSpectraExtractor targeted_spectra_extractor; targeted_spectra_extractor.storeSpectraMSP(output_filepath, experiment); // read back the file MSPGenericFile msp_file; msp_file.store(output_filepath, experiment); TEST_EQUAL(experiment.getSpectra().size(), 1) const auto& output_spectr1 = experiment.getSpectra()[0]; TEST_EQUAL(output_spectr1.size(), 1) const auto& peak = output_spectr1[0]; TEST_EQUAL(peak.getIntensity(), 10); TEST_EQUAL(peak.getMZ(), 100); } END_SECTION START_SECTION(void TargetedSpectraExtractor::storeSpectraMSP(const String& filename, MSExperiment& experiment) const) { FeatureMap input_fm; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_input1.featureXML"), input_fm); FeatureMap output_fm; TargetedSpectraExtractor targeted_spectra_extractor; targeted_spectra_extractor.searchSpectrum(input_fm, output_fm); TEST_EQUAL(output_fm.size(), 19); const auto& fm1 = output_fm[0]; TEST_EQUAL(fm1.getSubordinates().size(), 1); const auto& fm1_sub1 = fm1.getSubordinates()[0]; TEST_EQUAL(fm1_sub1.getMetaValue("PeptideRef"), "HMDB:HMDB0061131"); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ModificationDefinition_test.cpp
.cpp
9,354
305
// 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/ModificationDefinition.h> #include <OpenMS/CHEMISTRY/ModificationsDB.h> #include <unordered_set> #include <unordered_map> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ModificationDefinition, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ModificationDefinition* ptr = nullptr; ModificationDefinition* nullPointer = nullptr; START_SECTION(ModificationDefinition()) { ptr = new ModificationDefinition(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((virtual ~ModificationDefinition())) { delete ptr; } END_SECTION ptr = new ModificationDefinition(); START_SECTION((ModificationDefinition(const ModificationDefinition& rhs))) { ModificationDefinition mod_def; mod_def.setFixedModification(true); ModificationDefinition copy(mod_def); TEST_EQUAL(mod_def.isFixedModification(), copy.isFixedModification()) mod_def.setFixedModification(false); ModificationDefinition copy2(mod_def); TEST_EQUAL(mod_def.isFixedModification(), copy2.isFixedModification()) } END_SECTION START_SECTION((ModificationDefinition(const String& mod, bool fixed = true, UInt max_occur = 0))) { ModificationDefinition mod1("Acetyl (N-term)"); TEST_EQUAL(mod1.getModificationName(), "Acetyl (N-term)"); ModificationDefinition mod2("Oxidation (M)"); TEST_EQUAL(mod2.getModificationName(), "Oxidation (M)"); TEST_EQUAL(mod2.isFixedModification(), true); TEST_EQUAL(mod2.getMaxOccurrences(), 0); ModificationDefinition mod3("Carboxymethyl (C)", false, 2); TEST_EQUAL(mod3.getModificationName(), "Carboxymethyl (C)"); TEST_EQUAL(mod3.isFixedModification(), false); TEST_EQUAL(mod3.getMaxOccurrences(), 2); } END_SECTION START_SECTION((ModificationDefinition(const ResidueModification& mod, bool fixed = true, UInt max_occur = 0))) { const ResidueModification res_mod1 = *ModificationsDB::getInstance()->getModification("Acetyl (N-term)"); ModificationDefinition mod1(res_mod1); TEST_EQUAL(mod1.getModificationName(), "Acetyl (N-term)"); TEST_EQUAL(mod1.isFixedModification(), true); TEST_EQUAL(mod1.getMaxOccurrences(), 0); const ResidueModification res_mod2 = *ModificationsDB::getInstance()->getModification("Oxidation (M)"); ModificationDefinition mod2(res_mod2, false, 2); TEST_EQUAL(mod2.isFixedModification(), false); TEST_EQUAL(mod2.getMaxOccurrences(), 2); } END_SECTION START_SECTION((void setFixedModification(bool fixed))) { ptr->setFixedModification(true); TEST_EQUAL(ptr->isFixedModification(), true) ptr->setFixedModification(false); TEST_EQUAL(ptr->isFixedModification(), false) } END_SECTION START_SECTION((bool isFixedModification() const)) { // tested above NOT_TESTABLE } END_SECTION START_SECTION((void setMaxOccurrences(UInt num))) { ptr->setMaxOccurrences(1); TEST_EQUAL(ptr->getMaxOccurrences(), 1) ptr->setMaxOccurrences(1000); TEST_EQUAL(ptr->getMaxOccurrences(), 1000) } END_SECTION START_SECTION((UInt getMaxOccurrences() const)) { // tested above NOT_TESTABLE } END_SECTION START_SECTION((String getModificationName() const)) { ModificationDefinition mod1; mod1.setModification("Acetyl (N-term)"); TEST_EQUAL(mod1.getModificationName(), "Acetyl (N-term)") mod1.setModification("Oxidation (M)"); TEST_EQUAL(mod1.getModificationName(), "Oxidation (M)") } END_SECTION START_SECTION((String getModification() const)) { const ResidueModification* rm = ModificationsDB::getInstance()->getModification("Acetyl (N-term)"); ModificationDefinition mod1; mod1.setModification(rm->getFullId()); TEST_EQUAL(rm, &(mod1.getModification())); } END_SECTION START_SECTION((void setModification(const String& modification))) { // tested above NOT_TESTABLE } END_SECTION START_SECTION((ModificationDefinition& operator=(const ModificationDefinition& element))) { ModificationDefinition mod_def; mod_def.setFixedModification(true); *ptr = mod_def; TEST_EQUAL(mod_def.isFixedModification(), ptr->isFixedModification()) mod_def.setFixedModification(false); *ptr = mod_def; TEST_EQUAL(mod_def.isFixedModification(), ptr->isFixedModification()) } END_SECTION START_SECTION((bool operator==(const ModificationDefinition& rhs) const)) { ModificationDefinition m1, m2; TEST_TRUE(m1 == m2) m1.setFixedModification(false); TEST_EQUAL(m1 == m2, false) m1.setFixedModification(true); m1.setMaxOccurrences(15); TEST_EQUAL(m1 == m2, false) m1.setMaxOccurrences(0); m1.setModification("Oxidation (M)"); TEST_EQUAL(m1 == m2, false) m2.setModification("Oxidation (M)"); TEST_TRUE(m1 == m2) } END_SECTION START_SECTION((bool operator!=(const ModificationDefinition& rhs) const)) { ModificationDefinition m1, m2; TEST_EQUAL(m1 != m2, false) m1.setFixedModification(false); TEST_FALSE(m1 == m2) m1.setFixedModification(true); m1.setMaxOccurrences(15); TEST_FALSE(m1 == m2) m1.setMaxOccurrences(0); m1.setModification("Oxidation (M)"); TEST_FALSE(m1 == m2) m2.setModification("Oxidation (M)"); TEST_EQUAL(m1 != m2, false) } END_SECTION START_SECTION((bool operator<(const OpenMS::ModificationDefinition& rhs) const)) { ModificationDefinition m1, m2; m1.setModification("Oxidation (M)"); m2.setModification("Carboxymethyl (C)"); TEST_EQUAL(m1 < m2, false) TEST_EQUAL(m1 < m1, false) TEST_EQUAL(m2 < m1, true) } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// // Hash tests ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] std::hash<ModificationDefinition>)) { // Test 1: Equal objects must have equal hashes ModificationDefinition m1("Oxidation (M)", true, 3); ModificationDefinition m2("Oxidation (M)", true, 3); TEST_EQUAL(m1 == m2, true) TEST_EQUAL(std::hash<ModificationDefinition>{}(m1), std::hash<ModificationDefinition>{}(m2)) // Test 2: Different modifications should (likely) have different hashes ModificationDefinition m3("Acetyl (N-term)", true, 0); // Not guaranteed, but extremely likely to be different TEST_NOT_EQUAL(std::hash<ModificationDefinition>{}(m1), std::hash<ModificationDefinition>{}(m3)) // Test 3: Different fixed_modification should produce different hashes ModificationDefinition m4("Oxidation (M)", false, 3); TEST_EQUAL(m1 == m4, false) TEST_NOT_EQUAL(std::hash<ModificationDefinition>{}(m1), std::hash<ModificationDefinition>{}(m4)) // Test 4: Different max_occurrences should produce different hashes ModificationDefinition m5("Oxidation (M)", true, 5); TEST_EQUAL(m1 == m5, false) TEST_NOT_EQUAL(std::hash<ModificationDefinition>{}(m1), std::hash<ModificationDefinition>{}(m5)) // Test 5: Hash consistency - same object hashed multiple times std::size_t hash1 = std::hash<ModificationDefinition>{}(m1); std::size_t hash2 = std::hash<ModificationDefinition>{}(m1); TEST_EQUAL(hash1, hash2) } END_SECTION START_SECTION(([EXTRA] ModificationDefinition in std::unordered_set)) { std::unordered_set<ModificationDefinition> mod_set; ModificationDefinition m1("Oxidation (M)", true, 0); ModificationDefinition m2("Acetyl (N-term)", false, 2); ModificationDefinition m3("Carboxymethyl (C)", true, 1); // Insert modifications mod_set.insert(m1); mod_set.insert(m2); mod_set.insert(m3); TEST_EQUAL(mod_set.size(), 3) // Insert duplicate - should not increase size ModificationDefinition m1_copy("Oxidation (M)", true, 0); mod_set.insert(m1_copy); TEST_EQUAL(mod_set.size(), 3) // Find operations TEST_EQUAL(mod_set.find(m1) != mod_set.end(), true) TEST_EQUAL(mod_set.find(m2) != mod_set.end(), true) TEST_EQUAL(mod_set.count(m1_copy), 1) // Non-existent element ModificationDefinition m4("Phospho (S)", true, 0); TEST_EQUAL(mod_set.find(m4) == mod_set.end(), true) TEST_EQUAL(mod_set.count(m4), 0) } END_SECTION START_SECTION(([EXTRA] ModificationDefinition in std::unordered_map)) { std::unordered_map<ModificationDefinition, std::string> mod_map; ModificationDefinition m1("Oxidation (M)", true, 0); ModificationDefinition m2("Acetyl (N-term)", false, 2); // Insert key-value pairs mod_map[m1] = "oxidation_value"; mod_map[m2] = "acetyl_value"; TEST_EQUAL(mod_map.size(), 2) // Access by key TEST_EQUAL(mod_map[m1], "oxidation_value") TEST_EQUAL(mod_map[m2], "acetyl_value") // Update value mod_map[m1] = "updated_value"; TEST_EQUAL(mod_map[m1], "updated_value") TEST_EQUAL(mod_map.size(), 2) // Find using equal object ModificationDefinition m1_copy("Oxidation (M)", true, 0); auto it = mod_map.find(m1_copy); TEST_EQUAL(it != mod_map.end(), true) TEST_EQUAL(it->second, "updated_value") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/EGHTraceFitter_test.cpp
.cpp
12,116
415
// 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/EGHTraceFitter.h> /////////////////////////// #include <OpenMS/KERNEL/Peak1D.h> #include <cmath> using namespace OpenMS; using namespace std; #define PI 3.14159265358979323846 // TODO: include a more asymmetric trace in the test START_TEST(EGHTraceFitter, "$Id$") FeatureFinderAlgorithmPickedHelperStructs::MassTraces mts; FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt1; mt1.theoretical_int = 0.8; FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt2; mt2.theoretical_int = 0.2; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // set up mass traces to fit Peak1D p1_1; p1_1.setIntensity(1.08268226589f); p1_1.setMZ(1000); mt1.peaks.push_back(make_pair(677.1, &p1_1)); Peak1D p2_1; p2_1.setIntensity(0.270670566473f); p2_1.setMZ(1001); mt2.peaks.push_back(make_pair(677.1, &p2_1)); Peak1D p1_2; p1_2.setIntensity(1.58318959267f); p1_2.setMZ(1000); mt1.peaks.push_back(make_pair(677.4, &p1_2)); Peak1D p2_2; p2_2.setIntensity(0.395797398167f); p2_2.setMZ(1001); mt2.peaks.push_back(make_pair(677.4, &p2_2)); Peak1D p1_3; p1_3.setIntensity(2.22429840363f); p1_3.setMZ(1000); mt1.peaks.push_back(make_pair(677.7, &p1_3)); Peak1D p2_3; p2_3.setIntensity(0.556074600906f); p2_3.setMZ(1001); mt2.peaks.push_back(make_pair(677.7, &p2_3)); Peak1D p1_4; p1_4.setIntensity(3.00248879081f); p1_4.setMZ(1000); mt1.peaks.push_back(make_pair(678, &p1_4)); Peak1D p2_4; p2_4.setIntensity(0.750622197703f); p2_4.setMZ(1001); mt2.peaks.push_back(make_pair(678, &p2_4)); Peak1D p1_5; p1_5.setIntensity(3.89401804768f); p1_5.setMZ(1000); mt1.peaks.push_back(make_pair(678.3, &p1_5)); Peak1D p2_5; p2_5.setIntensity(0.97350451192f); p2_5.setMZ(1001); mt2.peaks.push_back(make_pair(678.3, &p2_5)); Peak1D p1_6; p1_6.setIntensity(4.8522452777f); p1_6.setMZ(1000); mt1.peaks.push_back(make_pair(678.6, &p1_6)); Peak1D p2_6; p2_6.setIntensity(1.21306131943f); p2_6.setMZ(1001); mt2.peaks.push_back(make_pair(678.6, &p2_6)); Peak1D p1_7; p1_7.setIntensity(5.80919229659f); p1_7.setMZ(1000); mt1.peaks.push_back(make_pair(678.9, &p1_7)); Peak1D p2_7; p2_7.setIntensity(1.45229807415f); p2_7.setMZ(1001); mt2.peaks.push_back(make_pair(678.9, &p2_7)); Peak1D p1_8; p1_8.setIntensity(6.68216169129f); p1_8.setMZ(1000); mt1.peaks.push_back(make_pair(679.2, &p1_8)); Peak1D p2_8; p2_8.setIntensity(1.67054042282f); p2_8.setMZ(1001); mt2.peaks.push_back(make_pair(679.2, &p2_8)); Peak1D p1_9; p1_9.setIntensity(7.38493077109f); p1_9.setMZ(1000); mt1.peaks.push_back(make_pair(679.5, &p1_9)); Peak1D p2_9; p2_9.setIntensity(1.84623269277f); p2_9.setMZ(1001); mt2.peaks.push_back(make_pair(679.5, &p2_9)); Peak1D p1_10; p1_10.setIntensity(7.84158938645f); p1_10.setMZ(1000); mt1.peaks.push_back(make_pair(679.8, &p1_10)); Peak1D p2_10; p2_10.setIntensity(1.96039734661f); p2_10.setMZ(1001); mt2.peaks.push_back(make_pair(679.8, &p2_10)); Peak1D p1_11; p1_11.setIntensity(8.0f); p1_11.setMZ(1000); mt1.peaks.push_back(make_pair(680.1, &p1_11)); Peak1D p2_11; p2_11.setIntensity(2.0f); p2_11.setMZ(1001); mt2.peaks.push_back(make_pair(680.1, &p2_11)); Peak1D p1_12; p1_12.setIntensity(7.84158938645f); p1_12.setMZ(1000); mt1.peaks.push_back(make_pair(680.4, &p1_12)); Peak1D p2_12; p2_12.setIntensity(1.96039734661f); p2_12.setMZ(1001); mt2.peaks.push_back(make_pair(680.4, &p2_12)); Peak1D p1_13; p1_13.setIntensity(7.38493077109f); p1_13.setMZ(1000); mt1.peaks.push_back(make_pair(680.7, &p1_13)); Peak1D p2_13; p2_13.setIntensity(1.84623269277f); p2_13.setMZ(1001); mt2.peaks.push_back(make_pair(680.7, &p2_13)); Peak1D p1_14; p1_14.setIntensity(6.68216169129f); p1_14.setMZ(1000); mt1.peaks.push_back(make_pair(681, &p1_14)); Peak1D p2_14; p2_14.setIntensity(1.67054042282f); p2_14.setMZ(1001); mt2.peaks.push_back(make_pair(681, &p2_14)); Peak1D p1_15; p1_15.setIntensity(5.80919229659f); p1_15.setMZ(1000); mt1.peaks.push_back(make_pair(681.3, &p1_15)); Peak1D p2_15; p2_15.setIntensity(1.45229807415f); p2_15.setMZ(1001); mt2.peaks.push_back(make_pair(681.3, &p2_15)); Peak1D p1_16; p1_16.setIntensity(4.8522452777f); p1_16.setMZ(1000); mt1.peaks.push_back(make_pair(681.6, &p1_16)); Peak1D p2_16; p2_16.setIntensity(1.21306131943f); p2_16.setMZ(1001); mt2.peaks.push_back(make_pair(681.6, &p2_16)); Peak1D p1_17; p1_17.setIntensity(3.89401804768f); p1_17.setMZ(1000); mt1.peaks.push_back(make_pair(681.9, &p1_17)); Peak1D p2_17; p2_17.setIntensity(0.97350451192f); p2_17.setMZ(1001); mt2.peaks.push_back(make_pair(681.9, &p2_17)); Peak1D p1_18; p1_18.setIntensity(3.00248879081f); p1_18.setMZ(1000); mt1.peaks.push_back(make_pair(682.2, &p1_18)); Peak1D p2_18; p2_18.setIntensity(0.750622197703f); p2_18.setMZ(1001); mt2.peaks.push_back(make_pair(682.2, &p2_18)); Peak1D p1_19; p1_19.setIntensity(2.22429840363f); p1_19.setMZ(1000); mt1.peaks.push_back(make_pair(682.5, &p1_19)); Peak1D p2_19; p2_19.setIntensity(0.556074600906f); p2_19.setMZ(1001); mt2.peaks.push_back(make_pair(682.5, &p2_19)); Peak1D p1_20; p1_20.setIntensity(1.58318959267f); p1_20.setMZ(1000); mt1.peaks.push_back(make_pair(682.8, &p1_20)); Peak1D p2_20; p2_20.setIntensity(0.395797398167f); p2_20.setMZ(1001); mt2.peaks.push_back(make_pair(682.8, &p2_20)); Peak1D p1_21; p1_21.setIntensity(1.08268226589f); p1_21.setMZ(1000); mt1.peaks.push_back(make_pair(683.1, &p1_21)); Peak1D p2_21; p2_21.setIntensity(0.270670566473f); p2_21.setMZ(1001); mt2.peaks.push_back(make_pair(683.1, &p2_21)); mt1.updateMaximum(); mts.push_back(mt1); mt2.updateMaximum(); mts.push_back(mt2); // fix base line to 0 since we have no baseline here mts.baseline = 0.0; mts.max_trace = 0; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // setup fitter Param p; p.setValue("max_iteration", 500); EGHTraceFitter egh_trace_fitter; egh_trace_fitter.setParameters(p); egh_trace_fitter.fit(mts); double expected_sigma = 1.5; double expected_H = 10.0; double expected_x0 = 680.1; double expected_tau = 0.0; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// EGHTraceFitter* ptr = nullptr; EGHTraceFitter* nullPointer = nullptr; START_SECTION(EGHTraceFitter()) { ptr = new EGHTraceFitter(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~EGHTraceFitter()) { delete ptr; } END_SECTION START_SECTION((EGHTraceFitter(const EGHTraceFitter& other))) { EGHTraceFitter egh1(egh_trace_fitter); TEST_EQUAL(egh1.getCenter(),egh_trace_fitter.getCenter()) TEST_EQUAL(egh1.getHeight(),egh_trace_fitter.getHeight()) TEST_EQUAL(egh1.getLowerRTBound(),egh_trace_fitter.getLowerRTBound()) TEST_EQUAL(egh1.getUpperRTBound(), egh_trace_fitter.getUpperRTBound()) } END_SECTION START_SECTION((EGHTraceFitter& operator=(const EGHTraceFitter& source))) { EGHTraceFitter egh1; egh1 = egh_trace_fitter; TEST_EQUAL(egh1.getCenter(),egh_trace_fitter.getCenter()) TEST_EQUAL(egh1.getHeight(),egh_trace_fitter.getHeight()) TEST_EQUAL(egh1.getLowerRTBound(),egh_trace_fitter.getLowerRTBound()) TEST_EQUAL(egh1.getUpperRTBound(), egh_trace_fitter.getUpperRTBound()) } END_SECTION START_SECTION((void fit(FeatureFinderAlgorithmPickedHelperStructs::MassTraces& traces))) { // fit was already done before TEST_REAL_SIMILAR(egh_trace_fitter.getCenter(), expected_x0) TEST_REAL_SIMILAR(egh_trace_fitter.getHeight(), expected_H) EGHTraceFitter weighted_fitter; Param params = weighted_fitter.getDefaults(); params.setValue("weighted", "true"); weighted_fitter.setParameters(params); weighted_fitter.fit(mts); TEST_REAL_SIMILAR(weighted_fitter.getCenter(), expected_x0) TEST_REAL_SIMILAR(weighted_fitter.getHeight(), expected_H) mts[0].theoretical_int = 0.4; mts[1].theoretical_int = 0.6; weighted_fitter.fit(mts); TEST_REAL_SIMILAR(weighted_fitter.getCenter(), expected_x0) TEST_REAL_SIMILAR(weighted_fitter.getHeight(), 6.0825) } END_SECTION START_SECTION((double getLowerRTBound() const)) { TEST_REAL_SIMILAR(egh_trace_fitter.getLowerRTBound(), expected_x0 - 2.5 * expected_sigma) } END_SECTION START_SECTION((double getUpperRTBound() const)) { TEST_REAL_SIMILAR(egh_trace_fitter.getUpperRTBound(), expected_x0 + 2.5 * expected_sigma) } END_SECTION START_SECTION((double getHeight() const)) { TEST_REAL_SIMILAR(egh_trace_fitter.getHeight(), expected_H) } END_SECTION START_SECTION((double getCenter() const)) { TEST_REAL_SIMILAR(egh_trace_fitter.getCenter(), expected_x0) } END_SECTION START_SECTION((double getTau() const)) { TEST_REAL_SIMILAR(egh_trace_fitter.getTau(), expected_tau) } END_SECTION START_SECTION((double getSigma() const)) { TEST_REAL_SIMILAR(egh_trace_fitter.getSigma(), expected_sigma) } END_SECTION START_SECTION((double getValue(double rt) const)) { TEST_REAL_SIMILAR(egh_trace_fitter.getValue(expected_x0), expected_H) } END_SECTION START_SECTION((double computeTheoretical(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace& trace, Size k))) { FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt; mt.theoretical_int = 0.8; Peak1D peak; peak.setIntensity(8.0); mt.peaks.push_back(make_pair(expected_x0, &peak)); // theoretical should be expected_H * theoretical_int at position expected_x0 TEST_REAL_SIMILAR(egh_trace_fitter.computeTheoretical(mt, 0), mt.theoretical_int * expected_H) } END_SECTION START_SECTION((bool checkMaximalRTSpan(const double max_rt_span))) { // Maximum RT span in relation to extended area that the model is allowed to have // 5.0 * sigma_ > max_rt_span * region_rt_span_ double region_rt_span = mt1.peaks[mt1.peaks.size() - 1].first - mt1.peaks[0].first; double max_rt_span = 5.0 * expected_sigma/ region_rt_span; TEST_EQUAL(egh_trace_fitter.checkMaximalRTSpan(max_rt_span), false); max_rt_span -= 0.1; // accept only smaller regions TEST_EQUAL(egh_trace_fitter.checkMaximalRTSpan(max_rt_span), true); } END_SECTION START_SECTION((bool checkMinimalRTSpan(const std::pair<double, double>& rt_bounds, const double min_rt_span))) { // is // (rt_bounds.second-rt_bounds.first) < min_rt_span * 5.0 * sigma_; // Minimum RT span in relation to extended area that has to remain after model fitting. pair<double, double> rt_bounds = make_pair(0.0,4.0); double min_rt_span = 0.5; TEST_EQUAL(egh_trace_fitter.checkMinimalRTSpan(rt_bounds, min_rt_span), false) min_rt_span += 0.5; TEST_EQUAL(egh_trace_fitter.checkMinimalRTSpan(rt_bounds, min_rt_span), true) } END_SECTION START_SECTION((virtual double getArea())) { TEST_REAL_SIMILAR(egh_trace_fitter.getArea(), sqrt(2 * PI) * expected_sigma * expected_H) } END_SECTION START_SECTION((virtual String getGnuplotFormula(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace& trace, const char function_name, const double baseline, const double rt_shift))) { String formula = egh_trace_fitter.getGnuplotFormula(mts[0], 'f', 0.0, 0.0); // should look like -- f(x)= 0 + (((4.5 + 3.93096e-15 * (x - 680.1 )) > 0) ? 8 * exp(-1 * (x - 680.1)**2 / ( 4.5 + 3.93096e-15 * (x - 680.1 ))) : 0) -- TEST_EQUAL(formula.hasPrefix("f(x)= 0 + ((("), true) TEST_EQUAL(formula.hasSubstring(" )) > 0) ? "), true) TEST_EQUAL(formula.hasSubstring(" * exp(-1 * ("), true) TEST_EQUAL(formula.hasSubstring(")**2 / ( "), true) TEST_EQUAL(formula.hasSuffix(" ))) : 0)"), true) } END_SECTION START_SECTION((double getFWHM() const)) { TEST_REAL_SIMILAR(egh_trace_fitter.getFWHM(), 3.53223007592464) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GzipIfstream_test.cpp
.cpp
4,478
143
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: David Wojnar $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/GzipIfstream.h> using namespace OpenMS; /////////////////////////// START_TEST(GzipIfstream, "$Id$") GzipIfstream* ptr = nullptr; GzipIfstream* nullPointer = nullptr; START_SECTION((GzipIfstream())) ptr = new GzipIfstream; TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~GzipIfstream())) delete ptr; END_SECTION START_SECTION(GzipIfstream(const char * filename)) TEST_EXCEPTION(Exception::FileNotFound, GzipIfstream gzip2(OPENMS_GET_TEST_DATA_PATH("ThisFileDoesNotExist"))) GzipIfstream gzip(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1.gz")); TEST_EQUAL(gzip.streamEnd(), false) TEST_EQUAL(gzip.isOpen(),true) char buffer[30]; buffer[29] = '\0'; size_t len = 29; TEST_EQUAL(29, gzip.read(buffer, len)) TEST_EQUAL(String(buffer), String("Was decompression successful?")) END_SECTION START_SECTION(void open(const char *filename)) GzipIfstream gzip; TEST_EXCEPTION(Exception::FileNotFound, gzip.open(OPENMS_GET_TEST_DATA_PATH("ThisFileDoesNotExist"))) gzip.open(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1.gz")); TEST_EQUAL(gzip.streamEnd(), false) TEST_EQUAL(gzip.isOpen(),true) char buffer[30]; buffer[29] = '\0'; size_t len = 29; TEST_EQUAL(29, gzip.read(buffer, len)) TEST_EQUAL(String(buffer), String("Was decompression successful?")) END_SECTION START_SECTION(size_t read(char *s, size_t n)) //tested in open(const char * filename) GzipIfstream gzip(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1_corrupt.gz")); char buffer[30]; buffer[29] = '\0'; size_t len = 29; //gzip.updateCRC32(buffer,10); //Why does that throw a "naked" Exception instead of a ConversionError? //~ TEST_EXCEPTION(Exception::BaseException,gzip.read(&buffer[9],10)); // gzip.updateCRC32(&buffer[9],19); // TEST_EQUAL(gzip.isCorrupted(),true) GzipIfstream gzip2(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1.gz")); TEST_EQUAL(gzip2.isOpen(),true) gzip2.read(buffer, len); TEST_EQUAL(1, gzip2.read(buffer,10)); TEST_EQUAL(gzip2.isOpen(), false) TEST_EQUAL(gzip2.streamEnd(),true) gzip2.open(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1_corrupt.gz")); //gzip2.updateCRC32(buffer,(size_t)30); //TEST_EQUAL(gzip2.isCorrupted(),true ) gzip2.close(); TEST_EQUAL(gzip2.isOpen(), false) TEST_EQUAL(gzip2.streamEnd(),true) TEST_EXCEPTION(Exception::IllegalArgument, gzip2.read(buffer,10)) gzip2.close(); TEST_EQUAL(gzip2.isOpen(), false) TEST_EQUAL(gzip2.streamEnd(),true) TEST_EXCEPTION(Exception::IllegalArgument, gzip2.read(buffer,10)) gzip2.open(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1.gz")); TEST_EQUAL(5, gzip2.read(buffer, 5)) // gzip2.updateCRC32(buffer,5); TEST_EQUAL(5, gzip2.read(&buffer[5], 5)) //gzip2.updateCRC32(&buffer[5],5); TEST_EQUAL(5, gzip2.read(&buffer[10], 5)) // gzip2.updateCRC32(&buffer[10],5); TEST_EQUAL(5, gzip2.read(&buffer[15], 5)) // gzip2.updateCRC32(&buffer[15],5); TEST_EQUAL(5, gzip2.read(&buffer[20], 5)) // gzip2.updateCRC32(&buffer[20],5); TEST_EQUAL(4, gzip2.read(&buffer[25], 4)) // gzip2.updateCRC32(&buffer[25],4); char end_of_file[1]; TEST_EQUAL(1,gzip2.read(end_of_file,2)) // gzip2.updateCRC32(end_of_file,1); TEST_EQUAL(gzip2.streamEnd(),true) buffer[29]= '\0'; // TEST_EQUAL(gzip2.isCorrupted(),false) TEST_EQUAL(String(buffer), String("Was decompression successful?")) END_SECTION START_SECTION(void close()) //tested in read NOT_TESTABLE END_SECTION START_SECTION(bool streamEnd() const ) //!!!tested in open(const char * filename) and read NOT_TESTABLE END_SECTION START_SECTION(bool isOpen() const) //tested in open(const char * filename) and read NOT_TESTABLE END_SECTION /* (updateCRC32(char* s, size_t n)) //tested in open(const char * filename) and read _TESTABLE _SECTION _SECTION(isCorrupted()) //tested in open(const char * filename) and read TESTABLE _SECTION*/ ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CrossValidation_test.cpp
.cpp
8,371
254
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Justin Sing $ // $Authors: Justin Sing $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/ML/CROSSVALIDATION/CrossValidation.h> #include <vector> #include <cmath> #include <limits> using namespace OpenMS; using std::vector; START_TEST(CrossValidation, "$Id$") // --- makeKFolds -------------------------------------------------------------- START_SECTION(makeKFolds basic and edge cases) { // Basic: n=5, K=2 -> round-robin [0,2,4], [1,3] { const auto folds = CrossValidation::makeKFolds(5, 2); TEST_EQUAL(folds.size(), 2); TEST_EQUAL(folds[0].size(), 3); TEST_EQUAL(folds[1].size(), 2); TEST_EQUAL(folds[0][0], 0); TEST_EQUAL(folds[0][1], 2); TEST_EQUAL(folds[0][2], 4); TEST_EQUAL(folds[1][0], 1); TEST_EQUAL(folds[1][1], 3); } // K > n gets clamped to n (LOO-like singletons) { const auto folds = CrossValidation::makeKFolds(5, 7); TEST_EQUAL(folds.size(), 5); for (Size i = 0; i < folds.size(); ++i) { TEST_EQUAL(folds[i].size(), 1); TEST_EQUAL(folds[i][0], i); } } // Exactly one sample, K==1 → single fold holding {0} { const auto folds = CrossValidation::makeKFolds(1, 1); TEST_EQUAL(folds.size(), 1); TEST_EQUAL(folds[0].size(), 1); TEST_EQUAL(folds[0][0], 0); } // K > n gets clamped to n (still a single fold with {0}) { const auto folds = CrossValidation::makeKFolds(1, 5); TEST_EQUAL(folds.size(), 1); TEST_EQUAL(folds[0].size(), 1); TEST_EQUAL(folds[0][0], 0); } // Invalid inputs TEST_EXCEPTION(Exception::InvalidValue, CrossValidation::makeKFolds(0, 1)); // n==0 TEST_EXCEPTION(Exception::InvalidValue, CrossValidation::makeKFolds(5, 0)); // K==0 } END_SECTION // --- gridSearch1D: best candidate selection --------------------------------- START_SECTION(gridSearch1D selects the true best candidate by score) { // Candidates around the optimum 0.5 const vector<double> cands{0.2, 0.5, 0.8}; // Any deterministic folds; content does not change the score logic here const auto folds = CrossValidation::makeKFolds(6, 3); // [[0,3],[1,4],[2,5]] // Train/eval: append |cand - 0.5| per held-out sample (constant error per sample) auto train_eval = [](double cand, const vector<vector<Size>>& flds, vector<double>& abs_errs) { const double e = std::fabs(cand - 0.5); for (const auto& fold : flds) { for (Size idx : fold) { (void)idx; abs_errs.push_back(e); } } }; // Score: mean of abs_errs auto score = [](const vector<double>& errs) -> double { double s = 0.0; for (double v : errs) s += v; return errs.empty() ? std::numeric_limits<double>::infinity() : s / errs.size(); }; const auto result = CrossValidation::gridSearch1D( cands.begin(), cands.end(), folds, train_eval, score); TEST_REAL_SIMILAR(result.first, 0.5); // best candidate TEST_REAL_SIMILAR(result.second, 0.0); // zero error at optimum } END_SECTION // --- gridSearch1D: tie-breaking policies ------------------------------------ START_SECTION(gridSearch1D tie-breaking (PreferLarger / PreferSmaller / PreferAny)) { const vector<double> cands{0.4, 0.6}; // symmetric around 0.5 -> equal scores const auto folds = CrossValidation::makeKFolds(4, 2); auto train_eval = [](double cand, const vector<vector<Size>>& flds, vector<double>& abs_errs) { const double e = std::fabs(cand - 0.5); // 0.1 for both for (const auto& fold : flds) for (Size idx : fold) { (void)idx; abs_errs.push_back(e); } }; auto score = [](const vector<double>& errs) { double s = 0.0; for (double v : errs) s += v; return s / errs.size(); }; // PreferLarger: picks 0.6 on tie { const auto [cand, sc] = CrossValidation::gridSearch1D( cands.begin(), cands.end(), folds, train_eval, score, 1e-12, CrossValidation::CandidateTieBreak::PreferLarger); TEST_REAL_SIMILAR(cand, 0.6); TEST_REAL_SIMILAR(sc, 0.1); } // PreferSmaller: picks 0.4 on tie { const auto [cand, sc] = CrossValidation::gridSearch1D( cands.begin(), cands.end(), folds, train_eval, score, 1e-12, CrossValidation::CandidateTieBreak::PreferSmaller); TEST_REAL_SIMILAR(cand, 0.4); TEST_REAL_SIMILAR(sc, 0.1); } // PreferAny: keeps first encountered (0.4) { const auto [cand, sc] = CrossValidation::gridSearch1D( cands.begin(), cands.end(), folds, train_eval, score, 1e-12, CrossValidation::CandidateTieBreak::PreferAny); TEST_REAL_SIMILAR(cand, 0.4); TEST_REAL_SIMILAR(sc, 0.1); } } END_SECTION // --- gridSearch1D: tie tolerance behavior ----------------------------------- START_SECTION(gridSearch1D respects tie tolerance) { // First candidate is within tie tolerance to perfect optimum; second is exact optimum. const double near = 0.5 - 5e-13; // |error| = 5e-13 const vector<double> cands{near, 0.5}; const auto folds = CrossValidation::makeKFolds(3, 3); auto train_eval = [](double cand, const vector<vector<Size>>& flds, vector<double>& abs_errs) { const double e = std::fabs(cand - 0.5); for (const auto& fold : flds) for (Size idx : fold) { (void)idx; abs_errs.push_back(e); } }; auto score = [](const vector<double>& errs) { double s = 0.0; for (double v : errs) s += v; return s / errs.size(); }; // With default tie_tol=1e-12, (5e-13 vs 0) are considered a tie → PreferLarger picks 0.5 { const auto [cand, sc] = CrossValidation::gridSearch1D( cands.begin(), cands.end(), folds, train_eval, score); TEST_REAL_SIMILAR(cand, 0.5); TEST_REAL_SIMILAR(sc, 0.0); } // If we tighten tie_tol below 5e-13, the smaller score (0.0) must win regardless of tie-break policy { const auto [cand, sc] = CrossValidation::gridSearch1D( cands.begin(), cands.end(), folds, train_eval, score, 1e-13, CrossValidation::CandidateTieBreak::PreferSmaller); TEST_REAL_SIMILAR(cand, 0.5); TEST_REAL_SIMILAR(sc, 0.0); } } END_SECTION // --- gridSearch1D: works with single-sample LOO (n==1) ----------------------- START_SECTION(gridSearch1D works with single-sample LOO (n==1)) { const std::vector<double> cands{0.2, 0.5}; const auto folds = CrossValidation::makeKFolds(1, 1); // [[0]] // Append one error per held-out idx (here exactly one) auto train_eval = [](double cand, const std::vector<std::vector<Size>>& flds, std::vector<double>& abs_errs) { const double e = std::fabs(cand - 0.3); // optimum at cand=0.3 for (const auto& fold : flds) for (Size idx : fold) { (void)idx; abs_errs.push_back(e); } }; // Mean absolute error auto score = [](const std::vector<double>& errs) -> double { double s = 0.0; for (double v : errs) s += v; return errs.empty() ? std::numeric_limits<double>::infinity() : s / errs.size(); }; const auto [best_cand, best_score] = CrossValidation::gridSearch1D(cands.begin(), cands.end(), folds, train_eval, score); TEST_REAL_SIMILAR(best_cand, 0.2); // closer to 0.3 than 0.5 TEST_REAL_SIMILAR(best_score, std::fabs(0.2 - 0.3)); } END_SECTION // --- gridSearch1D: empty candidate range throws ----------------------------- START_SECTION(gridSearch1D throws on empty candidate range) { const vector<double> empty; const auto folds = CrossValidation::makeKFolds(3, 3); auto train_eval = [](double /*cand*/, const vector<vector<Size>>& /*flds*/, vector<double>& /*abs_errs*/) {}; auto score = [](const vector<double>& errs) { return errs.empty() ? std::numeric_limits<double>::infinity() : errs.front(); }; TEST_EXCEPTION(Exception::InvalidRange, CrossValidation::gridSearch1D(empty.begin(), empty.end(), folds, train_eval, score)); } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DRange_test.cpp
.cpp
14,835
535
// 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/DRange.h> #include <unordered_set> #include <unordered_map> ///////////////////////////////////////////////////////////// using namespace OpenMS; START_TEST(DRange<D>, "$id$") ///////////////////////////////////////////////////////////// //do not modify these points, they are used in many tests DPosition<2> p1,p2,p3,one,two; p1[0]=-1.0f; p1[1]=-2.0f; p2[0]=3.0f; p2[1]=4.0f; p3[0]=-10.0f; p3[1]=20.0f; one[0]=1; one[1]=1; two[0]=2; two[1]=2; //do not modify these points, they are used in many tests std::cout.precision(writtenDigits<>(double())); std::cerr.precision(writtenDigits<>(double())); DRange<2>* ptr = nullptr; DRange<2>* nullPointer = nullptr; START_SECTION(DRange()) ptr = new DRange<2>; TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~DRange()) delete ptr; END_SECTION START_SECTION(DRange(const PositionType& lower, const PositionType& upper)) DRange<2> r(p1,p2); TEST_REAL_SIMILAR(r.minPosition()[0],-1.0f); TEST_REAL_SIMILAR(r.minPosition()[1],-2.0f); TEST_REAL_SIMILAR(r.maxPosition()[0],3.0f); TEST_REAL_SIMILAR(r.maxPosition()[1],4.0f); END_SECTION //do not modify this range, it is used in many tests DRange<2> r(p1,p2); //do not modify this range, it is used in many tests START_SECTION(DRange(const DRange& range)) DRange<2> r2(r); TEST_REAL_SIMILAR(r2.minPosition()[0],-1.0f); TEST_REAL_SIMILAR(r2.minPosition()[1],-2.0f); TEST_REAL_SIMILAR(r2.maxPosition()[0],3.0f); TEST_REAL_SIMILAR(r2.maxPosition()[1],4.0f); END_SECTION START_SECTION(DRange(const Base& range)) Internal::DIntervalBase<2> ib(r); DRange<2> r2(ib); TEST_REAL_SIMILAR(r2.minPosition()[0],-1.0f); TEST_REAL_SIMILAR(r2.minPosition()[1],-2.0f); TEST_REAL_SIMILAR(r2.maxPosition()[0],3.0f); TEST_REAL_SIMILAR(r2.maxPosition()[1],4.0f); END_SECTION START_SECTION(DRange& operator=(const Base& rhs)) Internal::DIntervalBase<2> ib(r); DRange<2> r2; r2 = ib; TEST_REAL_SIMILAR(r2.minPosition()[0],-1.0f); TEST_REAL_SIMILAR(r2.minPosition()[1],-2.0f); TEST_REAL_SIMILAR(r2.maxPosition()[0],3.0f); TEST_REAL_SIMILAR(r2.maxPosition()[1],4.0f); END_SECTION START_SECTION(DRange& operator=(const DRange& rhs)) DRange<2> r2; r2 = r; TEST_REAL_SIMILAR(r2.minPosition()[0],-1.0f); TEST_REAL_SIMILAR(r2.minPosition()[1],-2.0f); TEST_REAL_SIMILAR(r2.maxPosition()[0],3.0f); TEST_REAL_SIMILAR(r2.maxPosition()[1],4.0f); END_SECTION START_SECTION(DRange(CoordinateType minx, CoordinateType miny, CoordinateType maxx, CoordinateType maxy)) DRange<2> r2(1.0f,2.0f,3.0f,4.0f); TEST_REAL_SIMILAR(r2.minPosition()[0],1.0f); TEST_REAL_SIMILAR(r2.minPosition()[1],2.0f); TEST_REAL_SIMILAR(r2.maxPosition()[0],3.0f); TEST_REAL_SIMILAR(r2.maxPosition()[1],4.0f); DRange<2> r {2, 3, -2, -3}; // min > max TEST_EQUAL(r.minPosition(), DPosition<2>(-2, -3)) TEST_EQUAL(r.maxPosition(), DPosition<2>(2, 3)) END_SECTION START_SECTION(bool operator == (const DRange& rhs) const ) DRange<2> r2(r); TEST_EQUAL(r==r2,true); r2.setMinX(0.0f); TEST_EQUAL(r==r2,false); r2.setMinX(r.minPosition()[0]); TEST_EQUAL(r==r2,true); r2.setMaxY(0.0f); TEST_EQUAL(r==r2,false); r2.setMaxY(r.maxPosition()[1]); TEST_EQUAL(r==r2,true); END_SECTION START_SECTION(bool operator == (const Base& rhs) const ) Internal::DIntervalBase<2> r2(r); TEST_EQUAL(r==r2,true); r2.setMinX(0.0f); TEST_EQUAL(r==r2,false); r2.setMinX(r.minPosition()[0]); TEST_EQUAL(r==r2,true); r2.setMaxY(0.0f); TEST_EQUAL(r==r2,false); r2.setMaxY(r.maxPosition()[1]); TEST_EQUAL(r==r2,true); END_SECTION START_SECTION(bool encloses(const PositionType& position) const) DRange<2> r2(p1,p2); DPosition<2> p; p[0]=0.0f; p[1]=0.0f; TEST_EQUAL(r2.encloses(p),true); p[0]=-3.0f; p[1]=-3.0f; TEST_EQUAL(r2.encloses(p),false); p[0]=-3.0f; p[1]=0.0f; TEST_EQUAL(r2.encloses(p),false); p[0]=0.0f; p[1]=-3.0f; TEST_EQUAL(r2.encloses(p),false); p[0]=-3.0f; p[1]=5.0f; TEST_EQUAL(r2.encloses(p),false); p[0]=0.0f; p[1]=5.0f; TEST_EQUAL(r2.encloses(p),false); p[0]=5.0f; p[1]=5.0f; TEST_EQUAL(r2.encloses(p),false); p[0]=5.0f; p[1]=0.0f; TEST_EQUAL(r2.encloses(p),false); p[0]=5.0f; p[1]=-3.0f; TEST_EQUAL(r2.encloses(p),false); END_SECTION START_SECTION(DRangeIntersection intersects(const DRange& range) const) DRange<2> r2(p1,p2); DRange<2> r3(r2); TEST_EQUAL(r2.intersects(r3),DRange<2>::Inside) r3.setMaxX(10.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Intersects) r3.setMax(r2.maxPosition()+one); TEST_EQUAL(r2.intersects(r3),DRange<2>::Intersects) r3.setMin(r2.maxPosition()+one); r3.setMax(r2.maxPosition()+two); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMin(r2.minPosition()); r3.setMinX(10.0f); r3.setMax(r3.minPosition()+one); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(-10.0f); r3.setMinY(-10.0f); r3.setMax(r3.minPosition()+one); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(-10.0f); r3.setMinY(-10.0f); r3.setMaxX(0.0f); r3.setMaxY(-9.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(-10.0f); r3.setMinY(-10.0f); r3.setMaxX(10.0f); r3.setMaxY(-9.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(-10.0f); r3.setMinY(0.0f); r3.setMaxX(-9.0f); r3.setMaxY(1.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(-10.0f); r3.setMinY(10.0f); r3.setMax(r3.minPosition()+one); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(-10.0f); r3.setMinY(0.0f); r3.setMaxX(-9.0f); r3.setMaxY(10.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(9.0f); r3.setMinY(0.0f); r3.setMaxX(10.0f); r3.setMaxY(10.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(9.0f); r3.setMinY(0.0f); r3.setMaxX(10.0f); r3.setMaxY(10.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(9.0f); r3.setMinY(-5.0f); r3.setMaxX(10.0f); r3.setMaxY(0.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(9.0f); r3.setMinY(-5.0f); r3.setMaxX(10.0f); r3.setMaxY(5.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Disjoint) r3.setMinX(-5.0f); r3.setMinY(-5.0f); r3.setMaxX(0.0f); r3.setMaxY(0.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Intersects) r3.setMinX(-5.0f); r3.setMinY(-5.0f); r3.setMaxX(5.0f); r3.setMaxY(0.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Intersects) r3.setMinX(-5.0f); r3.setMinY(-5.0f); r3.setMaxX(5.0f); r3.setMaxY(5.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Intersects) r3.setMinX(0.0f); r3.setMinY(-5.0f); r3.setMaxX(0.0f); r3.setMaxY(0.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Intersects) r3.setMinX(0.0f); r3.setMinY(-5.0f); r3.setMaxX(5.0f); r3.setMaxY(0.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Intersects) r3.setMinX(0.0f); r3.setMinY(-5.0f); r3.setMaxX(5.0f); r3.setMaxY(5.0f); TEST_EQUAL(r2.intersects(r3),DRange<2>::Intersects) END_SECTION START_SECTION(bool isIntersected(const DRange& range) const) DRange<2> r2(p1,p2); DRange<2> r3(r2); TEST_EQUAL(r2.isIntersected(r3),true) r3.setMaxX(10.0f); TEST_EQUAL(r2.isIntersected(r3),true) r3.setMax(r2.maxPosition()+one); TEST_EQUAL(r2.isIntersected(r3),true) r3.setMin(r2.maxPosition()+one); r3.setMax(r2.maxPosition()+two); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMin(r2.minPosition()); r3.setMinX(10.0f); r3.setMax(r3.minPosition()+one); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(-10.0f); r3.setMinY(-10.0f); r3.setMax(r3.minPosition()+one); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(-10.0f); r3.setMinY(-10.0f); r3.setMaxX(0.0f); r3.setMaxY(-9.0f); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(-10.0f); r3.setMinY(-10.0f); r3.setMaxX(10.0f); r3.setMaxY(-9.0f); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(-10.0f); r3.setMinY(0.0f); r3.setMaxX(-9.0f); r3.setMaxY(1.0f); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(-10.0f); r3.setMinY(10.0f); r3.setMax(r3.minPosition()+one); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(-10.0f); r3.setMinY(0.0f); r3.setMaxX(-9.0f); r3.setMaxY(10.0f); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(9.0f); r3.setMinY(0.0f); r3.setMaxX(10.0f); r3.setMaxY(10.0f); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(9.0f); r3.setMinY(0.0f); r3.setMaxX(10.0f); r3.setMaxY(10.0f); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(9.0f); r3.setMinY(-5.0f); r3.setMaxX(10.0f); r3.setMaxY(0.0f); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(9.0f); r3.setMinY(-5.0f); r3.setMaxX(10.0f); r3.setMaxY(5.0f); TEST_EQUAL(r2.isIntersected(r3),false) r3.setMinX(-5.0f); r3.setMinY(-5.0f); r3.setMaxX(0.0f); r3.setMaxY(0.0f); TEST_EQUAL(r2.isIntersected(r3),true) r3.setMinX(-5.0f); r3.setMinY(-5.0f); r3.setMaxX(5.0f); r3.setMaxY(0.0f); TEST_EQUAL(r2.isIntersected(r3),true) r3.setMinX(-5.0f); r3.setMinY(-5.0f); r3.setMaxX(5.0f); r3.setMaxY(5.0f); TEST_EQUAL(r2.isIntersected(r3),true) r3.setMinX(0.0f); r3.setMinY(-5.0f); r3.setMaxX(0.0f); r3.setMaxY(0.0f); TEST_EQUAL(r2.isIntersected(r3),true) r3.setMinX(0.0f); r3.setMinY(-5.0f); r3.setMaxX(5.0f); r3.setMaxY(0.0f); TEST_EQUAL(r2.isIntersected(r3),true) r3.setMinX(0.0f); r3.setMinY(-5.0f); r3.setMaxX(5.0f); r3.setMaxY(5.0f); TEST_EQUAL(r2.isIntersected(r3),true) END_SECTION START_SECTION(DRange united(const DRange<D>& other_range) const) DRange<2> r2(p1,p2); DRange<2> r3(r2); TEST_EQUAL(r2 == r2.united(r3), true) TEST_EQUAL(r3 == r2.united(r3), true) TEST_EQUAL(r2 == r3.united(r2), true) TEST_EQUAL(r3 == r3.united(r2), true) r3.setMin(r2.maxPosition()+one); r3.setMax(r2.maxPosition()+two); DRange<2> r4; r4.setMin(r2.minPosition()); r4.setMax(r3.maxPosition()); TEST_EQUAL(r2.united(r3) == r4, true); TEST_EQUAL(r3.united(r2) == r4, true); END_SECTION START_SECTION(bool encloses(CoordinateType x, CoordinateType y) const) DRange<2> r2(p1,p2); TEST_EQUAL(r2.encloses(0.0f,0.0f),true); TEST_EQUAL(r2.encloses(-3.0f,-3.0f),false); TEST_EQUAL(r2.encloses(-3.0f,0.0f),false); TEST_EQUAL(r2.encloses(0.0f,-3.0f),false); TEST_EQUAL(r2.encloses(-3.0f,5.0f),false); TEST_EQUAL(r2.encloses(0.0f,5.0f),false); TEST_EQUAL(r2.encloses(5.0f,5.0f),false); TEST_EQUAL(r2.encloses(5.0f,0.0f),false); TEST_EQUAL(r2.encloses(5.0f,-3.0f),false); END_SECTION START_SECTION(DRange<D>& extend(double factor)) DRange<2> r(p1,p2); /* p1[0]=-1.0f; p1[1]=-2.0f; p2[0]=3.0f; p2[1]=4.0f; */ TEST_EXCEPTION(Exception::InvalidParameter, r.extend(-0.01)) auto other = r.extend(2.0); TEST_REAL_SIMILAR(r.minPosition()[0],-3.0f); TEST_REAL_SIMILAR(r.maxPosition()[0], 5.0f); TEST_REAL_SIMILAR(r.minPosition()[1],-5.0f); TEST_REAL_SIMILAR(r.maxPosition()[1], 7.0f); TEST_REAL_SIMILAR(other.minPosition()[0], -3.0f); TEST_REAL_SIMILAR(other.maxPosition()[0], 5.0f); END_SECTION START_SECTION(DRange<D>& extend(typename Base::PositionType addition)) DRange<2> r(p1, p2); /* p1[0]=-1.0f; p1[1]=-2.0f; p2[0]=3.0f; p2[1]=4.0f; */ auto other = r.extend({2.0, 3.0}); TEST_REAL_SIMILAR(r.minPosition()[0], -2.0f); TEST_REAL_SIMILAR(r.maxPosition()[0], 4.0f); TEST_REAL_SIMILAR(r.minPosition()[1], -3.5f); TEST_REAL_SIMILAR(r.maxPosition()[1], 5.5f); TEST_REAL_SIMILAR(other.minPosition()[0], -2.0f); TEST_REAL_SIMILAR(other.maxPosition()[0], 4.0f); // test shrinking to a single point r.extend({-200.0, 0.0}); TEST_REAL_SIMILAR(r.minPosition()[0], 1.0f); TEST_REAL_SIMILAR(r.maxPosition()[0], 1.0f); TEST_REAL_SIMILAR(r.minPosition()[1], -3.5f); TEST_REAL_SIMILAR(r.maxPosition()[1], 5.5f); END_SECTION START_SECTION(DRange<D>& ensureMinSpan(typename Base::PositionType min_span)) DRange<2> r(-0.1, 10, 0.1, 20); r.ensureMinSpan({1.0, 3.0}); TEST_REAL_SIMILAR(r.minPosition()[0], -0.5f); TEST_REAL_SIMILAR(r.maxPosition()[0], 0.5f); TEST_REAL_SIMILAR(r.minPosition()[1], 10.0f); TEST_REAL_SIMILAR(r.maxPosition()[1], 20.0f); END_SECTION START_SECTION(DRange<D>& swapDimensions()) DRange<2> r(p1, p2); /* p1[0]=-1.0f; p1[1]=-2.0f; p2[0]=3.0f; p2[1]=4.0f; */ r.swapDimensions(); TEST_REAL_SIMILAR(r.minPosition()[0], -2.0f); TEST_REAL_SIMILAR(r.maxPosition()[0], 4.0f); TEST_REAL_SIMILAR(r.minPosition()[1], -1.0f); TEST_REAL_SIMILAR(r.maxPosition()[1], 3.0f); END_SECTION START_SECTION(void pullIn(DPosition<D>& point) const) { DRange<2> r({1,2}, {3,4}); DPosition<2> p_out_left{0, 0}; r.pullIn(p_out_left); TEST_REAL_SIMILAR(p_out_left.getX(), 1) TEST_REAL_SIMILAR(p_out_left.getY(), 2) DPosition<2> p_out_right {5, 5}; r.pullIn(p_out_right); TEST_REAL_SIMILAR(p_out_right.getX(), 3) TEST_REAL_SIMILAR(p_out_right.getY(), 4) DPosition<2> p_in {2, 3}; r.pullIn(p_in); TEST_REAL_SIMILAR(p_in.getX(), 2) TEST_REAL_SIMILAR(p_in.getY(), 3) } END_SECTION START_SECTION(([EXTRA] std::hash<DRange<D>>)) { // Test that equal objects have equal hashes DRange<2> r1(1.0, 2.0, 3.0, 4.0); DRange<2> r2(1.0, 2.0, 3.0, 4.0); DRange<2> r3(0.0, 0.0, 5.0, 5.0); std::hash<DRange<2>> hasher; TEST_EQUAL(r1 == r2, true) TEST_EQUAL(hasher(r1), hasher(r2)) // Different ranges should (very likely) have different hashes TEST_EQUAL(r1 == r3, false) TEST_NOT_EQUAL(hasher(r1), hasher(r3)) // Test use in unordered_set std::unordered_set<DRange<2>> range_set; range_set.insert(r1); range_set.insert(r2); // duplicate, should not increase size range_set.insert(r3); TEST_EQUAL(range_set.size(), 2) TEST_EQUAL(range_set.count(r1), 1) TEST_EQUAL(range_set.count(r3), 1) // Test use in unordered_map std::unordered_map<DRange<2>, std::string> range_map; range_map[r1] = "first"; range_map[r3] = "second"; TEST_EQUAL(range_map.size(), 2) TEST_EQUAL(range_map[r1], "first") TEST_EQUAL(range_map[r2], "first") // r2 == r1, same key TEST_EQUAL(range_map[r3], "second") // Test with different dimensions (DRange<1>) DRange<1> r1d_a, r1d_b; r1d_a.setMin(DPosition<1>(1.0)); r1d_a.setMax(DPosition<1>(5.0)); r1d_b.setMin(DPosition<1>(1.0)); r1d_b.setMax(DPosition<1>(5.0)); std::hash<DRange<1>> hasher1d; TEST_EQUAL(r1d_a == r1d_b, true) TEST_EQUAL(hasher1d(r1d_a), hasher1d(r1d_b)) std::unordered_set<DRange<1>> range_set_1d; range_set_1d.insert(r1d_a); TEST_EQUAL(range_set_1d.count(r1d_b), 1) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++