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/MzDataValidator_test.cpp
.cpp
1,338
51
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/VALIDATORS/MzDataValidator.h> /////////////////////////// #include <OpenMS/FORMAT/ControlledVocabulary.h> using namespace OpenMS; using namespace OpenMS::Internal; using namespace std; START_TEST(MzDataValidator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CVMappings mapping; ControlledVocabulary cv; MzDataValidator* ptr = nullptr; MzDataValidator* nullPointer = nullptr; START_SECTION((MzDataValidator(const CVMappings &mapping, const ControlledVocabulary &cv))) { ptr = new MzDataValidator(mapping, cv); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~MzDataValidator()) { delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MultiplexFilteringCentroided_test.cpp
.cpp
4,394
96
// 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/MultiplexFilteringCentroided.h> #include <OpenMS/FEATUREFINDER/MultiplexFilteredMSExperiment.h> #include <OpenMS/FORMAT/MzMLFile.h> using namespace OpenMS; START_TEST(MultiplexFilteringCentroided, "$Id$") // read data MSExperiment exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MultiplexFiltering.mzML"), exp); exp.updateRanges(); // pick data 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<PeakPickerHiRes::PeakBoundary> boundaries; std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > boundaries_exp_s; std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > boundaries_exp_c; MSExperiment exp_picked; picker.pickExperiment(exp, exp_picked, boundaries_exp_s, boundaries_exp_c); // set parameters int charge_min = 1; int charge_max = 4; int isotopes_per_peptide_min = 3; int isotopes_per_peptide_max = 6; double intensity_cutoff = 10.0; double rt_band = 3; double mz_tolerance = 40; bool mz_tolerance_unit = true; // ppm (true), Da (false) double peptide_similarity = 0.8; double averagine_similarity = 0.75; double averagine_similarity_scaling = 0.75; String averagine_type="peptide"; // construct list of peak patterns MultiplexDeltaMasses shifts1; shifts1.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(0,"no_label")); shifts1.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(8.0443702794,"Arg8")); MultiplexDeltaMasses shifts2; shifts2.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(0,"no_label")); MultiplexDeltaMasses::LabelSet label_set; label_set.insert("Arg8"); label_set.insert("Arg8"); shifts2.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(2*8.0443702794,label_set)); std::vector<MultiplexIsotopicPeakPattern> patterns; for (int c = charge_max; c >= charge_min; --c) { MultiplexIsotopicPeakPattern pattern1(c, isotopes_per_peptide_max, shifts1, 0); patterns.push_back(pattern1); MultiplexIsotopicPeakPattern pattern2(c, isotopes_per_peptide_max, shifts2, 1); patterns.push_back(pattern2); } MultiplexFilteringCentroided* nullPointer = nullptr; MultiplexFilteringCentroided* ptr; START_SECTION(MultiplexFilteringCentroided(const MSExperiment& exp_picked, const std::vector<MultiplexIsotopicPeakPattern>& patterns, int isotopes_per_peptide_min, int isotopes_per_peptide_max, double intensity_cutoff, double rt_band, double mz_tolerance, bool mz_tolerance_unit, double peptide_similarity, double averagine_similarity, double averagine_similarity_scaling, String averagine_type="peptide")) MultiplexFilteringCentroided filtering(exp_picked, patterns, isotopes_per_peptide_min, isotopes_per_peptide_max, intensity_cutoff, rt_band, mz_tolerance, mz_tolerance_unit, peptide_similarity, averagine_similarity, averagine_similarity_scaling, averagine_type); ptr = new MultiplexFilteringCentroided(exp_picked, patterns, isotopes_per_peptide_min, isotopes_per_peptide_max, intensity_cutoff, rt_band, mz_tolerance, mz_tolerance_unit, peptide_similarity, averagine_similarity, averagine_similarity_scaling, averagine_type); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION MultiplexFilteringCentroided filtering(exp_picked, patterns, isotopes_per_peptide_min, isotopes_per_peptide_max, intensity_cutoff, rt_band, mz_tolerance, mz_tolerance_unit, peptide_similarity, averagine_similarity, averagine_similarity_scaling, averagine_type); START_SECTION(std::vector<MultiplexFilterResult> filter()) std::vector<MultiplexFilteredMSExperiment> results = filtering.filter(); TEST_EQUAL(results[0].size(), 0); TEST_EQUAL(results[1].size(), 0); TEST_EQUAL(results[2].size(), 0); TEST_EQUAL(results[3].size(), 0); TEST_EQUAL(results[4].size(), 4); TEST_EQUAL(results[5].size(), 4); TEST_EQUAL(results[6].size(), 4); TEST_EQUAL(results[7].size(), 0); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MzDataFile_test.cpp
.cpp
36,544
858
// 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/MzDataFile.h> #include <OpenMS/FORMAT/FileHandler.h> #include <OpenMS/KERNEL/MSExperiment.h> using namespace OpenMS; using namespace std; DRange<1> makeRange(double a, double b) { DPosition<1> pa(a), pb(b); return DRange<1>(pa, pb); } /////////////////////////// START_TEST(MzDataFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MzDataFile * ptr = nullptr; MzDataFile* nullPointer = nullptr; START_SECTION((MzDataFile())) { ptr = new MzDataFile; TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((~MzDataFile())) { delete ptr; } END_SECTION START_SECTION(const PeakFileOptions& getOptions() const) { MzDataFile file; TEST_EQUAL(file.getOptions().hasMSLevels(), false) const PeakFileOptions o = file.getOptions(); TEST_EQUAL(o.hasMSLevels(), false) } END_SECTION START_SECTION(setOptions(const PeakFileOptions & options)) { MzDataFile file; TEST_EQUAL(file.getOptions().hasMSLevels(), false) const PeakFileOptions o = file.getOptions(); PeakFileOptions options = o; options.addMSLevel(1); file.setOptions(options); TEST_EQUAL(file.getOptions().hasMSLevels(), true) } END_SECTION START_SECTION(PeakFileOptions& getOptions()) { MzDataFile 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) MzDataFile file; PeakMap e; // real test file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), e); //test DocumentIdentifier addition TEST_STRING_EQUAL(e.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData")); TEST_STRING_EQUAL(FileTypes::typeToName(e.getLoadedFileType()), "mzData"); //--------------------------------------------------------------------------- // ms-level, RT, native ID //--------------------------------------------------------------------------- TEST_EQUAL(e.size(), 3) TEST_EQUAL(e[0].getMSLevel(), 1) TEST_EQUAL(e[1].getMSLevel(), 2) TEST_EQUAL(e[2].getMSLevel(), 1) TEST_REAL_SIMILAR(e[0].getRT(), 60) TEST_REAL_SIMILAR(e[1].getRT(), 120) TEST_REAL_SIMILAR(e[2].getRT(), 180) TEST_STRING_EQUAL(e[0].getNativeID(), "spectrum=10") TEST_STRING_EQUAL(e[1].getNativeID(), "spectrum=11") TEST_STRING_EQUAL(e[2].getNativeID(), "spectrum=12") TEST_EQUAL(e[0].getType(), SpectrumSettings::SpectrumType::UNKNOWN) //--------------------------------------------------------------------------- //meta data array meta data //--------------------------------------------------------------------------- TEST_EQUAL(e[0].getFloatDataArrays()[0].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[0].getFloatDataArrays()[0].getMetaValue("Comment"), "Area of the peak") TEST_EQUAL(e[0].getFloatDataArrays()[0].getMetaValue("comment"), "bla|comment|bla") TEST_EQUAL(e[0].getFloatDataArrays()[1].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[0].getFloatDataArrays()[1].getMetaValue("Comment"), "Full width at half max") TEST_EQUAL(e[0].getFloatDataArrays()[2].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[0].getFloatDataArrays()[2].getMetaValue("Comment"), "Left width") TEST_EQUAL(e[0].getFloatDataArrays()[3].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[0].getFloatDataArrays()[3].getMetaValue("Comment"), "Right width") TEST_EQUAL(e[0].getFloatDataArrays()[4].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[0].getFloatDataArrays()[4].getMetaValue("Comment"), "Peak charge") TEST_EQUAL(e[0].getFloatDataArrays()[5].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[0].getFloatDataArrays()[5].getMetaValue("Comment"), "Signal to noise ratio") TEST_EQUAL(e[0].getFloatDataArrays()[6].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[0].getFloatDataArrays()[6].getMetaValue("Comment"), "Correlation value") TEST_EQUAL(e[0].getFloatDataArrays()[7].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[0].getFloatDataArrays()[7].getMetaValue("Comment"), "Peak shape") //--------------------------------------------------------------------------- //precursors //--------------------------------------------------------------------------- TEST_EQUAL(e[0].getPrecursors().size(), 0) TEST_EQUAL(e[1].getPrecursors().size(), 2) TEST_EQUAL(e[2].getPrecursors().size(), 0) TEST_REAL_SIMILAR(e[1].getPrecursors()[0].getMZ(), 1.2) TEST_EQUAL(e[1].getPrecursors()[0].getCharge(), 2) TEST_REAL_SIMILAR(e[1].getPrecursors()[0].getIntensity(), 2.3f) TEST_EQUAL(e[1].getPrecursors()[0].getMetaValue("IonSelectionComment"), "selected") TEST_EQUAL(e[1].getPrecursors()[0].getActivationMethods().count(Precursor::ActivationMethod::CID), 1) TEST_REAL_SIMILAR(e[1].getPrecursors()[0].getActivationEnergy(), 3.4) TEST_EQUAL(e[1].getPrecursors()[0].getMetaValue("ActivationComment"), "active") TEST_REAL_SIMILAR(e[1].getPrecursors()[1].getMZ(), 2.2) TEST_EQUAL(e[1].getPrecursors()[1].getCharge(), 3) TEST_REAL_SIMILAR(e[1].getPrecursors()[1].getIntensity(), 3.3f) TEST_EQUAL(e[1].getPrecursors()[1].getMetaValue("IonSelectionComment"), "selected2") TEST_EQUAL(e[1].getPrecursors()[1].getActivationMethods().count(Precursor::ActivationMethod::SID), 1) TEST_REAL_SIMILAR(e[1].getPrecursors()[1].getActivationEnergy(), 4.4) TEST_EQUAL(e[1].getPrecursors()[1].getMetaValue("ActivationComment"), "active2") //--------------------------------------------------------------------------- //instrument settings //--------------------------------------------------------------------------- TEST_EQUAL(e[0].getInstrumentSettings().getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[1].getInstrumentSettings().getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[2].getInstrumentSettings().metaValueExists("URL"), false) TEST_EQUAL(e[0].getInstrumentSettings().getMetaValue("SpecComment"), "Spectrum 1") TEST_EQUAL(e[1].getInstrumentSettings().getMetaValue("SpecComment"), "Spectrum 2") TEST_EQUAL(e[2].getInstrumentSettings().metaValueExists("SpecComment"), false) TEST_EQUAL(e[0].getInstrumentSettings().getScanMode(), InstrumentSettings::ScanMode::MASSSPECTRUM) TEST_EQUAL(e[1].getInstrumentSettings().getScanMode(), InstrumentSettings::ScanMode::MASSSPECTRUM) TEST_EQUAL(e[2].getInstrumentSettings().getScanMode(), InstrumentSettings::ScanMode::SIM) TEST_EQUAL(e[0].getInstrumentSettings().getPolarity(), IonSource::Polarity::POSITIVE) TEST_EQUAL(e[1].getInstrumentSettings().getPolarity(), IonSource::Polarity::POSITIVE) TEST_EQUAL(e[2].getInstrumentSettings().getPolarity(), IonSource::Polarity::NEGATIVE) TEST_EQUAL(e[0].getInstrumentSettings().getScanWindows().size(), 0) TEST_EQUAL(e[1].getInstrumentSettings().getScanWindows().size(), 1) TEST_REAL_SIMILAR(e[1].getInstrumentSettings().getScanWindows()[0].begin, 110) TEST_REAL_SIMILAR(e[1].getInstrumentSettings().getScanWindows()[0].end, 0) TEST_EQUAL(e[2].getInstrumentSettings().getScanWindows().size(), 1) TEST_REAL_SIMILAR(e[2].getInstrumentSettings().getScanWindows()[0].begin, 100) TEST_REAL_SIMILAR(e[2].getInstrumentSettings().getScanWindows()[0].end, 140) //--------------------------------------------------------------------------- //acquisition //--------------------------------------------------------------------------- TEST_EQUAL(e[0].getAcquisitionInfo().size(), 0) ABORT_IF(!e[0].getAcquisitionInfo().empty()); TEST_EQUAL(e[1].getAcquisitionInfo().size(), 2) ABORT_IF(e[1].getAcquisitionInfo().size() != 2); TEST_EQUAL(e[1].getType(), SpectrumSettings::SpectrumType::PROFILE) TEST_EQUAL(e[1].getAcquisitionInfo().getMethodOfCombination(), "sum") TEST_EQUAL(e[1].getAcquisitionInfo()[0].getIdentifier(), "501") TEST_EQUAL(e[1].getAcquisitionInfo()[1].getIdentifier(), "502") TEST_EQUAL(e[1].getAcquisitionInfo()[0].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[1].getAcquisitionInfo()[1].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[1].getAcquisitionInfo()[0].getMetaValue("AcqComment"), "Acquisition 1") TEST_EQUAL(e[1].getAcquisitionInfo()[1].getMetaValue("AcqComment"), "Acquisition 2") TEST_EQUAL(e[2].getAcquisitionInfo().size(), 1) ABORT_IF(e[2].getAcquisitionInfo().size() != 1); TEST_EQUAL(e[2].getType(), SpectrumSettings::SpectrumType::CENTROID) TEST_EQUAL(e[2].getAcquisitionInfo().getMethodOfCombination(), "average") TEST_EQUAL(e[2].getAcquisitionInfo()[0].getIdentifier(), "601") //--------------------------------------------------------------------------- // actual peak data: // 60 : (120,100) // 120: (110,100) (120,200) (130,100) // 180: (100,100) (110,200) (120,300) (130,200) (140,100) // // meta data array values: // 0) r_value // 1) area // 2) FWHM // 3) left_width // 4) right_width // 5) charge // 5) type // 6) signal_to_noise //--------------------------------------------------------------------------- TEST_EQUAL(e[0].size(), 1) TEST_EQUAL(e[1].size(), 3) TEST_EQUAL(e[2].size(), 5) TEST_REAL_SIMILAR(e[0][0].getPosition()[0], 120) TEST_REAL_SIMILAR(e[0][0].getIntensity(), 100) TEST_REAL_SIMILAR(e[0].getFloatDataArrays()[1][0], 100) TEST_REAL_SIMILAR(e[0].getFloatDataArrays()[2][0], 100) TEST_REAL_SIMILAR(e[0].getFloatDataArrays()[4][0], 100) TEST_REAL_SIMILAR(e[0].getFloatDataArrays()[3][0], 100) TEST_EQUAL(e[0].getFloatDataArrays()[5][0], 100) TEST_REAL_SIMILAR(e[0].getFloatDataArrays()[0][0], 100) TEST_REAL_SIMILAR(e[0].getFloatDataArrays()[7][0], 100) TEST_EQUAL(e[0].getFloatDataArrays()[6][0], 100) TEST_REAL_SIMILAR(e[1][0].getPosition()[0], 110) TEST_REAL_SIMILAR(e[1][0].getIntensity(), 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[1][0], 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[2][0], 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[4][0], 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[3][0], 100) TEST_EQUAL(e[1].getFloatDataArrays()[5][0], 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[0][0], 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[7][0], 100) TEST_EQUAL(e[1].getFloatDataArrays()[6][0], 100) TEST_REAL_SIMILAR(e[1][1].getPosition()[0], 120) TEST_REAL_SIMILAR(e[1][1].getIntensity(), 200) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[1][1], 200) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[2][1], 200) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[4][1], 200) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[3][1], 200) TEST_EQUAL(e[1].getFloatDataArrays()[5][1], 200) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[0][1], 200) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[7][1], 200) TEST_EQUAL(e[1].getFloatDataArrays()[6][1], 200) TEST_REAL_SIMILAR(e[1][2].getPosition()[0], 130) TEST_REAL_SIMILAR(e[1][2].getIntensity(), 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[1][2], 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[2][2], 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[4][2], 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[3][2], 100) TEST_EQUAL(e[1].getFloatDataArrays()[5][2], 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[0][2], 100) TEST_REAL_SIMILAR(e[1].getFloatDataArrays()[7][2], 100) TEST_EQUAL(e[1].getFloatDataArrays()[6][2], 100) TEST_REAL_SIMILAR(e[2][0].getPosition()[0], 100) TEST_REAL_SIMILAR(e[2][0].getIntensity(), 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[1][0], 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[2][0], 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[4][0], 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[3][0], 100) TEST_EQUAL(e[2].getFloatDataArrays()[5][0], 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[0][0], 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[7][0], 100) TEST_EQUAL(e[2].getFloatDataArrays()[6][0], 100) TEST_REAL_SIMILAR(e[2][1].getPosition()[0], 110) TEST_REAL_SIMILAR(e[2][1].getIntensity(), 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[1][1], 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[2][1], 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[4][1], 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[3][1], 200) TEST_EQUAL(e[2].getFloatDataArrays()[5][1], 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[0][1], 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[7][1], 200) TEST_EQUAL(e[2].getFloatDataArrays()[6][1], 200) TEST_REAL_SIMILAR(e[2][2].getPosition()[0], 120) TEST_REAL_SIMILAR(e[2][2].getIntensity(), 300) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[1][2], 300) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[2][2], 300) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[4][2], 300) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[3][2], 300) TEST_EQUAL(e[2].getFloatDataArrays()[5][2], 300) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[0][2], 300) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[7][2], 300) TEST_EQUAL(e[2].getFloatDataArrays()[6][2], 300) TEST_REAL_SIMILAR(e[2][3].getPosition()[0], 130) TEST_REAL_SIMILAR(e[2][3].getIntensity(), 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[1][3], 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[2][3], 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[4][3], 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[3][3], 200) TEST_EQUAL(e[2].getFloatDataArrays()[5][3], 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[0][3], 200) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[7][3], 200) TEST_EQUAL(e[2].getFloatDataArrays()[6][3], 200) TEST_REAL_SIMILAR(e[2][4].getPosition()[0], 140) TEST_REAL_SIMILAR(e[2][4].getIntensity(), 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[1][4], 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[2][4], 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[4][4], 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[3][4], 100) TEST_EQUAL(e[2].getFloatDataArrays()[5][4], 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[0][4], 100) TEST_REAL_SIMILAR(e[2].getFloatDataArrays()[7][4], 100) TEST_EQUAL(e[2].getFloatDataArrays()[6][4], 100) //--------------------------------------------------------------------------- // accession number //--------------------------------------------------------------------------- TEST_EQUAL(e.getIdentifier(), "lsid"); //--------------------------------------------------------------------------- // source file //--------------------------------------------------------------------------- TEST_EQUAL(e.getSourceFiles().size(), 1) TEST_STRING_EQUAL(e.getSourceFiles()[0].getNameOfFile(), "MzDataFile_test_1.raw"); TEST_STRING_EQUAL(e.getSourceFiles()[0].getPathToFile(), "/share/data/"); TEST_STRING_EQUAL(e.getSourceFiles()[0].getFileType(), "MS"); TEST_STRING_EQUAL(e.getSourceFiles()[0].getChecksum(), ""); TEST_EQUAL(e.getSourceFiles()[0].getChecksumType(), SourceFile::ChecksumType::UNKNOWN_CHECKSUM); //--------------------------------------------------------------------------- // conteact list //--------------------------------------------------------------------------- TEST_EQUAL(e.getContacts().size(), 2); ABORT_IF(e.getContacts().size() != 2); TEST_EQUAL(e.getContacts()[0].getFirstName(), "John"); TEST_EQUAL(e.getContacts()[0].getLastName(), "Doe"); TEST_EQUAL(e.getContacts()[0].getInstitution(), "department 1"); TEST_EQUAL(e.getContacts()[0].getContactInfo(), "www.john.doe"); TEST_EQUAL(e.getContacts()[1].getFirstName(), "Jane"); TEST_EQUAL(e.getContacts()[1].getLastName(), "Doe"); TEST_EQUAL(e.getContacts()[1].getInstitution(), "department 2"); TEST_EQUAL(e.getContacts()[1].getContactInfo(), "www.jane.doe"); //--------------------------------------------------------------------------- // data processing //--------------------------------------------------------------------------- for (Size i = 0; i < e.size(); ++i) { TEST_EQUAL(e[i].getDataProcessing().size(), 1) TEST_EQUAL(e[i].getDataProcessing()[0]->getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e[i].getDataProcessing()[0]->getMetaValue("comment"), "ProcessingComment") TEST_EQUAL(e[i].getDataProcessing()[0]->getCompletionTime().get(), "2001-02-03 04:05:06"); TEST_EQUAL(e[i].getDataProcessing()[0]->getSoftware().getName(), "MS-X"); TEST_EQUAL(e[i].getDataProcessing()[0]->getSoftware().getVersion(), "1.0"); TEST_EQUAL(e[i].getDataProcessing()[0]->getSoftware().getMetaValue("comment"), "SoftwareComment") } //--------------------------------------------------------------------------- // instrument //--------------------------------------------------------------------------- const Instrument& inst = e.getInstrument(); TEST_EQUAL(inst.getName(), "MS-Instrument") TEST_EQUAL(inst.getVendor(), "MS-Vendor") TEST_EQUAL(inst.getModel(), "MS 1") TEST_EQUAL(inst.getCustomizations(), "tuned") TEST_EQUAL(inst.getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(inst.getMetaValue("AdditionalComment"), "Additional") TEST_EQUAL(inst.getIonSources().size(), 1) TEST_EQUAL(inst.getIonSources()[0].getIonizationMethod(), IonSource::IonizationMethod::ESI) TEST_EQUAL(inst.getIonSources()[0].getInletType(), IonSource::InletType::DIRECT) TEST_EQUAL(inst.getIonSources()[0].getPolarity(), IonSource::Polarity::NEGATIVE) TEST_EQUAL(inst.getIonSources()[0].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(inst.getIonSources()[0].getMetaValue("SourceComment"), "Source") TEST_EQUAL(inst.getIonDetectors().size(), 1) TEST_EQUAL(inst.getIonDetectors()[0].getType(), IonDetector::Type::FARADAYCUP) TEST_EQUAL(inst.getIonDetectors()[0].getAcquisitionMode(), IonDetector::AcquisitionMode::TDC) TEST_EQUAL(inst.getIonDetectors()[0].getResolution(), 0.815) TEST_EQUAL(inst.getIonDetectors()[0].getADCSamplingFrequency(), 11.22) TEST_EQUAL(inst.getIonDetectors()[0].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(inst.getIonDetectors()[0].getMetaValue("DetectorComment"), "Detector") TEST_EQUAL(inst.getMassAnalyzers().size(), 2) ABORT_IF(inst.getMassAnalyzers().size() != 2); 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::CONSTANT) TEST_EQUAL(inst.getMassAnalyzers()[0].getScanDirection(), MassAnalyzer::ScanDirection::UP) TEST_EQUAL(inst.getMassAnalyzers()[0].getScanLaw(), MassAnalyzer::ScanLaw::LINEAR) TEST_EQUAL(inst.getMassAnalyzers()[0].getReflectronState(), MassAnalyzer::ReflectronState::OFF) TEST_EQUAL(inst.getMassAnalyzers()[0].getResolution(), 22.33) TEST_EQUAL(inst.getMassAnalyzers()[0].getAccuracy(), 33.44) TEST_EQUAL(inst.getMassAnalyzers()[0].getScanRate(), 44.55) TEST_EQUAL(inst.getMassAnalyzers()[0].getScanTime(), 55.66) TEST_EQUAL(inst.getMassAnalyzers()[0].getTOFTotalPathLength(), 66.77) TEST_EQUAL(inst.getMassAnalyzers()[0].getIsolationWidth(), 77.88) TEST_EQUAL(inst.getMassAnalyzers()[0].getFinalMSExponent(), 2) TEST_EQUAL(inst.getMassAnalyzers()[0].getMagneticFieldStrength(), 88.99) TEST_EQUAL(inst.getMassAnalyzers()[0].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(inst.getMassAnalyzers()[0].getMetaValue("AnalyzerComment"), "Analyzer 1") TEST_EQUAL(inst.getMassAnalyzers()[1].getType(), MassAnalyzer::AnalyzerType::QUADRUPOLE) TEST_EQUAL(inst.getMassAnalyzers()[1].getResolutionMethod(), MassAnalyzer::ResolutionMethod::BASELINE) TEST_EQUAL(inst.getMassAnalyzers()[1].getResolutionType(), MassAnalyzer::ResolutionType::PROPORTIONAL) TEST_EQUAL(inst.getMassAnalyzers()[1].getScanDirection(), MassAnalyzer::ScanDirection::DOWN) TEST_EQUAL(inst.getMassAnalyzers()[1].getScanLaw(), MassAnalyzer::ScanLaw::EXPONENTIAL) TEST_EQUAL(inst.getMassAnalyzers()[1].getReflectronState(), MassAnalyzer::ReflectronState::ON) TEST_EQUAL(inst.getMassAnalyzers()[1].getResolution(), 12.3) TEST_EQUAL(inst.getMassAnalyzers()[1].getAccuracy(), 13.4) TEST_EQUAL(inst.getMassAnalyzers()[1].getScanRate(), 14.5) TEST_EQUAL(inst.getMassAnalyzers()[1].getScanTime(), 15.6) TEST_EQUAL(inst.getMassAnalyzers()[1].getTOFTotalPathLength(), 16.7) TEST_EQUAL(inst.getMassAnalyzers()[1].getIsolationWidth(), 17.8) TEST_EQUAL(inst.getMassAnalyzers()[1].getFinalMSExponent(), -2) TEST_EQUAL(inst.getMassAnalyzers()[1].getMagneticFieldStrength(), 18.9) TEST_EQUAL(inst.getMassAnalyzers()[1].getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(inst.getMassAnalyzers()[1].getMetaValue("AnalyzerComment"), "Analyzer 2") //--------------------------------------------------------------------------- // sample //--------------------------------------------------------------------------- TEST_EQUAL(e.getSample().getName(), "MS-Sample") TEST_EQUAL(e.getSample().getNumber(), "0-815") TEST_EQUAL(e.getSample().getState(), Sample::SampleState::GAS) TEST_EQUAL(e.getSample().getMass(), 1.01) TEST_EQUAL(e.getSample().getVolume(), 2.02) TEST_EQUAL(e.getSample().getConcentration(), 3.03) TEST_EQUAL(e.getSample().getMetaValue("URL"), "www.open-ms.de") TEST_EQUAL(e.getSample().getMetaValue("SampleComment"), "Sample") /////////////////////// TESTING SPECIAL CASES /////////////////////// //load a second time to make sure everything is re-initialized correctly PeakMap e2; file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), e2); TEST_TRUE(e == e2) //loading a minimal file containing one spectrum - with whitespaces inside the base64 data PeakMap e3; file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_3_minimal.mzData"), e3); TEST_EQUAL(e3.size(), 1) TEST_EQUAL(e3[0].size(), 3) //load one extremely long spectrum - tests CDATA splitting PeakMap e4; file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_2_long.mzData"), e4); TEST_EQUAL(e4.size(), 1) TEST_EQUAL(e4[0].size(), 997530) //load with 64 bit precision and endian conversion PeakMap e5; file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_4_64bit.mzData"), e5); TEST_EQUAL(e5.getIdentifier(), ""); TEST_EQUAL(e5.size(), 1) TEST_EQUAL(e5[0].size(), 3) TEST_REAL_SIMILAR(e5[0][0].getPosition()[0], 110) TEST_REAL_SIMILAR(e5[0][0].getIntensity(), 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[1][0], 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[2][0], 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[4][0], 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[3][0], 100) TEST_EQUAL(e5[0].getFloatDataArrays()[5][0], 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[0][0], 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[7][0], 100) TEST_EQUAL(e5[0].getFloatDataArrays()[6][0], 100) TEST_REAL_SIMILAR(e5[0][1].getPosition()[0], 120) TEST_REAL_SIMILAR(e5[0][1].getIntensity(), 200) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[1][1], 200) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[2][1], 200) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[4][1], 200) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[3][1], 200) TEST_EQUAL(e5[0].getFloatDataArrays()[5][1], 200) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[0][1], 200) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[7][1], 200) TEST_EQUAL(e5[0].getFloatDataArrays()[6][1], 200) TEST_REAL_SIMILAR(e5[0][2].getPosition()[0], 130) TEST_REAL_SIMILAR(e5[0][2].getIntensity(), 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[1][2], 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[2][2], 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[4][2], 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[3][2], 100) TEST_EQUAL(e5[0].getFloatDataArrays()[5][2], 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[0][2], 100) TEST_REAL_SIMILAR(e5[0].getFloatDataArrays()[7][2], 100) TEST_EQUAL(e5[0].getFloatDataArrays()[6][2], 100) } END_SECTION START_SECTION(([EXTRA] load with metadata - only flag)) { TOLERANCE_ABSOLUTE(0.01) MzDataFile file; file.getOptions().setMetadataOnly(true); PeakMap e; // real test file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), e); //check number of scans TEST_EQUAL(e.size(), 0) TEST_EQUAL(e.getSourceFiles().size(), 1) TEST_STRING_EQUAL(e.getSourceFiles()[0].getNameOfFile(), "MzDataFile_test_1.raw"); TEST_EQUAL(e.getContacts().size(), 2); TEST_EQUAL(e.getContacts()[0].getFirstName(), "John"); TEST_EQUAL(e.getContacts()[0].getLastName(), "Doe"); TEST_EQUAL(e.getInstrument().getName(), "MS-Instrument") TEST_EQUAL(e.getInstrument().getVendor(), "MS-Vendor") TEST_EQUAL(e.getSample().getName(), "MS-Sample") TEST_EQUAL(e.getSample().getNumber(), "0-815") } END_SECTION START_SECTION(([EXTRA] load with selected MS levels)) { TOLERANCE_ABSOLUTE(0.01) PeakMap e; MzDataFile file; // load only MS level 1 file.getOptions().addMSLevel(1); file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), e); TEST_EQUAL(e.size(), 2) TEST_EQUAL(e[0].size(), 1) TEST_STRING_EQUAL(e[0].getNativeID(), "spectrum=10") TEST_EQUAL(e[1].size(), 5) TEST_STRING_EQUAL(e[1].getNativeID(), "spectrum=12") TEST_EQUAL(e[0].getMSLevel(), 1) TEST_EQUAL(e[1].getMSLevel(), 1) // load all MS levels file.getOptions().clearMSLevels(); file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), e); TEST_EQUAL(e.size(), 3) TEST_EQUAL(e[0].size(), 1) TEST_EQUAL(e[1].size(), 3) TEST_EQUAL(e[2].size(), 5) TEST_EQUAL(e[0].getMSLevel(), 1) TEST_EQUAL(e[1].getMSLevel(), 2) TEST_EQUAL(e[2].getMSLevel(), 1) } END_SECTION START_SECTION(([EXTRA] load with RT range)) { TOLERANCE_ABSOLUTE(0.01) PeakMap e; MzDataFile file; file.getOptions().setRTRange(makeRange(100, 200)); file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), 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.size(), 2) TEST_EQUAL(e[0].getMSLevel(), 2) TEST_EQUAL(e[1].getMSLevel(), 1) TEST_REAL_SIMILAR(e[0].getRT(), 120) TEST_REAL_SIMILAR(e[1].getRT(), 180) } END_SECTION START_SECTION(([EXTRA] load with MZ range)) { TOLERANCE_ABSOLUTE(0.01) PeakMap e; MzDataFile file; file.getOptions().setMZRange(makeRange(115, 135)); file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), 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.size(), 3) 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 intensity range)) { TOLERANCE_ABSOLUTE(0.01) PeakMap e; MzDataFile file; file.getOptions().setIntensityRange(makeRange(150, 350)); file.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), 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.size(), 3) 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((template <typename MapType> void store(const String &filename, const MapType &map) const)) { PeakMap e1, e2; MzDataFile f; f.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), e1); TEST_EQUAL(e1.size(), 3) std::string tmp_filename; NEW_TMP_FILE(tmp_filename); f.store(tmp_filename, e1); f.load(tmp_filename, e2); TEST_EQUAL(e2.getIdentifier(), "lsid"); e2[0].getDataProcessing()[0]->getSoftware().setMetaValue("comment", String("SoftwareComment")); e2[1].getDataProcessing()[0]->getSoftware().setMetaValue("comment", String("SoftwareComment")); e2[2].getDataProcessing()[0]->getSoftware().setMetaValue("comment", String("SoftwareComment")); TEST_TRUE(e1 == e2); } END_SECTION START_SECTION([EXTRA] storing / loading of meta data arrays) { MzDataFile file; //init spectrum/experiment/meta data array PeakMap exp; MSSpectrum spec; spec.resize(5); spec[0].setIntensity(1.0f); spec[0].setMZ(1.0); spec[1].setIntensity(2.0f); spec[1].setMZ(2.0); spec[2].setIntensity(3.0f); spec[2].setMZ(3.0); spec[3].setIntensity(4.0f); spec[3].setMZ(4.0); spec[4].setIntensity(5.0f); spec[4].setMZ(5.0); MSSpectrum::FloatDataArray mda1; mda1.push_back(1.1f); mda1.push_back(1.2f); mda1.push_back(1.3f); mda1.push_back(1.4f); mda1.push_back(1.5f); MSSpectrum::FloatDataArray mda2; mda2.push_back(-2.1f); mda2.push_back(-2.2f); mda2.push_back(-2.3f); mda2.push_back(-2.4f); mda2.push_back(-2.5f); //spectrum 1 (one meta data arrays) spec.setRT(500.0); spec.getFloatDataArrays().push_back(mda1); spec.getFloatDataArrays()[0].setName("MDA1"); exp.addSpectrum(spec); //spectrum 2 (zero meta data array) spec.setRT(600.0); spec.getFloatDataArrays().clear(); exp.addSpectrum(spec); //spectrum 3 (two meta data array) spec.setRT(700.0); spec.getFloatDataArrays().push_back(mda1); spec.getFloatDataArrays().push_back(mda2); spec.getFloatDataArrays()[0].setName("MDA1"); spec.getFloatDataArrays()[1].setName("MDA2"); exp.addSpectrum(spec); //******************************************* //store file std::string filename; NEW_TMP_FILE(filename); cout << "Filename: " << filename << std::endl; file.store(filename, exp); //******************************************* //load and check file PeakMap exp2; file.load(filename, exp2); TEST_EQUAL(exp2.size(), 3) TEST_EQUAL(exp2[0].getFloatDataArrays().size(), 1) TEST_EQUAL(exp2[1].getFloatDataArrays().size(), 0) TEST_EQUAL(exp2[2].getFloatDataArrays().size(), 2) TEST_EQUAL(exp2[0].getFloatDataArrays()[0].getName(), "MDA1"); TEST_EQUAL(exp2[2].getFloatDataArrays()[0].getName(), "MDA1"); TEST_EQUAL(exp2[2].getFloatDataArrays()[1].getName(), "MDA2"); TEST_EQUAL(exp2[0].getFloatDataArrays()[0].size(), 5) TEST_REAL_SIMILAR(exp2[0].getFloatDataArrays()[0][0], 1.1); TEST_REAL_SIMILAR(exp2[0].getFloatDataArrays()[0][1], 1.2); TEST_REAL_SIMILAR(exp2[0].getFloatDataArrays()[0][2], 1.3); TEST_REAL_SIMILAR(exp2[0].getFloatDataArrays()[0][3], 1.4); TEST_REAL_SIMILAR(exp2[0].getFloatDataArrays()[0][4], 1.5); TEST_EQUAL(exp2[2].getFloatDataArrays()[0].size(), 5) TEST_REAL_SIMILAR(exp2[2].getFloatDataArrays()[0][0], 1.1); TEST_REAL_SIMILAR(exp2[2].getFloatDataArrays()[0][1], 1.2); TEST_REAL_SIMILAR(exp2[2].getFloatDataArrays()[0][2], 1.3); TEST_REAL_SIMILAR(exp2[2].getFloatDataArrays()[0][3], 1.4); TEST_REAL_SIMILAR(exp2[2].getFloatDataArrays()[0][4], 1.5); TEST_EQUAL(exp2[2].getFloatDataArrays()[1].size(), 5) TEST_REAL_SIMILAR(exp2[2].getFloatDataArrays()[1][0], -2.1); TEST_REAL_SIMILAR(exp2[2].getFloatDataArrays()[1][1], -2.2); TEST_REAL_SIMILAR(exp2[2].getFloatDataArrays()[1][2], -2.3); TEST_REAL_SIMILAR(exp2[2].getFloatDataArrays()[1][3], -2.4); TEST_REAL_SIMILAR(exp2[2].getFloatDataArrays()[1][4], -2.5); //******************************************* //check if filtering of meta data arrays works PeakMap exp3; file.getOptions().setMZRange(DRange<1>(2.5, 7.0)); file.load(filename, exp3); TEST_EQUAL(exp.size(), 3) TEST_EQUAL(exp3[0].size(), 3) TEST_EQUAL(exp3[1].size(), 3) TEST_EQUAL(exp3[2].size(), 3) TEST_EQUAL(exp3[0].getFloatDataArrays().size(), 1) TEST_EQUAL(exp3[1].getFloatDataArrays().size(), 0) TEST_EQUAL(exp3[2].getFloatDataArrays().size(), 2) TEST_EQUAL(exp3[0].getFloatDataArrays()[0].getName(), "MDA1"); TEST_EQUAL(exp3[2].getFloatDataArrays()[0].getName(), "MDA1"); TEST_EQUAL(exp3[2].getFloatDataArrays()[1].getName(), "MDA2"); TEST_EQUAL(exp3[0].getFloatDataArrays()[0].size(), 3) TEST_REAL_SIMILAR(exp3[0].getFloatDataArrays()[0][0], 1.3); TEST_REAL_SIMILAR(exp3[0].getFloatDataArrays()[0][1], 1.4); TEST_REAL_SIMILAR(exp3[0].getFloatDataArrays()[0][2], 1.5) TEST_EQUAL(exp3[2].getFloatDataArrays()[0].size(), 3) TEST_REAL_SIMILAR(exp3[2].getFloatDataArrays()[0][0], 1.3); TEST_REAL_SIMILAR(exp3[2].getFloatDataArrays()[0][1], 1.4); TEST_REAL_SIMILAR(exp3[2].getFloatDataArrays()[0][2], 1.5); TEST_EQUAL(exp3[2].getFloatDataArrays()[1].size(), 3) TEST_REAL_SIMILAR(exp3[2].getFloatDataArrays()[1][0], -2.3); TEST_REAL_SIMILAR(exp3[2].getFloatDataArrays()[1][1], -2.4); TEST_REAL_SIMILAR(exp3[2].getFloatDataArrays()[1][2], -2.5); //********************************************* //test if the storing meta data arrays without a name works exp3[0].getFloatDataArrays()[0].setName(""); exp3[2].getFloatDataArrays()[0].setName(""); exp3[2].getFloatDataArrays()[1].setName(""); PeakMap exp4; file.store(filename, exp3); file.load(filename, exp4); TEST_EQUAL(exp.size(), 3) TEST_EQUAL(exp4[0].size(), 3) TEST_EQUAL(exp4[1].size(), 3) TEST_EQUAL(exp4[2].size(), 3) TEST_EQUAL(exp4[0].getFloatDataArrays().size(), 1) TEST_EQUAL(exp4[1].getFloatDataArrays().size(), 0) TEST_EQUAL(exp4[2].getFloatDataArrays().size(), 2) TEST_EQUAL(exp4[0].getFloatDataArrays()[0].getName(), ""); TEST_EQUAL(exp4[2].getFloatDataArrays()[0].getName(), ""); TEST_EQUAL(exp4[2].getFloatDataArrays()[1].getName(), ""); TEST_EQUAL(exp4[0].getFloatDataArrays()[0].size(), 3) TEST_REAL_SIMILAR(exp4[0].getFloatDataArrays()[0][0], 1.3); TEST_REAL_SIMILAR(exp4[0].getFloatDataArrays()[0][1], 1.4); TEST_REAL_SIMILAR(exp4[0].getFloatDataArrays()[0][2], 1.5) TEST_EQUAL(exp4[2].getFloatDataArrays()[0].size(), 3) TEST_REAL_SIMILAR(exp4[2].getFloatDataArrays()[0][0], 1.3); TEST_REAL_SIMILAR(exp4[2].getFloatDataArrays()[0][1], 1.4); TEST_REAL_SIMILAR(exp4[2].getFloatDataArrays()[0][2], 1.5); TEST_EQUAL(exp4[2].getFloatDataArrays()[1].size(), 3) TEST_REAL_SIMILAR(exp4[2].getFloatDataArrays()[1][0], -2.3); TEST_REAL_SIMILAR(exp4[2].getFloatDataArrays()[1][1], -2.4); TEST_REAL_SIMILAR(exp4[2].getFloatDataArrays()[1][2], -2.5); } END_SECTION START_SECTION([EXTRA] static bool isValid(const String& filename)) { std::string tmp_filename; MzDataFile f; PeakMap e; //test if empty file is valid NEW_TMP_FILE(tmp_filename); f.store(tmp_filename, e); TEST_EQUAL(f.isValid(tmp_filename, std::cerr), true); //test if filled file is valid NEW_TMP_FILE(tmp_filename); f.load(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), e); f.store(tmp_filename, e); TEST_EQUAL(f.isValid(tmp_filename, std::cerr), true); } END_SECTION START_SECTION(bool isSemanticallyValid(const String& filename, StringList& errors, StringList& warnings)) { //This is not officially supported - the mapping file was hand-crafted by Marc Sturm NOT_TESTABLE } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Mobilogram_test.cpp
.cpp
28,205
998
// 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/KERNEL/Mobilogram.h> /////////////////////////// #include <sstream> using namespace OpenMS; using namespace std; static_assert(OpenMS::Test::fulfills_rule_of_5<Mobilogram>(), "Must fulfill rule of 5"); static_assert(OpenMS::Test::fulfills_rule_of_6<Mobilogram>(), "Must fulfill rule of 6"); static_assert(OpenMS::Test::fulfills_fast_vector<Mobilogram>(), "Must have fast vector semantics"); static_assert(std::is_nothrow_move_constructible_v<Mobilogram>, "Must have nothrow move constructible"); START_TEST(Mobilogram, "$Id$") ///////////////////////////////////////////////////////////// // Dummy peak data MobilityPeak1D p1; p1.setIntensity(1.0f); p1.setMobility(2.0); MobilityPeak1D p2; p2.setIntensity(2.0f); p2.setMobility(10.0); MobilityPeak1D p3; p3.setIntensity(3.0f); p3.setMobility(30.0); ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Mobilogram* ptr = nullptr; Mobilogram* nullPointer = nullptr; START_SECTION((Mobilogram())) { ptr = new Mobilogram(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((~Mobilogram())) { delete ptr; } END_SECTION START_SECTION(([EXTRA] Mobilogram())) { Mobilogram tmp; MobilityPeak1D peak; peak.getPosition()[0] = 47.11; tmp.push_back(peak); TEST_EQUAL(tmp.size(), 1); TEST_REAL_SIMILAR(tmp[0].getMobility(), 47.11); } END_SECTION ///////////////////////////////////////////////////////////// // Member accessors START_SECTION((double getRT() const)) { Mobilogram s; TEST_REAL_SIMILAR(s.getRT(), -1.0) } END_SECTION START_SECTION((void setRT(double rt))) { Mobilogram s; s.setRT(0.451); TEST_REAL_SIMILAR(s.getRT(), 0.451) } END_SECTION START_SECTION((double getDriftTimeUnit() const)) { Mobilogram s; TEST_EQUAL(s.getDriftTimeUnit() == DriftTimeUnit::NONE, true); } END_SECTION START_SECTION((double getDriftTimeUnitAsString() const)) { Mobilogram s; TEST_EQUAL(s.getDriftTimeUnitAsString(), "<NONE>"); } END_SECTION START_SECTION((void setDriftTimeUnit(double dt))) { Mobilogram s; s.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); TEST_EQUAL(s.getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true); TEST_EQUAL(s.getDriftTimeUnitAsString(), "ms"); } END_SECTION ///////////////////////////////////////////////////////////// // RangeManager START_SECTION((virtual void updateRanges())) { Mobilogram s; s.push_back(p1); s.push_back(p2); s.push_back(p1); s.updateRanges(); s.updateRanges(); // second time to check the initialization TEST_REAL_SIMILAR(s.getMaxIntensity(), 2) TEST_REAL_SIMILAR(s.getMinIntensity(), 1) TEST_REAL_SIMILAR(s.getMaxMobility(), 10) TEST_REAL_SIMILAR(s.getMinMobility(), 2) // test with only one peak s.clear(); s.push_back(p1); s.updateRanges(); TEST_REAL_SIMILAR(s.getMaxIntensity(), 1) TEST_REAL_SIMILAR(s.getMinIntensity(), 1) TEST_REAL_SIMILAR(s.getMaxMobility(), 2) TEST_REAL_SIMILAR(s.getMinMobility(), 2) } END_SECTION ///////////////////////////////////////////////////////////// // Copy constructor, move constructor, assignment operator, move assignment operator, equality START_SECTION((Mobilogram(const Mobilogram& source))) { Mobilogram tmp; tmp.setRT(7.0); tmp.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); // peaks Mobilogram::PeakType peak; peak.getPosition()[0] = 47.11; tmp.push_back(peak); Mobilogram tmp2(tmp); TEST_REAL_SIMILAR(tmp2.getRT(), 7.0) TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true) // peaks TEST_EQUAL(tmp2.size(), 1) TEST_REAL_SIMILAR(tmp2[0].getPosition()[0], 47.11) } END_SECTION START_SECTION((Mobilogram(const Mobilogram&& source))) { // Ensure that Mobilogram has a no-except move constructor (otherwise // std::vector<Mobilogram> is inefficient and will copy instead of move). TEST_EQUAL(noexcept(Mobilogram(std::declval<Mobilogram&&>())), true) Mobilogram tmp; tmp.setRT(9.0); tmp.setDriftTimeUnit(DriftTimeUnit::VSSC); // peaks Mobilogram::PeakType peak; peak.getPosition()[0] = 47.11; tmp.push_back(peak); peak.getPosition()[0] = 48.11; tmp.push_back(peak); // copy tmp so we can move one of them Mobilogram orig = tmp; Mobilogram tmp2(std::move(tmp)); TEST_EQUAL(tmp2, orig) // should be equal to the original TEST_REAL_SIMILAR(tmp2.getRT(), 9.0) TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::VSSC, true) TEST_EQUAL(tmp2.size(), 2) TEST_REAL_SIMILAR(tmp2[0].getPosition()[0], 47.11) TEST_REAL_SIMILAR(tmp2[1].getPosition()[0], 48.11) // test move -- if this fails, then the move-operator did a copy, not a move... so this better not fail TEST_EQUAL(tmp.size(), 0) } END_SECTION START_SECTION((Mobilogram & operator=(const Mobilogram& source))) { Mobilogram tmp; tmp.setRT(7.0); tmp.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); // peaks Mobilogram::PeakType peak; peak.getPosition()[0] = 47.11; tmp.push_back(peak); // normal assignment Mobilogram tmp2; tmp2 = tmp; TEST_REAL_SIMILAR(tmp2.getRT(), 7.0) TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true) TEST_EQUAL(tmp2.size(), 1); TEST_REAL_SIMILAR(tmp2[0].getPosition()[0], 47.11); // Assignment of empty object // normal assignment tmp2 = Mobilogram(); TEST_REAL_SIMILAR(tmp2.getRT(), -1.0) TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::NONE, true) TEST_EQUAL(tmp2.size(), 0) } END_SECTION START_SECTION((Mobilogram & operator=(const Mobilogram&& source))) { Mobilogram tmp; tmp.setRT(9.0); tmp.setDriftTimeUnit(DriftTimeUnit::VSSC); // peaks Mobilogram::PeakType peak; peak.getPosition()[0] = 47.11; tmp.push_back(peak); peak.getPosition()[0] = 48.11; tmp.push_back(peak); // copy tmp so we can move one of them Mobilogram orig = tmp; // move assignment Mobilogram tmp2; tmp2 = std::move(tmp); TEST_EQUAL(tmp2, orig) // should be equal to the original TEST_REAL_SIMILAR(tmp2.getRT(), 9.0) TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::VSSC, true) TEST_EQUAL(tmp2.size(), 2) TEST_REAL_SIMILAR(tmp2[0].getPosition()[0], 47.11) TEST_REAL_SIMILAR(tmp2[1].getPosition()[0], 48.11) // test move -- if this fails, then the move-operator did a copy, not a move... so this better not fail TEST_EQUAL(tmp.size(), 0) // Assignment of empty object // normal assignment #ifndef OPENMS_WINDOWSPLATFORM #pragma clang diagnostic push // Ignore -Wpessimizing-move, because we want to test the move assignment operator. #pragma clang diagnostic ignored "-Wpessimizing-move" #endif tmp2 = std::move(Mobilogram()); #ifndef OPENMS_WINDOWSPLATFORM #pragma clang diagnostic pop #endif TEST_REAL_SIMILAR(tmp2.getRT(), -1.0) TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::NONE, true) TEST_EQUAL(tmp2.size(), 0) } END_SECTION START_SECTION((bool operator==(const Mobilogram& rhs) const)) { Mobilogram edit, empty; TEST_TRUE(edit == empty); edit = empty; edit.resize(1); TEST_EQUAL(edit == empty, false); edit = empty; edit.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); TEST_EQUAL(empty == edit, false); edit = empty; edit.setRT(5); TEST_EQUAL(empty == edit, false); edit = empty; edit.push_back(p1); edit.push_back(p2); edit.updateRanges(); edit.clear(); TEST_TRUE(empty == edit); } END_SECTION START_SECTION((bool operator!=(const Mobilogram& rhs) const)) { Mobilogram edit, empty; TEST_EQUAL(edit != empty, false); edit = empty; edit.resize(1); TEST_FALSE(edit == empty); edit = empty; edit.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); TEST_FALSE(edit == empty); edit = empty; edit.setRT(5); TEST_FALSE(edit == empty); edit = empty; edit.push_back(p1); edit.push_back(p2); edit.updateRanges(); edit.clear(); TEST_TRUE(edit == empty); } END_SECTION ///////////////////////////////////////////////////////////// // Sorting START_SECTION((void sortByIntensity(bool reverse = false))) { Mobilogram ds; MobilityPeak1D p; std::vector<double> mzs, intensities; intensities.push_back(201); mzs.push_back(420.130); intensities.push_back(60); mzs.push_back(412.824); intensities.push_back(56); mzs.push_back(423.269); intensities.push_back(37); mzs.push_back(415.287); intensities.push_back(34); mzs.push_back(413.800); intensities.push_back(31); mzs.push_back(419.113); intensities.push_back(31); mzs.push_back(416.293); intensities.push_back(31); mzs.push_back(418.232); intensities.push_back(29); mzs.push_back(414.301); intensities.push_back(29); mzs.push_back(412.321); for (Size i = 0; i < mzs.size(); ++i) { p.setIntensity(intensities[i]); p.setMobility(mzs[i]); ds.push_back(p); } ds.sortByIntensity(); std::vector<double> intensities_copy(intensities); std::sort(intensities_copy.begin(), intensities_copy.end()); Mobilogram::iterator it_ds = ds.begin(); ABORT_IF(ds.size() != intensities_copy.size()) for (std::vector<double>::iterator it = intensities_copy.begin(); it != intensities_copy.end(); ++it) { TEST_EQUAL(it_ds->getIntensity(), *it); ++it_ds; } ds.clear(); for (Size i = 0; i < mzs.size(); ++i) { p.setIntensity(intensities[i]); p.setMobility(mzs[i]); ds.push_back(p); } ds.sortByIntensity(); Mobilogram::iterator it1 = ds.begin(); TOLERANCE_ABSOLUTE(0.0001) for (std::vector<double>::iterator it = intensities_copy.begin(); it != intensities_copy.end(); ++it) { if (it1 != ds.end()) { // metadataarray values == mz values TEST_REAL_SIMILAR(it1->getIntensity(), *it); ++it1; } else { TEST_EQUAL(true, false) } } } END_SECTION START_SECTION((void sortByPosition())) { Mobilogram ds; std::vector<double> mzs {423.269, 420.130, 419.113, 418.232, 416.293, 415.287, 414.301, 413.800, 412.824, 412.321}; std::vector<double> intensities {56, 201, 31, 31, 31, 37, 29, 34, 60, 29}; for (Size i = 0; i < mzs.size(); ++i) { ds.emplace_back(mzs[i], intensities[i]); } ds.sortByPosition(); Mobilogram::iterator it = ds.begin(); for (std::vector<double>::reverse_iterator rit = intensities.rbegin(); rit != intensities.rend(); ++rit) { if (it == ds.end()) { TEST_EQUAL(true, false) } TEST_EQUAL(it->getIntensity(), *rit); ++it; } ds.clear(); for (Size i = 0; i < mzs.size(); ++i) { ds.emplace_back(mzs[i], intensities[i]); } ds.sortByPosition(); Size size = intensities.size(); ABORT_IF(ds.size() != size); Mobilogram::iterator it1 = ds.begin(); for (std::vector<double>::reverse_iterator rit = intensities.rbegin(); rit != intensities.rend(); ++rit) { // metadataarray values == intensity values TEST_REAL_SIMILAR(it1->getIntensity(), *rit); ++it1; } } END_SECTION START_SECTION(bool isSorted() const) { // make test dataset Mobilogram spec; MobilityPeak1D p; p.setIntensity(1.0); p.setMobility(1000.0); spec.push_back(p); p.setIntensity(1.0); p.setMobility(1001.0); spec.push_back(p); p.setIntensity(1.0); p.setMobility(1002.0); spec.push_back(p); TEST_EQUAL(spec.isSorted(), true) reverse(spec.begin(), spec.end()); TEST_EQUAL(spec.isSorted(), false) } END_SECTION START_SECTION(template<class Predicate> bool isSorted(const Predicate& lamdba) const) { Mobilogram ds; std::vector<double> mzs {423.269, 420.130, 419.113, 418.232, 416.293, 415.287, 414.301, 413.800, 412.824, 412.321}; std::vector<double> intensities {56, 201, 31, 31, 31, 37, 29, 34, 60, 29}; for (Size i = 0; i < mzs.size(); ++i) { ds.emplace_back(mzs[i], intensities[i]); } ds.sortByPosition(); // more expensive than isSorted(), but just to make sure TEST_EQUAL(ds.isSorted([&ds](Size a, Size b) { return ds[a].getMobility() < ds[b].getMobility(); }), true) TEST_EQUAL(ds.isSorted(), true) // call other method. Should give the same result ds.sortByIntensity(); TEST_EQUAL(ds.isSorted([&ds](Size a, Size b) { return ds[a].getIntensity() < ds[b].getIntensity(); }), true) TEST_EQUAL(ds.isSorted([&ds](Size a, Size b) { return ds[a].getMobility() < ds[b].getMobility(); }), false) TEST_EQUAL(ds.isSorted(), false) // call other method. Should give the same result } END_SECTION START_SECTION(template<class Predicate> void sort(const Predicate& lambda)) {// tested above NOT_TESTABLE } END_SECTION ///////////////////////////////////////////////////////////// // Finding peaks or peak ranges const Mobilogram spec_find = []() { Mobilogram spec; spec.push_back({1.0, 29.0f}); spec.push_back({2.0, 60.0f}); spec.push_back({3.0, 34.0f}); spec.push_back({4.0, 29.0f}); spec.push_back({5.0, 37.0f}); spec.push_back({6.0, 31.0f}); return spec; }(); START_SECTION((Iterator MBEnd(CoordinateType mb))) { Mobilogram::Iterator it; auto tmp = spec_find; it = tmp.MBEnd(4.5); TEST_EQUAL(it->getPosition()[0], 5.0) it = tmp.MBEnd(5.0); TEST_EQUAL(it->getPosition()[0], 6.0) it = tmp.MBEnd(5.5); TEST_EQUAL(it->getPosition()[0], 6.0) } END_SECTION START_SECTION((Iterator MBBegin(CoordinateType mb))) { Mobilogram::Iterator it; auto tmp = spec_find; it = tmp.MBBegin(4.5); TEST_EQUAL(it->getPosition()[0], 5.0) it = tmp.MBBegin(5.0); TEST_EQUAL(it->getPosition()[0], 5.0) it = tmp.MBBegin(5.5); TEST_EQUAL(it->getPosition()[0], 6.0) } END_SECTION START_SECTION((Iterator MBBegin(Iterator begin, CoordinateType mb, Iterator end))) { Mobilogram::Iterator it; auto tmp = spec_find; it = tmp.MBBegin(tmp.begin(), 4.5, tmp.end()); TEST_EQUAL(it->getPosition()[0], 5.0) it = tmp.MBBegin(tmp.begin(), 4.5, tmp.end()); TEST_EQUAL(it->getPosition()[0], 5.0) it = tmp.MBBegin(tmp.begin(), 4.5, tmp.begin()); TEST_EQUAL(it->getPosition()[0], tmp.begin()->getPosition()[0]) } END_SECTION START_SECTION((ConstIterator MBBegin(ConstIterator begin, CoordinateType mb, ConstIterator end) const)) { Mobilogram::Iterator it; auto tmp = spec_find; it = tmp.MBBegin(tmp.begin(), 4.5, tmp.end()); TEST_EQUAL(it->getPosition()[0], 5.0) it = tmp.MBBegin(tmp.begin(), 4.5, tmp.end()); TEST_EQUAL(it->getPosition()[0], 5.0) it = tmp.MBBegin(tmp.begin(), 4.5, tmp.begin()); TEST_EQUAL(it->getPosition()[0], tmp.begin()->getPosition()[0]) } END_SECTION START_SECTION((Iterator MBEnd(Iterator begin, CoordinateType mb, Iterator end))) { Mobilogram::Iterator it; auto tmp = spec_find; it = tmp.MBEnd(tmp.begin(), 4.5, tmp.end()); TEST_EQUAL(it->getPosition()[0], 5.0) it = tmp.MBEnd(tmp.begin(), 5, tmp.end()); TEST_EQUAL(it->getPosition()[0], 6.0) it = tmp.MBEnd(tmp.begin(), 4.5, tmp.begin()); TEST_EQUAL(it->getPosition()[0], tmp.begin()->getPosition()[0]) } END_SECTION START_SECTION((ConstIterator MBEnd(ConstIterator begin, CoordinateType mb, ConstIterator end) const)) { Mobilogram::ConstIterator it; it = spec_find.MBEnd(spec_find.begin(), 4.5, spec_find.end()); TEST_EQUAL(it->getPosition()[0], 5.0) it = spec_find.MBEnd(spec_find.begin(), 5, spec_find.end()); TEST_EQUAL(it->getPosition()[0], 6.0) it = spec_find.MBEnd(spec_find.begin(), 4.5, spec_find.begin()); TEST_EQUAL(it->getPosition()[0], spec_find.begin()->getPosition()[0]) } END_SECTION START_SECTION((ConstIterator MBEnd(CoordinateType mb) const)) { Mobilogram::ConstIterator it; it = spec_find.MBEnd(4.5); TEST_EQUAL(it->getPosition()[0], 5.0) it = spec_find.MBEnd(5.0); TEST_EQUAL(it->getPosition()[0], 6.0) it = spec_find.MBEnd(5.5); TEST_EQUAL(it->getPosition()[0], 6.0) } END_SECTION START_SECTION((ConstIterator MBBegin(CoordinateType mb) const)) { Mobilogram::ConstIterator it; it = spec_find.MBBegin(4.5); TEST_EQUAL(it->getPosition()[0], 5.0) it = spec_find.MBBegin(5.0); TEST_EQUAL(it->getPosition()[0], 5.0) it = spec_find.MBBegin(5.5); TEST_EQUAL(it->getPosition()[0], 6.0) } END_SECTION auto tmp = spec_find; START_SECTION((Iterator PosBegin(CoordinateType mb))) { Mobilogram::Iterator it; it = tmp.PosBegin(4.5); TEST_EQUAL(it->getPos(), 5.0) it = tmp.PosBegin(5.0); TEST_EQUAL(it->getPos(), 5.0) it = tmp.PosBegin(5.5); TEST_EQUAL(it->getPos(), 6.0) } END_SECTION START_SECTION((Iterator PosBegin(Iterator begin, CoordinateType mb, Iterator end))) { Mobilogram::Iterator it; it = tmp.PosBegin(tmp.begin(), 4.5, tmp.end()); TEST_EQUAL(it->getPos(), 5.0) it = tmp.PosBegin(tmp.begin(), 5.5, tmp.end()); TEST_EQUAL(it->getPos(), 6.0) it = tmp.PosBegin(tmp.begin(), 4.5, tmp.begin()); TEST_EQUAL(it->getPos(), tmp.begin()->getPos()) it = tmp.PosBegin(tmp.begin(), 8.0, tmp.end()); TEST_EQUAL((it - 1)->getPos(), (tmp.end() - 1)->getPos()) } END_SECTION START_SECTION((ConstIterator PosBegin(CoordinateType mb) const)) { Mobilogram::ConstIterator it; it = tmp.PosBegin(4.5); TEST_EQUAL(it->getPos(), 5.0) it = tmp.PosBegin(5.0); TEST_EQUAL(it->getPos(), 5.0) it = tmp.PosBegin(5.5); TEST_EQUAL(it->getPos(), 6.0) } END_SECTION START_SECTION((ConstIterator PosBegin(ConstIterator begin, CoordinateType mb, ConstIterator end) const)) { Mobilogram::ConstIterator it; it = tmp.PosBegin(tmp.begin(), 3.5, tmp.end()); TEST_EQUAL(it->getPos(), 4.0) it = tmp.PosBegin(tmp.begin(), 4.5, tmp.end()); TEST_EQUAL(it->getPos(), 5.0) it = tmp.PosBegin(tmp.begin(), 4.5, tmp.begin()); TEST_EQUAL(it->getPos(), tmp.begin()->getPos()) it = tmp.PosBegin(tmp.begin(), 8.0, tmp.end()); TEST_EQUAL((it - 1)->getPos(), (tmp.end() - 1)->getPos()) } END_SECTION START_SECTION((Iterator PosEnd(CoordinateType mb))) { Mobilogram::Iterator it; it = tmp.PosEnd(4.5); TEST_EQUAL(it->getPos(), 5.0) it = tmp.PosEnd(5.0); TEST_EQUAL(it->getPos(), 6.0) it = tmp.PosEnd(5.5); TEST_EQUAL(it->getPos(), 6.0) } END_SECTION START_SECTION((Iterator PosEnd(Iterator begin, CoordinateType mb, Iterator end))) { Mobilogram::Iterator it; it = tmp.PosEnd(tmp.begin(), 3.5, tmp.end()); TEST_EQUAL(it->getPos(), 4.0) it = tmp.PosEnd(tmp.begin(), 4.0, tmp.end()); TEST_EQUAL(it->getPos(), 5.0) it = tmp.PosEnd(tmp.begin(), 4.5, tmp.begin()); TEST_EQUAL(it->getPos(), tmp.begin()->getPos()) it = tmp.PosBegin(tmp.begin(), 8.0, tmp.end()); TEST_EQUAL((it - 1)->getPos(), (tmp.end() - 1)->getPos()) } END_SECTION START_SECTION((ConstIterator PosEnd(CoordinateType mb) const)) { Mobilogram::ConstIterator it; it = tmp.PosEnd(4.5); TEST_EQUAL(it->getPos(), 5.0) it = tmp.PosEnd(5.0); TEST_EQUAL(it->getPos(), 6.0) it = tmp.PosEnd(5.5); TEST_EQUAL(it->getPos(), 6.0) } END_SECTION START_SECTION((ConstIterator PosEnd(ConstIterator begin, CoordinateType mb, ConstIterator end) const)) { Mobilogram::ConstIterator it; it = tmp.PosEnd(tmp.begin(), 4.5, tmp.end()); TEST_EQUAL(it->getPos(), 5.0) it = tmp.PosEnd(tmp.begin(), 5.0, tmp.end()); TEST_EQUAL(it->getPos(), 6.0) it = tmp.PosEnd(tmp.begin(), 4.5, tmp.begin()); TEST_EQUAL(it->getPos(), tmp.begin()->getPos()) it = tmp.PosBegin(tmp.begin(), 8.0, tmp.end()); TEST_EQUAL((it - 1)->getPos(), (tmp.end() - 1)->getPos()) } END_SECTION const Mobilogram spec_test = []() { Mobilogram spec_test; spec_test.push_back({412.321, 29.0f}); spec_test.push_back({412.824, 60.0f}); spec_test.push_back({413.8, 34.0f}); spec_test.push_back({414.301, 29.0f}); spec_test.push_back({415.287, 37.0f}); spec_test.push_back({416.293, 31.0f}); spec_test.push_back({418.232, 31.0f}); spec_test.push_back({419.113, 31.0f}); spec_test.push_back({420.13, 201.0f}); spec_test.push_back({423.269, 56.0f}); spec_test.push_back({426.292, 34.0f}); spec_test.push_back({427.28, 82.0f}); spec_test.push_back({428.322, 87.0f}); spec_test.push_back({430.269, 30.0f}); spec_test.push_back({431.246, 29.0f}); spec_test.push_back({432.289, 42.0f}); spec_test.push_back({436.161, 32.0f}); spec_test.push_back({437.219, 54.0f}); spec_test.push_back({439.186, 40.0f}); spec_test.push_back({440.27, 40}); spec_test.push_back({441.224, 23.0f}); return spec_test; }(); START_SECTION((Size findNearest(CoordinateType mb) const)) { Mobilogram tmp = spec_test; // test outside mass range TEST_EQUAL(tmp.findNearest(400.0), 0); TEST_EQUAL(tmp.findNearest(500.0), 20); // test mass range borders TEST_EQUAL(tmp.findNearest(412.4), 0); TEST_EQUAL(tmp.findNearest(441.224), 20); // test inside scan TEST_EQUAL(tmp.findNearest(426.29), 10); TEST_EQUAL(tmp.findNearest(426.3), 10); TEST_EQUAL(tmp.findNearest(427.2), 11); TEST_EQUAL(tmp.findNearest(427.3), 11); // empty spectrum Mobilogram tmp2; TEST_PRECONDITION_VIOLATED(tmp2.findNearest(427.3)); } END_SECTION START_SECTION((Size findNearest(CoordinateType mb, CoordinateType tolerance) const)) { // test outside mass range TEST_EQUAL(spec_test.findNearest(400.0, 1.0), -1); TEST_EQUAL(spec_test.findNearest(500.0, 1.0), -1); // test mass range borders TEST_EQUAL(spec_test.findNearest(412.4, 0.01), -1); TEST_EQUAL(spec_test.findNearest(412.4, 0.1), 0); TEST_EQUAL(spec_test.findNearest(441.3, 0.01), -1); TEST_EQUAL(spec_test.findNearest(441.3, 0.1), 20); // test inside scan TEST_EQUAL(spec_test.findNearest(426.29, 0.1), 10); TEST_EQUAL(spec_test.findNearest(426.3, 0.1), 10); TEST_EQUAL(spec_test.findNearest(427.2, 0.1), 11); TEST_EQUAL(spec_test.findNearest(427.3, 0.1), 11); TEST_EQUAL(spec_test.findNearest(427.3, 0.001), -1); // empty spectrum Mobilogram spec_test2; TEST_EQUAL(spec_test2.findNearest(427.3, 1.0, 1.0), -1); } END_SECTION START_SECTION((Size findNearest(CoordinateType mb, CoordinateType left_tolerance, CoordinateType right_tolerance) const)) { // test outside mass range TEST_EQUAL(spec_test.findNearest(400.0, 1.0, 1.0), -1); TEST_EQUAL(spec_test.findNearest(500.0, 1.0, 1.0), -1); // test mass range borders TEST_EQUAL(spec_test.findNearest(412.4, 0.01, 0.01), -1); TEST_EQUAL(spec_test.findNearest(412.4, 0.1, 0.1), 0); TEST_EQUAL(spec_test.findNearest(441.3, 0.01, 0.01), -1); TEST_EQUAL(spec_test.findNearest(441.3, 0.1, 0.1), 20); // test inside scan TEST_EQUAL(spec_test.findNearest(426.29, 0.1, 0.1), 10); TEST_EQUAL(spec_test.findNearest(426.3, 0.1, 0.1), 10); TEST_EQUAL(spec_test.findNearest(427.2, 0.1, 0.1), 11); TEST_EQUAL(spec_test.findNearest(427.3, 0.1, 0.1), 11); TEST_EQUAL(spec_test.findNearest(427.3, 0.001, 0.001), -1); TEST_EQUAL(spec_test.findNearest(427.3, 0.1, 0.001), 11); TEST_EQUAL(spec_test.findNearest(427.3, 0.001, 1.01), -1); TEST_EQUAL(spec_test.findNearest(427.3, 0.001, 1.1), 12); // empty spectrum Mobilogram spec_test2; TEST_EQUAL(spec_test2.findNearest(427.3, 1.0, 1.0), -1); } END_SECTION START_SECTION((Size findHighestInWindow(CoordinateType mb, CoordinateType tolerance_left, CoordinateType tolerance_righ) const)) { // test outside mass range TEST_EQUAL(spec_test.findHighestInWindow(400.0, 1.0, 1.0), -1); TEST_EQUAL(spec_test.findHighestInWindow(500.0, 1.0, 1.0), -1); // test mass range borders TEST_EQUAL(spec_test.findHighestInWindow(412.4, 0.01, 0.01), -1); TEST_EQUAL(spec_test.findHighestInWindow(412.4, 0.1, 0.1), 0); TEST_EQUAL(spec_test.findHighestInWindow(441.3, 0.01, 0.01), -1); TEST_EQUAL(spec_test.findHighestInWindow(441.3, 0.1, 0.1), 20); // test inside scan TEST_EQUAL(spec_test.findHighestInWindow(426.29, 0.1, 0.1), 10); TEST_EQUAL(spec_test.findHighestInWindow(426.3, 0.1, 0.1), 10); TEST_EQUAL(spec_test.findHighestInWindow(427.2, 0.1, 0.1), 11); TEST_EQUAL(spec_test.findHighestInWindow(427.3, 0.1, 0.1), 11); TEST_EQUAL(spec_test.findHighestInWindow(427.3, 0.001, 0.001), -1); TEST_EQUAL(spec_test.findHighestInWindow(427.3, 0.1, 0.001), 11); TEST_EQUAL(spec_test.findHighestInWindow(427.3, 0.001, 1.01), -1); TEST_EQUAL(spec_test.findHighestInWindow(427.3, 0.001, 1.1), 12); TEST_EQUAL(spec_test.findHighestInWindow(427.3, 9.0, 4.0), 8); TEST_EQUAL(spec_test.findHighestInWindow(430.25, 1.9, 1.01), 13); // empty spectrum Mobilogram spec_test2; TEST_EQUAL(spec_test2.findHighestInWindow(427.3, 1.0, 1.0), -1); } END_SECTION START_SECTION(ConstIterator getBasePeak() const) { const auto it = spec_test.getBasePeak(); TEST_REAL_SIMILAR(it->getIntensity(), 201.0) TEST_EQUAL(std::distance(spec_test.begin(), it), 8); Mobilogram empty; TEST_EQUAL(empty.getBasePeak() == empty.end(), true); } END_SECTION START_SECTION(Iterator getBasePeak()) { Mobilogram test = spec_test; auto it = test.getBasePeak(); it->setIntensity(it->getIntensity() + 0.0); TEST_REAL_SIMILAR(it->getIntensity(), 201.0) TEST_EQUAL(std::distance(test.begin(), it), 8); } END_SECTION START_SECTION(PeakType::IntensityType calculateTIC() const) { auto r = spec_test.calculateTIC(); TEST_REAL_SIMILAR(r, 1032.0) TEST_EQUAL(Mobilogram().calculateTIC(), 0.0) } END_SECTION START_SECTION(void clear()) { Mobilogram edit; edit.resize(1); edit.setRT(5); edit.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); edit.clear(); TEST_EQUAL(edit.size(), 0) TEST_EQUAL(edit == Mobilogram(), false) TEST_EQUAL(edit.empty(), true) } END_SECTION START_SECTION(([Mobilogram::RTLess] bool operator()(const Mobilogram& a, const Mobilogram& b) const)) { vector<Mobilogram> v; Mobilogram sp1; sp1.setRT(3.0f); v.push_back(sp1); Mobilogram sp2; sp2.setRT(2.0f); v.push_back(sp2); Mobilogram sp3; sp3.setRT(1.0f); v.push_back(sp3); std::sort(v.begin(), v.end(), Mobilogram::RTLess()); TEST_REAL_SIMILAR(v[0].getRT(), 1.0); TEST_REAL_SIMILAR(v[1].getRT(), 2.0); TEST_REAL_SIMILAR(v[2].getRT(), 3.0); /// Mobilogram s1; s1.setRT(0.451); Mobilogram s2; s2.setRT(0.5); TEST_EQUAL(Mobilogram::RTLess()(s1, s2), true); TEST_EQUAL(Mobilogram::RTLess()(s2, s1), false); TEST_EQUAL(Mobilogram::RTLess()(s2, s2), false); } END_SECTION START_SECTION(([EXTRA] std::ostream & operator<<(std::ostream& os, const Mobilogram& spec))) { Mobilogram spec; MobilityPeak1D p; p.setIntensity(29.0f); p.setMobility(412.321); spec.push_back(p); // 0 p.setIntensity(60.0f); p.setMobility(412.824); spec.push_back(p); // 1 p.setIntensity(34.0f); p.setMobility(413.8); spec.push_back(p); // 2 p.setIntensity(29.0f); p.setMobility(414.301); spec.push_back(p); // 3 p.setIntensity(37.0f); p.setMobility(415.287); spec.push_back(p); // 4 p.setIntensity(31.0f); p.setMobility(416.293); spec.push_back(p); // 5 p.setIntensity(31.0f); p.setMobility(418.232); spec.push_back(p); // 6 p.setIntensity(31.0f); p.setMobility(419.113); spec.push_back(p); // 7 p.setIntensity(201.0f); p.setMobility(420.13); spec.push_back(p); // 8 p.setIntensity(56.0f); p.setMobility(423.269); spec.push_back(p); // 9 p.setIntensity(34.0f); p.setMobility(426.292); spec.push_back(p); // 10 spec.setRT(7.0); ostringstream test_stream; test_stream << spec; TEST_EQUAL(test_stream.str(), "-- MOBILOGRAM BEGIN --\n" "POS: 412.321 INT: 29\n" "POS: 412.824 INT: 60\n" "POS: 413.8 INT: 34\n" "POS: 414.301 INT: 29\n" "POS: 415.287 INT: 37\n" "POS: 416.293 INT: 31\n" "POS: 418.232 INT: 31\n" "POS: 419.113 INT: 31\n" "POS: 420.13 INT: 201\n" "POS: 423.269 INT: 56\n" "POS: 426.292 INT: 34\n" "-- MOBILOGRAM END --\n") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MissedCleavages_test.cpp
.cpp
6,589
203
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Swenja Wagner, Patricia Scheil $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CHEMISTRY/ProteaseDB.h> #include <OpenMS/CHEMISTRY/ProteaseDigestion.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/METADATA/MetaInfoInterface.h> #include <OpenMS/METADATA/PeptideHit.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/QC/MissedCleavages.h> #include <OpenMS/QC/QCBase.h> #include <string> #include <vector> ////////////////////////// using namespace OpenMS; START_TEST(MissedCleavages, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // construct PeptideHits PeptideHit pep_hit_no_cut; pep_hit_no_cut.setSequence(AASequence::fromString("AAAAAAAAAAAAAK")); PeptideHit pep_hit_one_cut; pep_hit_one_cut.setSequence(AASequence::fromString("AAAAKAAAAAR")); PeptideHit pep_hit_three_cuts; pep_hit_three_cuts.setSequence(AASequence::fromString("AAAKAAARAAAKAAAR")); // construct vectors of PeptideHits std::vector<PeptideHit> pep_hits_0 = {pep_hit_no_cut}; std::vector<PeptideHit> pep_hits_1 = {pep_hit_one_cut}; std::vector<PeptideHit> pep_hits_3 = {pep_hit_three_cuts}; std::vector<PeptideHit> pep_hits_empty = {}; // construct PeptideIdentification with PeptideHits PeptideIdentification pep_id_0; pep_id_0.setHits(pep_hits_0); PeptideIdentification pep_id_1; pep_id_1.setHits(pep_hits_1); PeptideIdentification pep_id_empty; pep_id_empty.setHits(pep_hits_empty); PeptideIdentification pep_id_3; pep_id_3.setHits(pep_hits_3); // construct vectors of PeptideIdentifications PeptideIdentificationList pep_ids = {pep_id_0, pep_id_1, pep_id_empty}; PeptideIdentificationList pep_ids_1 = {pep_id_1, pep_id_1}; PeptideIdentificationList pep_ids_empty {}; PeptideIdentificationList pep_ids_3 = {pep_id_3}; // construct features with peptideIdentifications Feature feat_empty_pi; feat_empty_pi.setPeptideIdentifications(pep_ids_empty); feat_empty_pi.setMetaValue("FWHM", 32.21); Feature feat; feat.setPeptideIdentifications(pep_ids); feat.setMetaValue("FWHM", 32.21); Feature feat_empty; feat_empty.setMetaValue("FWHM", 32.21); Feature feat_3; feat_3.setPeptideIdentifications(pep_ids_3); feat_3.setMetaValue("FWHM", 32.21); // FeatureMap FeatureMap feature_map; FeatureMap feature_map_3; FeatureMap feature_map_empty; FeatureMap feature_map_no_protein; FeatureMap feature_map_no_enzyme; // stores data in the FeatureMaps feature_map.push_back(feat_empty_pi); feature_map.push_back(feat); feature_map.push_back(feat_empty); feature_map.setUnassignedPeptideIdentifications(pep_ids_1); feature_map.getProteinIdentifications().resize(1); feature_map.getProteinIdentifications()[0].getSearchParameters().digestion_enzyme = *ProteaseDB::getInstance()->getEnzyme("trypsin"); feature_map.getProteinIdentifications()[0].getSearchParameters().missed_cleavages = 2; // FeatureMap with more missed cleavages than allowed feature_map_3.push_back(feat_3); feature_map_3.getProteinIdentifications().resize(1); feature_map_3.getProteinIdentifications()[0].getSearchParameters().digestion_enzyme.setName("trypsin"); feature_map_3.getProteinIdentifications()[0].getSearchParameters().missed_cleavages = 2; // FeatureMap without ProteinIdentifications feature_map_no_protein.push_back(feat); // FeatureMap without given enzyme feature_map_no_enzyme.push_back(feat); ProteinIdentification prot_id; feature_map_no_enzyme.setProteinIdentifications({prot_id}); ////////////////////////////////////////////////////////////////// // start Section ///////////////////////////////////////////////////////////////// MissedCleavages* ptr = nullptr; MissedCleavages* nulpt = nullptr; START_SECTION(MissedCleavages()) { ptr = new MissedCleavages(); TEST_NOT_EQUAL(ptr, nulpt) } END_SECTION START_SECTION(~MissedCleavages()) { delete ptr; } END_SECTION // tests compute function START_SECTION(void compute(FeatureMap& fmap)) { // test with valid input MissedCleavages mc; mc.compute(feature_map); auto result = mc.getResults(); TEST_EQUAL(result[0].size(), 2) TEST_EQUAL(result[0][0], 1) TEST_EQUAL(result[0][1], 3) std::vector<UInt32> frequ; // test if result is stored as MetaInformation in PeptideHits in FeatureMap auto lam = [&frequ](PeptideIdentification& pep_id) { if (pep_id.getHits().empty()) { return; } if (pep_id.getHits()[0].metaValueExists("missed_cleavages")) { frequ.push_back(pep_id.getHits()[0].getMetaValue("missed_cleavages")); } }; feature_map.applyFunctionOnPeptideIDs(lam); TEST_EQUAL(frequ.size(), 4) TEST_EQUAL(frequ[0], 0) TEST_EQUAL(frequ[1], 1) TEST_EQUAL(frequ[2], 1) TEST_EQUAL(frequ[3], 1) // empty feature map MissedCleavages mc_empty; mc_empty.compute(feature_map_empty); auto result_empty = mc_empty.getResults(); TEST_EQUAL(result_empty[0].empty(), true) // Missing informations in ProteinIdentifications // fmap.getProteinIdentifications().empty() MissedCleavages mc_no_protein; TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, mc_no_protein.compute(feature_map_no_protein), "Missing information in ProteinIdentifications.") // no given enzyme // enzyme == "unknown_enzyme" MissedCleavages mc_no_enzyme; TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, mc_no_enzyme.compute(feature_map_no_enzyme), "No digestion enzyme in FeatureMap detected. No computation possible.") // Number of missed cleavages is greater than the allowed maximum number of missed cleavages. MissedCleavages mc_3; mc_3.compute(feature_map_3); auto result_3 = mc_3.getResults(); TEST_EQUAL(result_3[0].size(), 1) TEST_EQUAL(result_3[0][3], 1) } END_SECTION MissedCleavages mc; START_SECTION(const String& getName() const override) {TEST_EQUAL(mc.getName(), "MissedCleavages")} END_SECTION START_SECTION(QCBase::Status requirements() const override) {TEST_EQUAL(QCBase::Status(QCBase::Requires::POSTFDRFEAT) == mc.requirements(), true)} END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BinnedSpectralContrastAngle_test.cpp
.cpp
2,744
89
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer$ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/COMPARISON/BinnedSpectralContrastAngle.h> #include <OpenMS/KERNEL/BinnedSpectrum.h> #include <OpenMS/FORMAT/DTAFile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(BinnedSpectralContrastAngle, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// BinnedSpectralContrastAngle* ptr = nullptr; BinnedSpectralContrastAngle* nullPointer = nullptr; START_SECTION(BinnedSpectralContrastAngle()) { ptr = new BinnedSpectralContrastAngle(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~BinnedSpectralContrastAngle()) { delete ptr; } END_SECTION ptr = new BinnedSpectralContrastAngle(); START_SECTION((BinnedSpectralContrastAngle(const BinnedSpectralContrastAngle &source))) { BinnedSpectralContrastAngle copy(*ptr); TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); } END_SECTION START_SECTION((BinnedSpectralContrastAngle& operator=(const BinnedSpectralContrastAngle &source))) { BinnedSpectralContrastAngle copy; copy = *ptr; TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); } END_SECTION START_SECTION((double operator()(const BinnedSpectrum &spec1, const BinnedSpectrum &spec2) const)) { PeakSpectrum s1, s2; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s2); s2.pop_back(); BinnedSpectrum bs1 (s1, 1.5, false, 2, BinnedSpectrum::DEFAULT_BIN_OFFSET_LOWRES); BinnedSpectrum bs2 (s2, 1.5, false, 2, BinnedSpectrum::DEFAULT_BIN_OFFSET_LOWRES); double score = (*ptr)(bs1, bs2); TEST_REAL_SIMILAR(score,0.999985) } END_SECTION START_SECTION((double operator()(const BinnedSpectrum &spec) const )) { PeakSpectrum s1; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); BinnedSpectrum bs1 (s1, 1.5, false, 2, BinnedSpectrum::DEFAULT_BIN_OFFSET_LOWRES); double score = (*ptr)(bs1); TEST_REAL_SIMILAR(score, 1); } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MRMRTNormalizer_test.cpp
.cpp
11,904
290
// 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/ANALYSIS/OPENSWATH/MRMRTNormalizer.h> /////////////////////////// using namespace std; using namespace OpenMS; /////////////////////////// START_TEST(MRMRTNormalizer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// class MRMRTNormalizer_test : public MRMRTNormalizer { public : static int jackknifeOutlierCandidate_(std::vector<double> & x, std::vector<double> & y) { return MRMRTNormalizer::jackknifeOutlierCandidate_(x, y); } static int residualOutlierCandidate_(std::vector<double> & x, std::vector<double> & y) { return MRMRTNormalizer::residualOutlierCandidate_(x, y); } }; // no constructor / destructor of static class // MRMRTNormalizer() // ~MRMRTNormalizer() // START_SECTION((static int jackknifeOutlierCandidate_(std::vector<double> & x, std::vector<double> & y))) { static const double arrx1[] = { 1.1, 2.0,3.3,3.9,4.9,6.2 }; std::vector<double> x1 (arrx1, arrx1 + sizeof(arrx1) / sizeof(arrx1[0]) ); static const double arry1[] = { 0.9, 1.9,3.0,3.7,5.2,6.1 }; std::vector<double> y1 (arry1, arry1 + sizeof(arry1) / sizeof(arry1[0]) ); int c1 = MRMRTNormalizer_test::jackknifeOutlierCandidate_(x1,y1); TEST_EQUAL(c1,4); static const double arrx2[] = { 1,2,3,4,5,6 }; std::vector<double> x2 (arrx2, arrx2 + sizeof(arrx2) / sizeof(arrx2[0]) ); static const double arry2[] = { 1,2,3,4,5,6}; std::vector<double> y2 (arry2, arry2 + sizeof(arry2) / sizeof(arry2[0]) ); int c2 = MRMRTNormalizer_test::jackknifeOutlierCandidate_(x2,y2); TEST_EQUAL(c2,0); } END_SECTION START_SECTION((static int residualOutlierCandidate_(std::vector<double> & x, std::vector<double> & y))) { static const double arrx1[] = { 1.1, 2.0,3.3,3.9,4.9,6.2 }; std::vector<double> x1 (arrx1, arrx1 + sizeof(arrx1) / sizeof(arrx1[0]) ); static const double arry1[] = { 0.9, 1.9,3.0,3.7,5.2,6.1 }; std::vector<double> y1 (arry1, arry1 + sizeof(arry1) / sizeof(arry1[0]) ); int c1 = MRMRTNormalizer_test::residualOutlierCandidate_(x1,y1); TEST_EQUAL(c1,4); static const double arrx2[] = { 1,2,3,4,5,6 }; std::vector<double> x2 (arrx2, arrx2 + sizeof(arrx2) / sizeof(arrx2[0]) ); static const double arry2[] = { 1,2,3,4,5,6}; std::vector<double> y2 (arry2, arry2 + sizeof(arry2) / sizeof(arry2[0]) ); int c2 = MRMRTNormalizer_test::residualOutlierCandidate_(x2,y2); TEST_EQUAL(c2,0); } END_SECTION START_SECTION((static std::vector<std::pair<double, double> > removeOutliersIterative(std::vector<std::pair<double, double> > & pairs, double rsq_limit, double coverage_limit, bool use_chauvenet, std::string method))) { { static const double arrx1[] = { 1.1,2.0,3.3,3.9,4.9,6.2 }; std::vector<double> x1 (arrx1, arrx1 + sizeof(arrx1) / sizeof(arrx1[0]) ); static const double arry1[] = { 0.9,1.9,3.0,3.7,5.2,6.1 }; std::vector<double> y1 (arry1, arry1 + sizeof(arry1) / sizeof(arry1[0]) ); std::vector<std::pair<double, double> > input1; for (Size i = 0; i < x1.size(); i++) { input1.push_back(std::make_pair(x1[i], y1[i])); } std::vector<std::pair<double, double> > output1 = MRMRTNormalizer::removeOutliersIterative(input1, 0.9, 0.5, true, "iter_residual"); TEST_EQUAL( output1.size() , input1.size() ); } { static const double arrx2[] = { 1.1,2.0,3.3,3.9,4.9,6.2 }; std::vector<double> x2 (arrx2, arrx2 + sizeof(arrx2) / sizeof(arrx2[0]) ); static const double arry2[] = { 0.9,1.9,7.0,3.7,5.2,6.1 }; std::vector<double> y2 (arry2, arry2 + sizeof(arry2) / sizeof(arry2[0]) ); std::vector<std::pair<double, double> > input2; for (Size i = 0; i < x2.size(); i++) { input2.push_back(std::make_pair(x2[i], y2[i])); } std::vector<std::pair<double, double> > output2 = MRMRTNormalizer::removeOutliersIterative(input2, 0.9, 0.5, true, "iter_residual"); TEST_EQUAL( output2.size() , input2.size() - 1 ); TEST_EQUAL( output2[0].first, input2[0].first ); TEST_EQUAL( output2[1].second, input2[1].second ); TEST_EQUAL( output2[2].first, input2[3].first ); TEST_EQUAL( output2[3].second, input2[4].second ); } { static const double arrx3[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,1,21,22,23,24,25,26,27,28,29,30 }; std::vector<double> x3 (arrx3, arrx3 + sizeof(arrx3) / sizeof(arrx3[0]) ); static const double arry3[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,22,23,24,25,26,27,28,29,30 }; std::vector<double> y3 (arry3, arry3 + sizeof(arry3) / sizeof(arry3[0]) ); std::vector<std::pair<double, double> > input3; for (Size i = 0; i < x3.size(); i++) { input3.push_back(std::make_pair(x3[i], y3[i])); } std::vector<std::pair<double, double> > output3 = MRMRTNormalizer::removeOutliersIterative(input3, 0.9, 0.2, true, "iter_residual"); TEST_EQUAL( output3.size() , input3.size() - 2 ); TEST_EQUAL( output3[18].first, input3[18].first ); TEST_EQUAL( output3[19].second, input3[21].second ); } // Test without chauvenet (use_chauvenet = false) { static const double arrx2[] = { 1.1,2.0,3.3,3.9,4.9,6.2 }; std::vector<double> x2 (arrx2, arrx2 + sizeof(arrx2) / sizeof(arrx2[0]) ); static const double arry2[] = { 0.9,1.9,7.0,3.7,5.2,6.1 }; std::vector<double> y2 (arry2, arry2 + sizeof(arry2) / sizeof(arry2[0]) ); std::vector<std::pair<double, double> > input2; for (Size i = 0; i < x2.size(); i++) { input2.push_back(std::make_pair(x2[i], y2[i])); } std::vector<std::pair<double, double> > output2 = MRMRTNormalizer::removeOutliersIterative(input2, 0.9, 0.5, false, "iter_residual"); TEST_EQUAL( output2.size() , input2.size() - 1 ); TEST_EQUAL( output2[0].first, input2[0].first ); TEST_EQUAL( output2[1].second, input2[1].second ); TEST_EQUAL( output2[2].first, input2[3].first ); TEST_EQUAL( output2[3].second, input2[4].second ); } { static const double arrx3[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,1,21,22,23,24,25,26,27,28,29,30 }; std::vector<double> x3 (arrx3, arrx3 + sizeof(arrx3) / sizeof(arrx3[0]) ); static const double arry3[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,22,23,24,25,26,27,28,29,30 }; std::vector<double> y3 (arry3, arry3 + sizeof(arry3) / sizeof(arry3[0]) ); std::vector<std::pair<double, double> > input3; for (Size i = 0; i < x3.size(); i++) { input3.push_back(std::make_pair(x3[i], y3[i])); } std::vector<std::pair<double, double> > output3 = MRMRTNormalizer::removeOutliersIterative(input3, 0.9, 0.2, false, "iter_residual"); TEST_EQUAL( output3.size() , input3.size() - 2 ); TEST_EQUAL( output3[18].first, input3[18].first ); TEST_EQUAL( output3[19].second, input3[21].second ); } // Tests with jackknife // TODO : find a testcase where jackknife and iter_residual are different! { static const double arrx2[] = { 1.1,2.0,3.3,3.9,4.9,6.2 }; std::vector<double> x2 (arrx2, arrx2 + sizeof(arrx2) / sizeof(arrx2[0]) ); static const double arry2[] = { 0.9,1.9,7.0,3.7,5.2,6.1 }; std::vector<double> y2 (arry2, arry2 + sizeof(arry2) / sizeof(arry2[0]) ); std::vector<std::pair<double, double> > input2; for (Size i = 0; i < x2.size(); i++) { input2.push_back(std::make_pair(x2[i], y2[i])); } std::vector<std::pair<double, double> > output2 = MRMRTNormalizer::removeOutliersIterative(input2, 0.9, 0.5, false, "iter_jackknife"); TEST_EQUAL( output2.size() , input2.size() - 1 ); TEST_EQUAL( output2[0].first, input2[0].first ); TEST_EQUAL( output2[1].second, input2[1].second ); TEST_EQUAL( output2[2].first, input2[3].first ); TEST_EQUAL( output2[3].second, input2[4].second ); } { static const double arrx3[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,1,21,22,23,24,25,26,27,28,29,30 }; std::vector<double> x3 (arrx3, arrx3 + sizeof(arrx3) / sizeof(arrx3[0]) ); static const double arry3[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,22,23,24,25,26,27,28,29,30 }; std::vector<double> y3 (arry3, arry3 + sizeof(arry3) / sizeof(arry3[0]) ); std::vector<std::pair<double, double> > input3; for (Size i = 0; i < x3.size(); i++) { input3.push_back(std::make_pair(x3[i], y3[i])); } std::vector<std::pair<double, double> > output3 = MRMRTNormalizer::removeOutliersIterative(input3, 0.9, 0.2, false, "iter_jackknife"); TEST_EQUAL( output3.size() , input3.size() - 2 ); TEST_EQUAL( output3[18].first, input3[18].first ); TEST_EQUAL( output3[19].second, input3[21].second ); } } END_SECTION START_SECTION(( static double chauvenet_probability(std::vector< double > &residuals, int pos) )) { static const double arr1[] = { 1,2,3,4,2,10,11,75,5,8,3,5,6,9,130 }; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 0), 0.61831553); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 1), 0.6387955); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 2), 0.65955473); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 3), 0.68057951); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 4), 0.6387955); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 5), 0.81146293); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 6), 0.8339146); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 7), 0.10161557); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 8), 0.70185552); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 9), 0.76703896); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 10), 0.65955473); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 11), 0.70185552); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 12), 0.72336784); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 13), 0.78916526); TEST_REAL_SIMILAR( MRMRTNormalizer::chauvenet_probability(data1, 14), 0.00126358); } END_SECTION START_SECTION((static bool chauvenet(std::vector<double> & residuals, int pos))) { static const double arr1[] = { 1,2,3,4,2,10,11,75,5,8,3,5,6,9,130 }; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 0), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 1), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 2), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 3), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 4), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 5), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 6), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 7), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 8), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 9), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 10), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 11), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 12), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 13), false); TEST_EQUAL( MRMRTNormalizer::chauvenet(data1, 14), true); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConfidenceScoring_test.cpp
.cpp
8,619
277
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hendrik Weisser $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/ConfidenceScoring.h> /////////////////////////// using namespace OpenMS; std::vector<TargetedExperiment::RetentionTime> get_rts_(double rt_val) { // add retention time for the peptide std::vector<TargetedExperiment::RetentionTime> retention_times; TargetedExperiment::RetentionTime retention_time; retention_time.setRT(rt_val); retention_time.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::NORMALIZED; retention_times.push_back(retention_time); return retention_times; } START_TEST(ConfidenceScoring<D>, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ConfidenceScoring* confidence_scoring_ptr = nullptr; ConfidenceScoring* confidence_scoring_nullPointer = nullptr; START_SECTION((explicit ConfidenceScoring(bool test_mode_=false))) confidence_scoring_ptr = new ConfidenceScoring; TEST_NOT_EQUAL(confidence_scoring_ptr, confidence_scoring_nullPointer) END_SECTION START_SECTION((virtual ~ConfidenceScoring())) delete confidence_scoring_ptr; END_SECTION START_SECTION((void initialize(TargetedExperiment library, Size n_decoys, Size n_transitions, TransformationDescription rt_trafo))) ConfidenceScoring scoring; TargetedExperiment library; TransformationDescription rt_trafo; scoring.initialize(library, 0, 0, rt_trafo); TEST_NOT_EQUAL(&scoring, confidence_scoring_nullPointer) END_SECTION START_SECTION((void initializeGlm(double intercept, double rt_coef, double int_coef))) ConfidenceScoring scoring; scoring.initializeGlm(0.0, -1.0, -1.0); TEST_NOT_EQUAL(&scoring, confidence_scoring_nullPointer) END_SECTION START_SECTION((void scoreMap(FeatureMap & features))) { ConfidenceScoring scoring(true); // initialize with test mode TargetedExperiment library; TransformationDescription rt_trafo; scoring.initialize(library, 0, 0, rt_trafo); scoring.initializeGlm(0.0, -1.0, -1.0); FeatureMap features; TEST_EXCEPTION(Exception::IllegalArgument, scoring.scoreMap(features)) // The input to the program is // - a transition library which contains peptides with corresponding assays // - a feature map where each feature corresponds to an assay (mapped with // MetaValue "PeptideRef") and each feature has as many subordinates as the // assay has transitions (mapped with MetaValue "native_id") // In this case we have 2 assays (pep_1 and pep_2) with 1 transition each // (tr_10 for pep_1 and tr_20 for pep_2). { TargetedExperiment::Peptide p; p.id = "pep_1"; p.rts = get_rts_(50.0); library.addPeptide(p); ReactionMonitoringTransition rm_trans; rm_trans.setNativeID("tr_10"); rm_trans.setPrecursorMZ(400.0); rm_trans.setProductMZ(500.0); rm_trans.setPeptideRef(p.id); rm_trans.setLibraryIntensity(500.0); library.addTransition(rm_trans); } { TargetedExperiment::Peptide p; p.id = "pep_2"; p.rts = get_rts_(60.0); library.addPeptide(p); ReactionMonitoringTransition rm_trans; rm_trans.setNativeID("tr_20"); rm_trans.setPrecursorMZ(400.0); rm_trans.setProductMZ(500.0); rm_trans.setPeptideRef(p.id); rm_trans.setLibraryIntensity(500.0); library.addTransition(rm_trans); } { Feature f; f.setRT(60.0); f.setMetaValue("PeptideRef", "pep_1"); f.setOverallQuality(-1); std::vector<Feature> subordinates; Feature sub; sub.setIntensity(1); sub.setMZ(500); sub.setMetaValue("native_id", "tr_10"); subordinates.push_back(sub); f.setSubordinates(subordinates); features.push_back(f); } { Feature f; f.setRT(60.0); f.setMetaValue("PeptideRef", "pep_2"); f.setOverallQuality(-1); std::vector<Feature> subordinates; Feature sub; sub.setIntensity(1); sub.setMZ(500); sub.setMetaValue("native_id", "tr_20"); subordinates.push_back(sub); f.setSubordinates(subordinates); features.push_back(f); } scoring.initialize(library, 0, 0, rt_trafo); scoring.scoreMap(features); TEST_REAL_SIMILAR(features[0].getOverallQuality(), 0.0); TEST_REAL_SIMILAR(features[1].getOverallQuality(), 1.0); // the absolute computed score for each feature TEST_REAL_SIMILAR(features[0].getMetaValue("GLM_score"), 0.0); TEST_REAL_SIMILAR(features[1].getMetaValue("GLM_score"), 0.5); // the local fdr score (1-quality) TEST_REAL_SIMILAR(features[0].getMetaValue("local_FDR"), 1.0); TEST_REAL_SIMILAR(features[1].getMetaValue("local_FDR"), 0.0); } END_SECTION START_SECTION(([EXTRA] test exceptions)) { ConfidenceScoring scoring(true); // initialize with test mode TargetedExperiment library; TransformationDescription rt_trafo; scoring.initialize(library, 0, 0, rt_trafo); scoring.initializeGlm(0.0, -1.0, -1.0); FeatureMap features; { TargetedExperiment::Peptide p; p.id = "pep_1"; p.rts = get_rts_(50.0); library.addPeptide(p); ReactionMonitoringTransition rm_trans; rm_trans.setNativeID("tr_10"); rm_trans.setPrecursorMZ(400.0); rm_trans.setProductMZ(500.0); rm_trans.setPeptideRef(p.id); rm_trans.setLibraryIntensity(500.0); library.addTransition(rm_trans); } { TargetedExperiment::Peptide p; p.id = "pep_2"; p.rts = get_rts_(60.0); library.addPeptide(p); ReactionMonitoringTransition rm_trans; rm_trans.setNativeID("tr_20"); rm_trans.setPrecursorMZ(400.0); rm_trans.setProductMZ(500.0); rm_trans.setPeptideRef(p.id); rm_trans.setLibraryIntensity(500.0); library.addTransition(rm_trans); } // If no meta value is present for the featuere, we cannot map it to the assay { Feature f; f.setRT(60.0); f.setOverallQuality(-1); //f.setMetaValue("PeptideRef", "pep_1"); features.push_back(f); } { Feature f; f.setRT(60.0); f.setOverallQuality(-1); //f.setMetaValue("PeptideRef", "pep_2"); features.push_back(f); } scoring.initialize(library, 0, 0, rt_trafo); TEST_EXCEPTION_WITH_MESSAGE(Exception::IllegalArgument, scoring.scoreMap(features), "Feature does not contain meta value 'PeptideRef' (reference to assay)") // After we add the meta value, we still should get an exception features[0].setMetaValue("PeptideRef", "pep_1"); features[1].setMetaValue("PeptideRef", "pep_2"); TEST_EXCEPTION_WITH_MESSAGE(Exception::IllegalArgument, scoring.scoreMap(features), "Feature intensities were empty - please provide feature subordinate with intensities") // An exception should be thrown if the sub-features cannot be mapped to the // transitions (e.g. the metavalue "native_id" is missing) { std::vector<Feature> subordinates; Feature sub; sub.setIntensity(1); sub.setMZ(500); // sub.setMetaValue("native_id", "tr_10"); subordinates.push_back(sub); features[0].setSubordinates(subordinates); } { std::vector<Feature> subordinates; Feature sub; sub.setIntensity(1); sub.setMZ(500); //sub.setMetaValue("native_id", "tr_20"); subordinates.push_back(sub); features[1].setSubordinates(subordinates); } TEST_EXCEPTION_WITH_MESSAGE(Exception::IllegalArgument, scoring.scoreMap(features), "Did not find a feature for each assay provided - each feature needs to have n subordinates with the meta-value 'native_id' set to the corresponding transition.") { std::vector<Feature> subordinates; Feature sub; sub.setIntensity(1); sub.setMZ(500); sub.setMetaValue("native_id", "tr_10"); subordinates.push_back(sub); features[0].setSubordinates(subordinates); } { std::vector<Feature> subordinates; Feature sub; sub.setIntensity(1); sub.setMZ(500); sub.setMetaValue("native_id", "tr_20"); subordinates.push_back(sub); features[1].setSubordinates(subordinates); } scoring.scoreMap(features); TEST_REAL_SIMILAR(features[0].getOverallQuality(), 0.0); TEST_REAL_SIMILAR(features[1].getOverallQuality(), 1.0); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CrossLinksDB_test.cpp
.cpp
9,571
259
// 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/CrossLinksDB.h> #include <limits> /////////////////////////// using namespace OpenMS; using namespace std; struct ResidueModificationOriginCmp { bool operator() (const ResidueModification* a, const ResidueModification* b) const { if (a->getOrigin() == b->getOrigin()) { return a->getTermSpecificity() < b->getTermSpecificity(); } return a->getOrigin() < b->getOrigin(); } }; START_TEST(CrossLinksDB, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CrossLinksDB* ptr = nullptr; CrossLinksDB* nullPointer = nullptr; START_SECTION(CrossLinksDB* getInstance()) { ptr = CrossLinksDB::getInstance(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(Size getNumberOfModifications() const) // range because data may change over time TEST_EQUAL(ptr->getNumberOfModifications() > 10, true); END_SECTION START_SECTION(const ResidueModification& getModification(Size index) const) TEST_EQUAL(!ptr->getModification(0)->getId().empty(), true) END_SECTION START_SECTION((void searchModifications(std::set<const ResidueModification*>& mods, const String& mod_name, const String& residue, ResidueModification::TermSpecificity term_spec) const)) { set<const ResidueModification*> mods; ptr->searchModifications(mods, "DSS", "K", ResidueModification::ANYWHERE); TEST_EQUAL(mods.size(), 1); TEST_STRING_EQUAL((*mods.begin())->getFullId(), "DSS (K)"); // terminal mod: ptr->searchModifications(mods, "DSS", "", ResidueModification::N_TERM); TEST_EQUAL(mods.size(), 1); ptr->searchModifications(mods, "EDC"); TEST_EQUAL(mods.size(), 8); ABORT_IF(mods.size() != 8); // Create a sorted set (sorted by getOrigin) instead of sorted by pointer // value -> this is more robust on different platforms. set<const ResidueModification*, ResidueModificationOriginCmp> mods_sorted; // Copy the mods into our sorted container set<const ResidueModification*>::const_iterator mod_it_ = mods.begin(); for (; mod_it_ != mods.end(); mod_it_++) { mods_sorted.insert((*mod_it_)); } set<const ResidueModification*, ResidueModificationOriginCmp>::const_iterator mod_it = mods_sorted.begin(); // EDC is a heterobifunctional cross-linker: one reactive site binds to C-term, D and E, the other to N-term, K, S, T // no distinction between the two sites implemented in CrossLinksDB or ResidueModification, the search engine has to take care of that for now TEST_EQUAL((*mod_it)->getOrigin(), 'D') TEST_STRING_EQUAL((*mod_it)->getId(), "EDC") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::ANYWHERE) ++mod_it; TEST_EQUAL((*mod_it)->getOrigin(), 'E') TEST_STRING_EQUAL((*mod_it)->getId(), "EDC") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::ANYWHERE) ++mod_it; TEST_EQUAL((*mod_it)->getOrigin(), 'K') TEST_STRING_EQUAL((*mod_it)->getId(), "EDC") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::ANYWHERE) ++mod_it; TEST_EQUAL((*mod_it)->getOrigin(), 'S') TEST_STRING_EQUAL((*mod_it)->getId(), "EDC") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::ANYWHERE) ++mod_it; TEST_EQUAL((*mod_it)->getOrigin(), 'T') TEST_STRING_EQUAL((*mod_it)->getId(), "EDC") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::ANYWHERE) ++mod_it; TEST_EQUAL((*mod_it)->getOrigin(), 'X') TEST_STRING_EQUAL((*mod_it)->getId(), "EDC") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::C_TERM) ++mod_it; TEST_EQUAL((*mod_it)->getOrigin(), 'X') TEST_STRING_EQUAL((*mod_it)->getId(), "EDC") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::N_TERM) ++mod_it; TEST_EQUAL((*mod_it)->getOrigin(), 'Y') TEST_STRING_EQUAL((*mod_it)->getId(), "EDC") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::ANYWHERE) ptr->searchModifications(mods, "EDC", "", ResidueModification::C_TERM); TEST_EQUAL(mods.size(), 1) ABORT_IF(mods.size() != 1) // Copy the mods into our sorted container mods_sorted.clear(); for (mod_it_ = mods.begin(); mod_it_ != mods.end(); mod_it_++) { mods_sorted.insert((*mod_it_)); } mod_it = mods_sorted.begin(); TEST_EQUAL((*mod_it)->getOrigin(), 'X') TEST_STRING_EQUAL((*mod_it)->getId(), "EDC") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::C_TERM) // no match, thus mods should be empty ptr->searchModifications(mods, "EDC", "R", ResidueModification::ANYWHERE); TEST_EQUAL(mods.size(), 0) } END_SECTION START_SECTION((void searchModificationsByDiffMonoMass(std::vector<String>& mods, double mass, double max_error, const String& residue, ResidueModification::TermSpecificity term_spec))) { vector<String> mods; // these two cross-linkers have exactly the same mass / structure after the cross-linking reaction ptr->searchModificationsByDiffMonoMass(mods, 138.06807961, 0.00001, "K"); TEST_EQUAL(find(mods.begin(), mods.end(), "DSS (K)") != mods.end(), true); TEST_EQUAL(find(mods.begin(), mods.end(), "BS3 (K)") != mods.end(), true); // something exotic.. mods should return empty (without clearing it before) ptr->searchModificationsByDiffMonoMass(mods, 800000000.0, 0.1, "S"); TEST_EQUAL(mods.size(), 0); // terminal mod: ptr->searchModificationsByDiffMonoMass(mods, 138.068, 0.01, "", ResidueModification::N_TERM); set<String> uniq_mods; for (vector<String>::const_iterator it = mods.begin(); it != mods.end(); ++it) { uniq_mods.insert(*it); } TEST_EQUAL(mods.size(), 2); TEST_EQUAL(uniq_mods.size(), 2); TEST_EQUAL(uniq_mods.find("BS3 (N-term)") != uniq_mods.end(), true); // something exotic.. mods should return empty (without clearing it before) ptr->searchModificationsByDiffMonoMass(mods, 4200000, 0.1, "", ResidueModification::N_TERM); TEST_EQUAL(mods.size(), 0); ptr->searchModificationsByDiffMonoMass(mods, 138.068, 0.01); uniq_mods.clear(); for (vector<String>::const_iterator it = mods.begin(); it != mods.end(); ++it) { uniq_mods.insert(*it); } TEST_EQUAL(uniq_mods.find("DSS (K)") != uniq_mods.end(), true); TEST_EQUAL(uniq_mods.find("BS3 (K)") != uniq_mods.end(), true); TEST_EQUAL(uniq_mods.find("BS3 (N-term)") != uniq_mods.end(), true); TEST_EQUAL(uniq_mods.find("DSS (S)") != uniq_mods.end(), true); // something exotic.. mods should return empty (without clearing it before) ptr->searchModificationsByDiffMonoMass(mods, 800000000.0, 0.1); TEST_EQUAL(mods.size(), 0); } END_SECTION START_SECTION((const ResidueModification& getModification(const String& mod_name, const String& residue, ResidueModification::TermSpecificity term_spec) const)) { TEST_EQUAL(ptr->getModification("EDC (E)")->getFullId(), "EDC (E)"); TEST_EQUAL(ptr->getModification("EDC (E)")->getId(), "EDC"); TEST_EQUAL(ptr->getModification("DSS", "S", ResidueModification::ANYWHERE)->getId(), "DSS"); TEST_EQUAL(ptr->getModification("DSS", "S", ResidueModification::ANYWHERE)->getFullId(), "DSS (S)"); // terminal mod: TEST_EQUAL(ptr->getModification("DSS", "", ResidueModification::N_TERM)->getId(), "DSS"); TEST_EQUAL(ptr->getModification("BS3", "", ResidueModification::N_TERM)->getFullId(), "BS3 (N-term)"); TEST_EQUAL(ptr->getModification("EDC", "", ResidueModification::N_TERM)->getFullId(), "EDC (N-term)"); } END_SECTION START_SECTION((Size findModificationIndex(const String& mod_name) const)) { Size index = numeric_limits<Size>::max(); index = ptr->findModificationIndex("EDC (T)"); TEST_NOT_EQUAL(index, numeric_limits<Size>::max()); } END_SECTION START_SECTION(void readFromOBOFile(const String& filename)) // implicitely tested above NOT_TESTABLE END_SECTION START_SECTION(void readFromUnimodXMLFile(const String& filename)) // just provided for convenience at the moment NOT_TESTABLE END_SECTION START_SECTION((void getAllSearchModifications(std::vector<String>& modifications))) { vector<String> mods; ptr->getAllSearchModifications(mods); TEST_EQUAL(find(mods.begin(), mods.end(), "EDC (S)") != mods.end(), true); TEST_EQUAL(find(mods.begin(), mods.end(), "DSS (K)") != mods.end(), true); TEST_EQUAL(find(mods.begin(), mods.end(), "BS3 (N-term)") != mods.end(), true); TEST_EQUAL(find(mods.begin(), mods.end(), "DSS") != mods.end(), false); TEST_EQUAL(find(mods.begin(), mods.end(), "EDC (E)") != mods.end(), true); // repeat search .. return size should be the same Size old_size=mods.size(); ptr->getAllSearchModifications(mods); TEST_EQUAL(mods.size(), old_size); } END_SECTION START_SECTION((bool addModification(ResidueModification* modification))) { TEST_EQUAL(ptr->has("DSS (C-term)"), false); std::unique_ptr<ResidueModification> modification(new ResidueModification()); modification->setFullId("DSS (C-term)"); ptr->addModification(std::move(modification)); TEST_EQUAL(ptr->has("DSS (C-term)"), true); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IonSource_test.cpp
.cpp
8,727
257
// 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/IonSource.h> /////////////////////////// #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; START_TEST(IonSource, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// IonSource* ptr = nullptr; IonSource* nullPointer = nullptr; START_SECTION((IonSource())) ptr = new IonSource(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~IonSource())) delete ptr; END_SECTION START_SECTION(Int getOrder() const) IonSource tmp; TEST_EQUAL(tmp.getOrder(),0) END_SECTION START_SECTION(void setOrder(Int order)) IonSource tmp; tmp.setOrder(4711); TEST_EQUAL(tmp.getOrder(),4711) END_SECTION START_SECTION((InletType getInletType() const)) IonSource tmp; TEST_EQUAL(tmp.getInletType(),IonSource::InletType::INLETNULL); END_SECTION START_SECTION((void setInletType(InletType inlet_type))) IonSource tmp; tmp.setInletType(IonSource::InletType::DIRECT); TEST_EQUAL(tmp.getInletType(),IonSource::InletType::DIRECT); END_SECTION START_SECTION((IonizationMethod getIonizationMethod() const)) IonSource tmp; TEST_EQUAL(tmp.getIonizationMethod(),IonSource::IonizationMethod::IONMETHODNULL); END_SECTION START_SECTION((void setIonizationMethod(IonizationMethod ionization_type))) IonSource tmp; tmp.setIonizationMethod(IonSource::IonizationMethod::ESI); TEST_EQUAL(tmp.getIonizationMethod(),IonSource::IonizationMethod::ESI); END_SECTION START_SECTION((Polarity getPolarity() const)) IonSource tmp; TEST_EQUAL(tmp.getPolarity(),IonSource::Polarity::POLNULL); END_SECTION START_SECTION((void setPolarity(Polarity polarity))) IonSource tmp; tmp.setPolarity(IonSource::Polarity::POSITIVE); TEST_EQUAL(tmp.getPolarity(),IonSource::Polarity::POSITIVE); END_SECTION START_SECTION((IonSource(const IonSource& source))) IonSource tmp; tmp.setInletType(IonSource::InletType::DIRECT); tmp.setIonizationMethod(IonSource::IonizationMethod::ESI); tmp.setPolarity(IonSource::Polarity::POSITIVE); tmp.setMetaValue("label",String("label")); tmp.setOrder(45); IonSource tmp2(tmp); TEST_EQUAL(tmp2.getPolarity(),IonSource::Polarity::POSITIVE); TEST_EQUAL(tmp2.getInletType(),IonSource::InletType::DIRECT); TEST_EQUAL(tmp2.getIonizationMethod(),IonSource::IonizationMethod::ESI); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_EQUAL(tmp2.getOrder(),45) END_SECTION START_SECTION((IonSource& operator= (const IonSource& source))) IonSource tmp; tmp.setInletType(IonSource::InletType::DIRECT); tmp.setIonizationMethod(IonSource::IonizationMethod::ESI); tmp.setPolarity(IonSource::Polarity::POSITIVE); tmp.setMetaValue("label",String("label")); tmp.setOrder(45); IonSource tmp2; tmp2 = tmp; TEST_EQUAL(tmp2.getPolarity(),IonSource::Polarity::POSITIVE); TEST_EQUAL(tmp2.getInletType(),IonSource::InletType::DIRECT); TEST_EQUAL(tmp2.getIonizationMethod(),IonSource::IonizationMethod::ESI); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_EQUAL(tmp2.getOrder(),45) tmp2 = IonSource(); TEST_EQUAL(tmp2.getPolarity(),IonSource::Polarity::POLNULL); TEST_EQUAL(tmp2.getInletType(),IonSource::InletType::INLETNULL); TEST_EQUAL(tmp2.getIonizationMethod(),IonSource::IonizationMethod::IONMETHODNULL); TEST_EQUAL(tmp2.getMetaValue("label").isEmpty(), true); TEST_EQUAL(tmp2.getOrder(),0) END_SECTION START_SECTION((bool operator== (const IonSource& rhs) const)) IonSource edit,empty; TEST_EQUAL(edit==empty,true); edit = empty; edit.setInletType(IonSource::InletType::DIRECT); TEST_EQUAL(edit==empty,false); edit = empty; edit.setIonizationMethod(IonSource::IonizationMethod::ESI); TEST_EQUAL(edit==empty,false); edit = empty; edit.setPolarity(IonSource::Polarity::POSITIVE); TEST_EQUAL(edit==empty,false); edit = empty; edit.setMetaValue("label",String("label")); TEST_EQUAL(edit==empty,false); edit = empty; edit.setOrder(45); TEST_EQUAL(edit==empty,false); END_SECTION START_SECTION((bool operator!= (const IonSource& rhs) const)) IonSource edit,empty; TEST_EQUAL(edit!=empty,false); edit = empty; edit.setInletType(IonSource::InletType::DIRECT); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setIonizationMethod(IonSource::IonizationMethod::ESI); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setPolarity(IonSource::Polarity::POSITIVE); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setMetaValue("label",String("label")); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setOrder(45); TEST_EQUAL(edit!=empty,true); END_SECTION START_SECTION((static StringList getAllNamesOfInletType())) StringList names = IonSource::getAllNamesOfInletType(); TEST_EQUAL(names.size(), static_cast<size_t>(IonSource::InletType::SIZE_OF_INLETTYPE)); TEST_EQUAL(names[static_cast<size_t>(IonSource::InletType::INLETNULL)], "Unknown"); TEST_EQUAL(names[static_cast<size_t>(IonSource::InletType::DIRECT)], "Direct"); TEST_EQUAL(names[static_cast<size_t>(IonSource::InletType::NANOSPRAY)], "Nanospray inlet"); END_SECTION START_SECTION((static StringList getAllNamesOfIonizationMethod())) StringList names = IonSource::getAllNamesOfIonizationMethod(); TEST_EQUAL(names.size(), static_cast<size_t>(IonSource::IonizationMethod::SIZE_OF_IONIZATIONMETHOD)); TEST_EQUAL(names[static_cast<size_t>(IonSource::IonizationMethod::IONMETHODNULL)], "Unknown"); TEST_EQUAL(names[static_cast<size_t>(IonSource::IonizationMethod::ESI)], "Electrospray ionisation"); TEST_EQUAL(names[static_cast<size_t>(IonSource::IonizationMethod::MALDI)], "Matrix-assisted laser desorption ionization"); END_SECTION START_SECTION((static StringList getAllNamesOfPolarity())) StringList names = IonSource::getAllNamesOfPolarity(); TEST_EQUAL(names.size(), static_cast<size_t>(IonSource::Polarity::SIZE_OF_POLARITY)); TEST_EQUAL(names[static_cast<size_t>(IonSource::Polarity::POLNULL)], "unknown"); TEST_EQUAL(names[static_cast<size_t>(IonSource::Polarity::POSITIVE)], "positive"); TEST_EQUAL(names[static_cast<size_t>(IonSource::Polarity::NEGATIVE)], "negative"); END_SECTION START_SECTION(([EXTRA] std::hash<IonSource>)) { // Test that equal objects have equal hashes IonSource is1, is2; is1.setInletType(IonSource::InletType::DIRECT); is1.setIonizationMethod(IonSource::IonizationMethod::ESI); is1.setPolarity(IonSource::Polarity::POSITIVE); is1.setOrder(45); is1.setMetaValue("label", String("test")); is2.setInletType(IonSource::InletType::DIRECT); is2.setIonizationMethod(IonSource::IonizationMethod::ESI); is2.setPolarity(IonSource::Polarity::POSITIVE); is2.setOrder(45); is2.setMetaValue("label", String("test")); TEST_EQUAL(is1 == is2, true) TEST_EQUAL(std::hash<IonSource>{}(is1), std::hash<IonSource>{}(is2)) // Test that different objects (likely) have different hashes IonSource is3; is3.setInletType(IonSource::InletType::BATCH); is3.setIonizationMethod(IonSource::IonizationMethod::MALDI); is3.setPolarity(IonSource::Polarity::NEGATIVE); is3.setOrder(10); TEST_EQUAL(is1 == is3, false) // Hash values should differ (not guaranteed but highly likely for different inputs) TEST_NOT_EQUAL(std::hash<IonSource>{}(is1), std::hash<IonSource>{}(is3)) // Test use in unordered_set std::unordered_set<IonSource> ion_source_set; ion_source_set.insert(is1); ion_source_set.insert(is2); // Duplicate, should not increase size ion_source_set.insert(is3); TEST_EQUAL(ion_source_set.size(), 2) // Test use in unordered_map std::unordered_map<IonSource, int> ion_source_map; ion_source_map[is1] = 1; ion_source_map[is2] = 2; // Should overwrite is1's value ion_source_map[is3] = 3; TEST_EQUAL(ion_source_map.size(), 2) TEST_EQUAL(ion_source_map[is1], 2) TEST_EQUAL(ion_source_map[is3], 3) // Test that default-constructed objects have equal hashes IonSource default1, default2; TEST_EQUAL(default1 == default2, true) TEST_EQUAL(std::hash<IonSource>{}(default1), std::hash<IonSource>{}(default2)) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GridBasedClustering_test.cpp
.cpp
3,571
89
// 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/KERNEL/StandardTypes.h> #include <OpenMS/DATASTRUCTURES/DRange.h> #include <OpenMS/ML/CLUSTERING/GridBasedClustering.h> #include <OpenMS/FEATUREFINDER/MultiplexClustering.h> using namespace OpenMS; START_TEST(GridBasedClustering, "$Id$") MultiplexClustering::MultiplexDistance metric(1); std::vector<double> grid_spacing_x; std::vector<double> grid_spacing_y; for (double i = 0; i <= 10; ++i) { grid_spacing_x.push_back(i); grid_spacing_y.push_back(i); } std::vector<double> data_x; std::vector<double> data_y; std::vector<int> properties_A; std::vector<int> properties_B; for (int i = 0; i < 1000; ++i) { data_x.push_back(5*(sin(static_cast<double>(i))+1)); data_y.push_back(5*(sin(static_cast<double>(i+18))+1)); properties_A.push_back(1); // Should be the same within each cluster. properties_B.push_back(i); // Should be different within each cluster. } GridBasedClustering<MultiplexClustering::MultiplexDistance>* nullPointer = nullptr; GridBasedClustering<MultiplexClustering::MultiplexDistance>* ptr; START_SECTION(GridBasedClustering(Metric metric, const std::vector<double> &data_x, const std::vector<double> &data_y, const std::vector<int> &properties_A, const std::vector<int> &properties_B, std::vector<double> grid_spacing_x, std::vector<double> grid_spacing_y)) GridBasedClustering<MultiplexClustering::MultiplexDistance> clustering(metric, data_x, data_y, properties_A, properties_B, grid_spacing_x, grid_spacing_y); clustering.cluster(); TEST_EQUAL(clustering.getResults().size(), 12); ptr = new GridBasedClustering<MultiplexClustering::MultiplexDistance>(metric, data_x, data_y, properties_A, properties_B, grid_spacing_x, grid_spacing_y); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION START_SECTION(GridBasedClustering(Metric metric, const std::vector<double> &data_x, const std::vector<double> &data_y, std::vector<double> grid_spacing_x, std::vector<double> grid_spacing_y)) GridBasedClustering<MultiplexClustering::MultiplexDistance> clustering(metric, data_x, data_y, grid_spacing_x, grid_spacing_y); clustering.cluster(); TEST_EQUAL(clustering.getResults().size(), 12); ptr = new GridBasedClustering<MultiplexClustering::MultiplexDistance>(metric, data_x, data_y, grid_spacing_x, grid_spacing_y); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION GridBasedClustering<MultiplexClustering::MultiplexDistance> clustering(metric, data_x, data_y, grid_spacing_x, grid_spacing_y); START_SECTION(void cluster()) clustering.cluster(); TEST_EQUAL(clustering.getResults().size(), 12); END_SECTION START_SECTION(std::map<int Cluster> getResults() const) clustering.cluster(); TEST_EQUAL(clustering.getResults().size(), 12); END_SECTION START_SECTION(void extendClustersY()) clustering.cluster(); clustering.extendClustersY(); TEST_EQUAL(clustering.getResults().size(), 11); END_SECTION START_SECTION(void removeSmallClustersY(double threshold_y)) clustering.cluster(); clustering.removeSmallClustersY(0.9); TEST_EQUAL(clustering.getResults().size(), 8); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MassTrace_test.cpp
.cpp
20,721
821
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Erhan Kenar, Holger Franken, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/KERNEL/MassTrace.h> /////////////////////////// using namespace OpenMS; using namespace std; PeakType fillPeak(double rt, double mz, double it) { PeakType p; p.setIntensity((OpenMS::Peak2D::IntensityType)it); p.setMZ(mz); p.setRT((rt)); return p; } START_TEST(MassTrace, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MassTrace* d_ptr = nullptr; MassTrace* nullPointer = nullptr; START_SECTION((MassTrace())) { d_ptr = new MassTrace; TEST_NOT_EQUAL(d_ptr, nullPointer); } END_SECTION START_SECTION((~MassTrace())) { delete d_ptr; } END_SECTION std::vector<PeakType> peak_vec; std::list<PeakType> peak_lst; PeakType tmp_peak0 = fillPeak(152.22, 230.10223, 542.0); peak_vec.push_back(tmp_peak0); peak_lst.push_back(tmp_peak0); PeakType tmp_peak1 = fillPeak(153.23, 230.10235, 542293.0); peak_vec.push_back(tmp_peak1); peak_lst.push_back(tmp_peak1); PeakType tmp_peak2 = fillPeak(154.21, 230.10181, 18282393.0); peak_vec.push_back(tmp_peak2); peak_lst.push_back(tmp_peak2); PeakType tmp_peak3 = fillPeak(155.24, 230.10229, 33329535.0); peak_vec.push_back(tmp_peak3); peak_lst.push_back(tmp_peak3); PeakType tmp_peak4 = fillPeak(156.233, 230.10116, 17342933.0); peak_vec.push_back(tmp_peak4); peak_lst.push_back(tmp_peak4); PeakType tmp_peak5 = fillPeak(157.24, 230.10198, 333291.0); peak_vec.push_back(tmp_peak5); peak_lst.push_back(tmp_peak5); PeakType tmp_peak6 = fillPeak(158.238, 230.10254, 339.0); peak_vec.push_back(tmp_peak6); peak_lst.push_back(tmp_peak6); String si, sm, sr; for (Size i = 0; i<peak_vec.size(); ++i) { si += ", " + String(peak_vec[i].getIntensity()); sm += ", " + String(peak_vec[i].getMZ()); sr += ", " + String(peak_vec[i].getRT()); } std::cout << sr << "\n" << sm << "\n" << si << "\n\n"; ///////////////////////////////////////////////////////////// // detailed constructors test ///////////////////////////////////////////////////////////// START_SECTION((MassTrace(const std::list<PeakType>& trace_peaks))) { MassTrace tmp_mt(peak_lst); std::list<PeakType>::const_iterator l_it = peak_lst.begin(); for (MassTrace::const_iterator m_it = tmp_mt.begin(); m_it != tmp_mt.end(); ++m_it) { TEST_EQUAL(*l_it, *m_it); ++l_it; } TEST_REAL_SIMILAR(tmp_mt.getAverageMS1CycleTime(), (tmp_peak6.getRT() - tmp_peak0.getRT()) / (7-1)); } END_SECTION ///// START_SECTION((MassTrace(const std::vector<PeakType>& trace_peaks))) { MassTrace tmp_mt(peak_vec); std::vector<PeakType>::const_iterator v_it = peak_vec.begin(); for (MassTrace::const_iterator m_it = tmp_mt.begin(); m_it != tmp_mt.end(); ++m_it) { TEST_EQUAL(*v_it, *m_it); ++v_it; } TEST_REAL_SIMILAR(tmp_mt.getAverageMS1CycleTime(), (tmp_peak6.getRT() - tmp_peak0.getRT()) / (7-1)); } END_SECTION ///// MassTrace test_mt(peak_lst); test_mt.updateWeightedMeanRT(); test_mt.updateWeightedMeanMZ(); ///////////////////////////////////////////////////////////// // operator tests ///////////////////////////////////////////////////////////// START_SECTION((PeakType& operator[](const Size &mt_idx))) { TEST_REAL_SIMILAR(test_mt[1].getRT(), 153.23); TEST_REAL_SIMILAR(test_mt[1].getMZ(), 230.10235); TEST_REAL_SIMILAR(test_mt[1].getIntensity(), (OpenMS::Peak2D::IntensityType)542293.0); TEST_REAL_SIMILAR(test_mt[4].getRT(), 156.233); TEST_REAL_SIMILAR(test_mt[4].getMZ(), 230.10116); TEST_REAL_SIMILAR(test_mt[4].getIntensity(), (OpenMS::Peak2D::IntensityType)17342933.0); } END_SECTION ///// START_SECTION((const PeakType& operator[](const Size &mt_idx) const )) { const MassTrace test_mt_const(test_mt); double rt1 = test_mt_const[1].getRT(); double mz1 = test_mt_const[1].getMZ(); double int1 = test_mt_const[1].getIntensity(); double rt2 = test_mt_const[4].getRT(); double mz2 = test_mt_const[4].getMZ(); double int2 = test_mt_const[4].getIntensity(); TEST_REAL_SIMILAR(rt1, 153.23); TEST_REAL_SIMILAR(mz1, 230.10235); TEST_REAL_SIMILAR(int1, 542293.0); TEST_REAL_SIMILAR(rt2, 156.233); TEST_REAL_SIMILAR(mz2, 230.10116); TEST_REAL_SIMILAR(int2, 17342933.0); } END_SECTION ///////////////////////////////////////////////////////////// // iterator tests ///////////////////////////////////////////////////////////// std::vector<PeakType>::iterator start_it = peak_vec.begin(); std::vector<PeakType>::iterator end_it = peak_vec.end(); std::vector<PeakType>::reverse_iterator rstart_it = peak_vec.rbegin(); std::vector<PeakType>::reverse_iterator rend_it = peak_vec.rend(); std::vector<PeakType>::const_iterator const_start_it = peak_vec.begin(); std::vector<PeakType>::const_iterator const_end_it = peak_vec.end(); std::vector<PeakType>::const_reverse_iterator const_rstart_it = peak_vec.rbegin(); std::vector<PeakType>::const_reverse_iterator const_rend_it = peak_vec.rend(); START_SECTION((iterator begin())) { MassTrace::iterator mt_it = test_mt.begin(); TEST_EQUAL(*start_it, *mt_it); } END_SECTION ///// START_SECTION((iterator end())) { MassTrace::iterator mt_it = test_mt.begin(); for ( ; mt_it != test_mt.end() - 1; ++mt_it) { } TEST_EQUAL(*(end_it - 1), *mt_it); } END_SECTION ///// START_SECTION((const_iterator begin() const)) { MassTrace::const_iterator mt_it = test_mt.begin(); TEST_EQUAL(*const_start_it, *mt_it); } END_SECTION ///// START_SECTION((const_iterator end() const)) { MassTrace::const_iterator mt_it = test_mt.begin(); for ( ; mt_it != test_mt.end() - 1; ++mt_it) { } TEST_EQUAL(*(const_end_it - 1), *mt_it); } END_SECTION ///// START_SECTION((reverse_iterator rbegin())) { MassTrace::reverse_iterator mt_it = test_mt.rbegin(); TEST_EQUAL(*rstart_it, *mt_it); } END_SECTION ///// START_SECTION((reverse_iterator rend())) { MassTrace::reverse_iterator mt_it = test_mt.rbegin(); for ( ; mt_it != test_mt.rend() - 1; ++mt_it) { } TEST_EQUAL(*(rend_it - 1), *mt_it); } END_SECTION ///// START_SECTION((const_reverse_iterator rbegin() const)) { MassTrace::const_reverse_iterator mt_it = test_mt.rbegin(); TEST_EQUAL(*const_rstart_it, *mt_it); } END_SECTION ///// START_SECTION((const_reverse_iterator rend() const)) { MassTrace::const_reverse_iterator mt_it = test_mt.rbegin(); for ( ; mt_it != test_mt.rend() - 1; ++mt_it) { } TEST_EQUAL(*(const_rend_it - 1), *mt_it); } END_SECTION ///////////////////////////////////////////////////////////// // accessor method tests ///////////////////////////////////////////////////////////// START_SECTION((Size getSize() const)) { Size test_mt_size = test_mt.getSize(); TEST_EQUAL(test_mt_size, 7); } END_SECTION ///// START_SECTION((String getLabel() const )) { const String test_mt_label = test_mt.getLabel(); TEST_EQUAL(test_mt_label, ""); } END_SECTION ///// START_SECTION((void setLabel(const String& label))) { test_mt.setLabel("TEST_TRACE"); String test_mt_label = test_mt.getLabel(); TEST_EQUAL(test_mt_label, "TEST_TRACE"); } END_SECTION ///// START_SECTION((double getCentroidMZ() const )) { MassTrace test_mt_const(test_mt); double test_mt_cent_mz = test_mt_const.getCentroidMZ(); TEST_REAL_SIMILAR(test_mt_cent_mz, 230.10188); } END_SECTION ///// START_SECTION((double getCentroidRT() const )) { MassTrace test_mt_const(test_mt); double test_mt_cent_rt = test_mt_const.getCentroidRT(); TEST_REAL_SIMILAR(test_mt_cent_rt, 155.214671250425); } END_SECTION ///// START_SECTION((double getAverageMS1CycleTime() const)) { MassTrace tmp_mt(peak_lst); TEST_REAL_SIMILAR(tmp_mt.getAverageMS1CycleTime(), (tmp_peak6.getRT() - tmp_peak0.getRT()) / (7-1)); } END_SECTION ///// START_SECTION((void updateWeightedMZsd())) { MassTrace empty_trace; TEST_EXCEPTION(Exception::InvalidValue, empty_trace.updateWeightedMZsd()); std::vector<PeakType> peaks; PeakType p1, p2; p1.setMZ(123.123); p1.setIntensity(0.0); p2.setMZ(123.321); p2.setIntensity(0.0); peaks.push_back(p1); peaks.push_back(p2); MassTrace zero_int_mt(peaks); TEST_EXCEPTION(Exception::InvalidValue, zero_int_mt.updateWeightedMZsd()); test_mt.updateWeightedMZsd(); double test_mt_sd = test_mt.getCentroidSD(); TEST_REAL_SIMILAR(test_mt_sd, 0.0004594); } END_SECTION ///// START_SECTION((double getCentroidSD() const )) { MassTrace test_mt_const(test_mt); double test_mt_sd = test_mt_const.getCentroidSD(); TEST_REAL_SIMILAR(test_mt_sd, 0.0004594); } END_SECTION ///// START_SECTION((double getTraceLength() const )) { const MassTrace test_mt_const(test_mt); double mt_length = test_mt_const.getTraceLength(); TEST_REAL_SIMILAR(mt_length, 6.018) } END_SECTION ///// std::vector<double> smoothed_ints; smoothed_ints.push_back(500.0); smoothed_ints.push_back(540000.0); smoothed_ints.push_back(18000000.0); smoothed_ints.push_back(33000000.0); smoothed_ints.push_back(17500000.0); smoothed_ints.push_back(540000.0); smoothed_ints.push_back(549223.0); smoothed_ints.push_back(300.0); START_SECTION((void setSmoothedIntensities(const std::vector<double>& db_vec))) { TEST_EXCEPTION(Exception::InvalidValue, test_mt.setSmoothedIntensities(smoothed_ints)); smoothed_ints.pop_back(); test_mt.setSmoothedIntensities(smoothed_ints); TEST_EQUAL(test_mt.getSmoothedIntensities().size(), smoothed_ints.size()) } END_SECTION ///// START_SECTION((std::vector<double> getSmoothedIntensities())) { std::vector<double> smoothed_vec = test_mt.getSmoothedIntensities(); TEST_EQUAL(smoothed_vec.empty(), false); TEST_EQUAL(smoothed_vec.size(), smoothed_ints.size()); } END_SECTION ///// test_mt.setSmoothedIntensities(smoothed_ints); START_SECTION((double getIntensity(bool smoothed) const)) { test_mt.estimateFWHM(true); double smoothed_area = test_mt.getIntensity(true); TEST_REAL_SIMILAR(smoothed_area, 69505990.0000001); double raw_area = test_mt.getIntensity(false); TEST_REAL_SIMILAR(raw_area, 69863097.2125001); } END_SECTION ///// START_SECTION((double getMaxIntensity(bool smoothed) const)) { double smoothed_maxint = test_mt.getMaxIntensity(true); TEST_REAL_SIMILAR(smoothed_maxint, 33000000.0); double raw_maxint= test_mt.getMaxIntensity(false); TEST_REAL_SIMILAR(raw_maxint, 33329536.0); } END_SECTION ///// START_SECTION((double getMaxIntensity(bool) const )) { const MassTrace test_mt_const(test_mt); double smoothed_maxint = test_mt_const.getMaxIntensity(true); TEST_REAL_SIMILAR(smoothed_maxint, 33000000.0); double raw_maxint= test_mt_const.getMaxIntensity(false); TEST_REAL_SIMILAR(raw_maxint, 33329536.0); } END_SECTION ///// START_SECTION((const std::vector<double>& getSmoothedIntensities() const)) { std::vector<double> smoothed_vec = test_mt.getSmoothedIntensities(); TEST_EQUAL(smoothed_vec.empty(), false); TEST_EQUAL(smoothed_vec.size(), smoothed_ints.size()); } END_SECTION ///// MassTrace test_mt2(peak_vec), test_mt3; test_mt2.updateWeightedMeanRT(); test_mt2.updateWeightedMeanMZ(); START_SECTION((double getFWHM() const)) { double test_mt_fwhm = test_mt.getFWHM(); TEST_REAL_SIMILAR(test_mt_fwhm, 3.05481743986255); } END_SECTION ///// START_SECTION((double computeSmoothedPeakArea() const)) { double peak_area = test_mt.computeSmoothedPeakArea(); TEST_REAL_SIMILAR(peak_area, 70303689.0475001) } END_SECTION ///// // create Masstraces which can be used to test missing RT scans std::vector<PeakType> peak_vec_red; double rt[] = {152.0, 153.0, 154.0, 155.0, 156.0, 157.0, 158.0, 159.0, 160.0}; double it[] = { 542, 542293, 1.82824e+007, 3.33295e+007, 3.33295e+007, 3.33295e+007, 1.73429e+007, 333291, 339}; for (Size i=0; i<9; ++i) { peak_vec_red.push_back(fillPeak(rt[i], 100.0, it[i])); } std::vector<PeakType> peak_vec_red2 = peak_vec_red; peak_vec_red2.erase(peak_vec_red2.begin() + 4); MassTrace tmp_mt(peak_vec_red); MassTrace tmp_mt2(peak_vec_red2); START_SECTION((double computePeakArea() const)) { double peak_area = test_mt.computePeakArea(); TEST_REAL_SIMILAR(peak_area, 70303710.2575001) // ensure that missing peaks (=scans) do not impact quantification TEST_REAL_SIMILAR(tmp_mt.computePeakArea(), tmp_mt2.computePeakArea()) } END_SECTION ///// START_SECTION((double computeFwhmAreaSmooth() const)) { double peak_area = test_mt.computeFwhmAreaSmooth(); TEST_REAL_SIMILAR(peak_area, 69505990.0000001) } END_SECTION ///// START_SECTION((double computeFwhmArea() const)) { double peak_area = test_mt.computeFwhmArea(); TEST_REAL_SIMILAR(peak_area, 69863097.2125001) // ensure that missing peaks (=scans) do not impact quantification tmp_mt.estimateFWHM(); tmp_mt2.estimateFWHM(); TEST_REAL_SIMILAR(tmp_mt.computeFwhmArea(), tmp_mt2.computeFwhmArea()) } END_SECTION ///// START_SECTION((Size findMaxByIntPeak(bool use_smoothed_ints = false) const )) { TEST_EXCEPTION(Exception::InvalidValue, test_mt2.findMaxByIntPeak(true)); TEST_EXCEPTION(Exception::InvalidValue, test_mt3.findMaxByIntPeak(false)); TEST_EXCEPTION(Exception::InvalidValue, test_mt3.findMaxByIntPeak(true)); Size max_peak_idx1 = test_mt.findMaxByIntPeak(true); Size max_peak_idx2 = test_mt.findMaxByIntPeak(false); TEST_EQUAL(max_peak_idx1, 3); TEST_EQUAL(max_peak_idx2, 3); } END_SECTION ///// START_SECTION((double estimateFWHM(bool use_smoothed_ints = false))) { TEST_EXCEPTION(Exception::InvalidValue, test_mt2.estimateFWHM(true)); TEST_EXCEPTION(Exception::InvalidValue, test_mt3.estimateFWHM(false)); double test_fwhm1 = test_mt.estimateFWHM(false); double test_fwhm2 = test_mt.estimateFWHM(true); TEST_REAL_SIMILAR(test_fwhm1, 3.07921244222942); TEST_REAL_SIMILAR(test_fwhm2, 3.05481743986255); } END_SECTION ///// START_SECTION(static MT_QUANTMETHOD getQuantMethod(const String& val)) TEST_EQUAL(MassTrace::getQuantMethod("area"), MassTrace::MT_QUANT_AREA) TEST_EQUAL(MassTrace::getQuantMethod("median"), MassTrace::MT_QUANT_MEDIAN) TEST_EQUAL(MassTrace::getQuantMethod("max_height"), MassTrace::MT_QUANT_HEIGHT) TEST_EQUAL(MassTrace::getQuantMethod("somethingwrong"), MassTrace::SIZE_OF_MT_QUANTMETHOD) END_SECTION START_SECTION((void setQuantMethod(MT_QUANTMETHOD method))) { MassTrace mt_empty; TEST_EQUAL(mt_empty.getQuantMethod(), MassTrace::MT_QUANT_AREA); MassTrace raw_mt(peak_vec); // area (default) raw_mt.estimateFWHM(false); TEST_REAL_SIMILAR(raw_mt.getIntensity(false), 69863097.2125001); raw_mt.setQuantMethod(MassTrace::MT_QUANT_MEDIAN); // should return the median of the intensities TEST_REAL_SIMILAR(raw_mt.getIntensity(false), 542293.0); TEST_EQUAL(raw_mt.getQuantMethod(), MassTrace::MT_QUANT_MEDIAN); // test max_height raw_mt.setQuantMethod(MassTrace::MT_QUANT_HEIGHT); TEST_REAL_SIMILAR(raw_mt.getIntensity(false), 33329535.0); TEST_EQUAL(raw_mt.getQuantMethod(), MassTrace::MT_QUANT_HEIGHT); TEST_EXCEPTION(Exception::InvalidValue, raw_mt.setQuantMethod(MassTrace::SIZE_OF_MT_QUANTMETHOD)) } END_SECTION START_SECTION((MT_QUANTMETHOD getQuantMethod() const)) { NOT_TESTABLE // tested above } END_SECTION ///// START_SECTION((std::pair<Size, Size> getFWHMborders() const )) { MassTrace raw_mt(peak_vec); std::pair<Size, Size> interval = raw_mt.getFWHMborders(); TEST_EQUAL(interval.first, 0); TEST_EQUAL(interval.second, 0); interval = test_mt.getFWHMborders(); TEST_EQUAL(interval.first, 1); TEST_EQUAL(interval.second, 5); } END_SECTION ///// std::vector<PeakType> double_peak(peak_vec); double_peak.insert(double_peak.end(), peak_vec.begin(), peak_vec.end()); std::vector<double> double_smooth_ints(smoothed_ints); double_smooth_ints.insert(double_smooth_ints.end(), smoothed_ints.begin(), smoothed_ints.end()); MassTrace double_mt(double_peak); double_mt.setSmoothedIntensities(double_smooth_ints); START_SECTION((MassTrace(const MassTrace &))) { MassTrace copy_mt(test_mt); MassTrace::const_iterator c_it = copy_mt.begin(); for (MassTrace::const_iterator t_it = test_mt.begin(); t_it != test_mt.end(); ++t_it) { TEST_EQUAL(*c_it, *t_it); ++c_it; } TEST_REAL_SIMILAR(copy_mt.getCentroidMZ(), test_mt.getCentroidMZ()); TEST_REAL_SIMILAR(copy_mt.getCentroidRT(), test_mt.getCentroidRT()); TEST_EQUAL(copy_mt.getLabel(), test_mt.getLabel()); std::vector<double> sm1(copy_mt.getSmoothedIntensities()), sm2(test_mt.getSmoothedIntensities()); std::vector<double>::const_iterator sm1_it = sm1.begin(); for (std::vector<double>::const_iterator sm2_it = sm2.begin(); sm2_it != sm2.end(); ++sm2_it) { TEST_EQUAL(*sm1_it, *sm2_it); ++sm1_it; } } END_SECTION ///// START_SECTION((MassTrace& operator=(const MassTrace &))) { MassTrace copy_mt = test_mt; MassTrace::const_iterator c_it = copy_mt.begin(); for (MassTrace::const_iterator t_it = test_mt.begin(); t_it != test_mt.end(); ++t_it) { TEST_EQUAL(*c_it, *t_it); ++c_it; } TEST_REAL_SIMILAR(copy_mt.getCentroidMZ(), test_mt.getCentroidMZ()); TEST_REAL_SIMILAR(copy_mt.getCentroidRT(), test_mt.getCentroidRT()); TEST_EQUAL(copy_mt.getLabel(), test_mt.getLabel()); std::vector<double> sm1(copy_mt.getSmoothedIntensities()), sm2(test_mt.getSmoothedIntensities()); std::vector<double>::const_iterator sm1_it = sm1.begin(); for (std::vector<double>::const_iterator sm2_it = sm2.begin(); sm2_it != sm2.end(); ++sm2_it) { TEST_EQUAL(*sm1_it, *sm2_it); ++sm1_it; } } END_SECTION ///// START_SECTION((ConvexHull2D getConvexhull() const )) { ConvexHull2D tmp_hull = test_mt.getConvexhull(); DPosition<2> tmp_p1(154.21, 230.10181); DPosition<2> tmp_p2(155.22, 230.10181); DPosition<2> tmp_p3(154.21, 229.10181); TEST_EQUAL(tmp_hull.encloses(tmp_p1), true); TEST_EQUAL(tmp_hull.encloses(tmp_p2), false); TEST_EQUAL(tmp_hull.encloses(tmp_p3), false); } END_SECTION ///// MassTrace empty_trace; START_SECTION((void updateWeightedMeanRT())) { TEST_EXCEPTION(Exception::InvalidValue, empty_trace.updateWeightedMeanRT()); test_mt.updateWeightedMeanRT(); TEST_REAL_SIMILAR(test_mt.getCentroidRT(), 155.214671250425); } END_SECTION ///// START_SECTION((void updateMedianRT())) { TEST_EXCEPTION(Exception::InvalidValue, empty_trace.updateMedianRT()); test_mt.updateMedianRT(); TEST_REAL_SIMILAR(test_mt.getCentroidRT(), 155.24); } END_SECTION ///// START_SECTION((void updateMedianMZ())) { TEST_EXCEPTION(Exception::InvalidValue, empty_trace.updateMedianMZ()); test_mt.updateMedianMZ(); TEST_REAL_SIMILAR(test_mt.getCentroidMZ(), 230.10198); } END_SECTION ///// START_SECTION((void updateMeanMZ())) { TEST_EXCEPTION(Exception::InvalidValue, empty_trace.updateMeanMZ()); test_mt.updateMeanMZ(); TEST_REAL_SIMILAR(test_mt.getCentroidMZ(), 230.101918); } END_SECTION ///// START_SECTION((void updateWeightedMeanMZ())) { TEST_EXCEPTION(Exception::InvalidValue, empty_trace.updateWeightedMeanMZ()); test_mt.updateWeightedMeanMZ(); TEST_REAL_SIMILAR(test_mt.getCentroidMZ(), 230.101883054967); } END_SECTION ///// START_SECTION((void updateSmoothedMaxRT())) { MassTrace raw_mt(peak_vec); TEST_EXCEPTION(Exception::InvalidValue, raw_mt.updateSmoothedMaxRT()); test_mt.updateSmoothedMaxRT(); double smooth_max_rt = test_mt.getCentroidRT(); TEST_REAL_SIMILAR(smooth_max_rt, 155.24); } END_SECTION ///// START_SECTION((void updateSmoothedWeightedMeanRT())) { MassTrace raw_mt(peak_vec); TEST_EXCEPTION(Exception::InvalidValue, raw_mt.updateSmoothedWeightedMeanRT()); test_mt.updateSmoothedWeightedMeanRT(); double smooth_max_rt = test_mt.getCentroidRT(); TEST_REAL_SIMILAR(smooth_max_rt, 155.2468039); } END_SECTION ///// START_SECTION((double computeIntensitySum() const)) { // Test empty trace MassTrace empty_trace; TEST_REAL_SIMILAR(empty_trace.computeIntensitySum(), 0.0); // Test with known data // Sum should be: 542.0 + 542293.0 + 18282393.0 + 33329535.0 + 17342933.0 + 333291.0 + 339.0 TEST_REAL_SIMILAR(test_mt.computeIntensitySum(), 69831326.0); } END_SECTION ///// ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DataArrays_test.cpp
.cpp
10,157
382
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Your Name $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/METADATA/DataArrays.h> using namespace OpenMS; using namespace OpenMS::DataArrays; using namespace std; /////////////////////////// START_TEST(DataArrays, "$Id$") ///////////////////////////////////////////////////////////// FloatDataArray* fda_ptr = nullptr; FloatDataArray* fda_nullPointer = nullptr; START_SECTION((FloatDataArray())) fda_ptr = new FloatDataArray; TEST_NOT_EQUAL(fda_ptr, fda_nullPointer) TEST_EQUAL(fda_ptr->size(), 0) END_SECTION START_SECTION(([EXTRA] ~FloatDataArray())) delete fda_ptr; END_SECTION START_SECTION((FloatDataArray copy constructor)) FloatDataArray fda1{1.0f, 2.0f, 3.0f}; fda1.setName("test_array"); FloatDataArray fda2(fda1); TEST_EQUAL(fda2.size(), 3) TEST_EQUAL(fda2[0], 1.0f) TEST_EQUAL(fda2[1], 2.0f) TEST_EQUAL(fda2[2], 3.0f) TEST_EQUAL(fda2.getName(), "test_array") END_SECTION START_SECTION((FloatDataArray operator==)) FloatDataArray fda1{1.0f, 2.0f, 3.0f}; FloatDataArray fda2{1.0f, 2.0f, 3.0f}; FloatDataArray fda3{1.0f, 2.0f, 4.0f}; FloatDataArray fda4{1.0f, 2.0f}; TEST_TRUE(fda1 == fda2) TEST_FALSE(fda1 == fda3) TEST_FALSE(fda1 == fda4) // Test with metadata fda1.setName("array1"); TEST_FALSE(fda1 == fda2) fda2.setName("array1"); TEST_TRUE(fda1 == fda2) END_SECTION START_SECTION((FloatDataArray operator!=)) FloatDataArray fda1{1.0f, 2.0f, 3.0f}; FloatDataArray fda2{1.0f, 2.0f, 3.0f}; FloatDataArray fda3{1.0f, 2.0f, 4.0f}; TEST_FALSE(fda1 != fda2) TEST_TRUE(fda1 != fda3) END_SECTION START_SECTION((FloatDataArray operator<)) FloatDataArray fda1{1.0f, 2.0f, 3.0f}; FloatDataArray fda2{1.0f, 2.0f, 3.0f}; FloatDataArray fda3{1.0f, 2.0f, 4.0f}; TEST_FALSE(fda1 < fda2) TEST_TRUE(fda1 < fda3) TEST_FALSE(fda3 < fda1) END_SECTION START_SECTION((FloatDataArray operator<=)) FloatDataArray fda1{1.0f, 2.0f, 3.0f}; FloatDataArray fda2{1.0f, 2.0f, 3.0f}; FloatDataArray fda3{1.0f, 2.0f, 4.0f}; TEST_TRUE(fda1 <= fda2) TEST_TRUE(fda1 <= fda3) TEST_FALSE(fda3 <= fda1) END_SECTION START_SECTION((FloatDataArray operator>)) FloatDataArray fda1{1.0f, 2.0f, 3.0f}; FloatDataArray fda2{1.0f, 2.0f, 3.0f}; FloatDataArray fda3{1.0f, 2.0f, 4.0f}; TEST_FALSE(fda1 > fda2) TEST_FALSE(fda1 > fda3) TEST_TRUE(fda3 > fda1) END_SECTION START_SECTION((FloatDataArray operator>=)) FloatDataArray fda1{1.0f, 2.0f, 3.0f}; FloatDataArray fda2{1.0f, 2.0f, 3.0f}; FloatDataArray fda3{1.0f, 2.0f, 4.0f}; TEST_TRUE(fda1 >= fda2) TEST_FALSE(fda1 >= fda3) TEST_TRUE(fda3 >= fda1) END_SECTION // Test special float cases START_SECTION((FloatDataArray with NaN)) FloatDataArray fda1{1.0f, std::numeric_limits<float>::quiet_NaN(), 3.0f}; FloatDataArray fda2{1.0f, std::numeric_limits<float>::quiet_NaN(), 3.0f}; FloatDataArray fda3{1.0f, 2.0f, 3.0f}; // NaN comparisons should follow IEEE 754 rules TEST_FALSE(fda1 == fda2) // NaN != NaN TEST_TRUE(fda1 != fda2) END_SECTION ///////////////////////////////////////////////////////////// // IntegerDataArray tests IntegerDataArray* ida_ptr = nullptr; IntegerDataArray* ida_nullPointer = nullptr; START_SECTION((IntegerDataArray())) ida_ptr = new IntegerDataArray; TEST_NOT_EQUAL(ida_ptr, ida_nullPointer) TEST_EQUAL(ida_ptr->size(), 0) END_SECTION START_SECTION(([EXTRA] ~IntegerDataArray())) delete ida_ptr; END_SECTION START_SECTION((IntegerDataArray copy constructor)) IntegerDataArray ida1{1, 2, 3}; ida1.setName("int_array"); IntegerDataArray ida2(ida1); TEST_EQUAL(ida2.size(), 3) TEST_EQUAL(ida2[0], 1) TEST_EQUAL(ida2[1], 2) TEST_EQUAL(ida2[2], 3) TEST_EQUAL(ida2.getName(), "int_array") END_SECTION START_SECTION((IntegerDataArray operator==)) IntegerDataArray ida1{1, 2, 3}; IntegerDataArray ida2{1, 2, 3}; IntegerDataArray ida3{1, 2, 4}; TEST_TRUE(ida1 == ida2) TEST_FALSE(ida1 == ida3) END_SECTION START_SECTION((IntegerDataArray operator!=)) IntegerDataArray ida1{1, 2, 3}; IntegerDataArray ida2{1, 2, 3}; IntegerDataArray ida3{1, 2, 4}; TEST_FALSE(ida1 != ida2) TEST_TRUE(ida1 != ida3) END_SECTION START_SECTION((IntegerDataArray operator<)) IntegerDataArray ida1{1, 2, 3}; IntegerDataArray ida2{1, 2, 3}; IntegerDataArray ida3{1, 2, 4}; TEST_FALSE(ida1 < ida2) TEST_TRUE(ida1 < ida3) TEST_FALSE(ida3 < ida1) END_SECTION START_SECTION((IntegerDataArray operator<=)) IntegerDataArray ida1{1, 2, 3}; IntegerDataArray ida2{1, 2, 3}; IntegerDataArray ida3{1, 2, 4}; TEST_TRUE(ida1 <= ida2) TEST_TRUE(ida1 <= ida3) TEST_FALSE(ida3 <= ida1) END_SECTION START_SECTION((IntegerDataArray operator>)) IntegerDataArray ida1{1, 2, 3}; IntegerDataArray ida2{1, 2, 3}; IntegerDataArray ida3{1, 2, 4}; TEST_FALSE(ida1 > ida2) TEST_FALSE(ida1 > ida3) TEST_TRUE(ida3 > ida1) END_SECTION START_SECTION((IntegerDataArray operator>=)) IntegerDataArray ida1{1, 2, 3}; IntegerDataArray ida2{1, 2, 3}; IntegerDataArray ida3{1, 2, 4}; TEST_TRUE(ida1 >= ida2) TEST_FALSE(ida1 >= ida3) TEST_TRUE(ida3 >= ida1) END_SECTION ///////////////////////////////////////////////////////////// // StringDataArray tests StringDataArray* sda_ptr = nullptr; StringDataArray* sda_nullPointer = nullptr; START_SECTION((StringDataArray())) sda_ptr = new StringDataArray; TEST_NOT_EQUAL(sda_ptr, sda_nullPointer) TEST_EQUAL(sda_ptr->size(), 0) END_SECTION START_SECTION(([EXTRA] ~StringDataArray())) delete sda_ptr; END_SECTION START_SECTION((StringDataArray copy constructor)) StringDataArray sda1{"apple", "banana", "cherry"}; sda1.setName("string_array"); StringDataArray sda2(sda1); TEST_EQUAL(sda2.size(), 3) TEST_EQUAL(sda2[0], "apple") TEST_EQUAL(sda2[1], "banana") TEST_EQUAL(sda2[2], "cherry") TEST_EQUAL(sda2.getName(), "string_array") END_SECTION START_SECTION((StringDataArray operator==)) StringDataArray sda1{"apple", "banana", "cherry"}; StringDataArray sda2{"apple", "banana", "cherry"}; StringDataArray sda3{"apple", "banana", "date"}; TEST_TRUE(sda1 == sda2) TEST_FALSE(sda1 == sda3) END_SECTION START_SECTION((StringDataArray operator!=)) StringDataArray sda1{"apple", "banana", "cherry"}; StringDataArray sda2{"apple", "banana", "cherry"}; StringDataArray sda3{"apple", "banana", "date"}; TEST_FALSE(sda1 != sda2) TEST_TRUE(sda1 != sda3) END_SECTION START_SECTION((StringDataArray operator<)) StringDataArray sda1{"apple", "banana", "cherry"}; StringDataArray sda2{"apple", "banana", "cherry"}; StringDataArray sda3{"apple", "banana", "date"}; TEST_FALSE(sda1 < sda2) TEST_TRUE(sda1 < sda3) TEST_FALSE(sda3 < sda1) END_SECTION START_SECTION((StringDataArray operator<=)) StringDataArray sda1{"apple", "banana", "cherry"}; StringDataArray sda2{"apple", "banana", "cherry"}; StringDataArray sda3{"apple", "banana", "date"}; TEST_TRUE(sda1 <= sda2) TEST_TRUE(sda1 <= sda3) TEST_FALSE(sda3 <= sda1) END_SECTION START_SECTION((StringDataArray operator>)) StringDataArray sda1{"apple", "banana", "cherry"}; StringDataArray sda2{"apple", "banana", "cherry"}; StringDataArray sda3{"apple", "banana", "date"}; TEST_FALSE(sda1 > sda2) TEST_FALSE(sda1 > sda3) TEST_TRUE(sda3 > sda1) END_SECTION START_SECTION((StringDataArray operator>=)) StringDataArray sda1{"apple", "banana", "cherry"}; StringDataArray sda2{"apple", "banana", "cherry"}; StringDataArray sda3{"apple", "banana", "date"}; TEST_TRUE(sda1 >= sda2) TEST_FALSE(sda1 >= sda3) TEST_TRUE(sda3 >= sda1) END_SECTION // Test std::vector functionality inheritance START_SECTION((DataArrays std::vector functionality)) FloatDataArray fda; fda.push_back(1.0f); fda.push_back(2.0f); fda.push_back(3.0f); TEST_EQUAL(fda.size(), 3) TEST_EQUAL(fda.front(), 1.0f) TEST_EQUAL(fda.back(), 3.0f) fda.clear(); TEST_EQUAL(fda.size(), 0) TEST_TRUE(fda.empty()) // Test reserve and capacity fda.reserve(100); TEST_TRUE(fda.capacity() >= 100) // Test iteration IntegerDataArray ida{1, 2, 3, 4, 5}; int sum = 0; for (const auto& val : ida) { sum += val; } TEST_EQUAL(sum, 15) END_SECTION // Test MetaInfoDescription functionality inheritance START_SECTION((DataArrays MetaInfoDescription functionality)) FloatDataArray fda; fda.setName("my_float_array"); TEST_EQUAL(fda.getName(), "my_float_array") IntegerDataArray ida; ida.setName("my_int_array"); TEST_EQUAL(ida.getName(), "my_int_array") StringDataArray sda; sda.setName("my_string_array"); TEST_EQUAL(sda.getName(), "my_string_array") // Test that metadata affects comparison FloatDataArray fda1{1.0f, 2.0f}; FloatDataArray fda2{1.0f, 2.0f}; TEST_TRUE(fda1 == fda2) fda1.setName("array1"); TEST_FALSE(fda1 == fda2) fda2.setName("array1"); TEST_TRUE(fda1 == fda2) // Test MetaInfo functionality fda1.setMetaValue("label", "test_label"); TEST_FALSE(fda1 == fda2) fda2.setMetaValue("label", "test_label"); TEST_TRUE(fda1 == fda2) END_SECTION // Test mixed comparisons with different metadata START_SECTION((DataArrays comparison with mixed metadata)) FloatDataArray fda1{1.0f, 2.0f, 3.0f}; FloatDataArray fda2{1.0f, 2.0f, 3.0f}; // Same data, different names fda1.setName("A"); fda2.setName("B"); // Arrays with different metadata should compare consistently // The exact ordering doesn't matter as long as it's consistent bool less_than = fda1 < fda2; bool greater_than = fda1 > fda2; TEST_TRUE(less_than != greater_than) // One should be true, one false TEST_FALSE(fda1 == fda2) TEST_TRUE(fda1 != fda2) END_SECTION ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ParamJSONFile_test.cpp
.cpp
4,603
122
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Simon Gene Gottlieb $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <fstream> /////////////////////////// #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/DATASTRUCTURES/Param.h> #include <OpenMS/FORMAT/ParamJSONFile.h> /////////////////////////// #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshadow" #endif using namespace OpenMS; START_TEST(ParamJSONFile, "$Id") START_SECTION((bool ParamJSONFile::load(const std::string& filename, Param& param))) { String filename; NEW_TMP_FILE(filename) Param param; param.setValue("test:1:value", 1, "description"); // Check that FileNotFound is being thrown TEST_EXCEPTION(Exception::FileNotFound, ParamJSONFile::load("/does/not/exist/FileDoesNotExist.json", param)) // Check parsing error is thrown std::ofstream ofs(filename.c_str(), std::ios::out); ofs << "not a json"; ofs.close(); TEST_EXCEPTION(Exception::ParseError, ParamJSONFile::load(filename.c_str(), param)) // Check all types can be parsed /// set all expected params param.setValue("test:1:bool1", "false"); param.setValidStrings("test:1:bool1", {"true", "false"}); param.setValue("test:1:bool2", "false"); param.setValidStrings("test:1:bool2", {"true", "false"}); param.setValue("test:1:bool3", "true"); param.setValidStrings("test:1:bool3", {"false", "true"}); param.setValue("test:1:bool4", "true"); param.setValidStrings("test:1:bool4", {"false", "true"}); param.setValue("test:1:int", 0); param.setValue("test:1:double", 0.); param.setValue("test:1:string", ""); param.setValue("test:1:int_list", std::vector<int> {}); param.setValue("test:1:double_list", std::vector<double> {}); param.setValue("test:1:string_list", std::vector<std::string> {}); param.setValue("test:1:file_output", std::string {}, "some description", {"output file"}); param.setValue("test:1:is_executable_v1", std::string {}, "test is executable tag, giving a string", {"is_executable", "input file"}); param.setValue("test:1:is_executable_v2", std::string {}, "test is executable tag, giving a type: File", {"is_executable", "input file"}); // create matching json file ofs.open(filename.c_str(), std::ios::out); ofs << "{\n" " \"bool1\": true,\n" " \"bool2\": false,\n" " \"bool3\": true,\n" " \"bool4\": false,\n" " \"int\": 5,\n" " \"double\": 6.1,\n" " \"string\": \"Hello OpenMS\",\n" " \"int_list\": [10, 11, 12],\n" " \"double_list\": [13.25, 15.125],\n" " \"string_list\": [\"SeqAn\", \"rocks\"],\n" " \"file_output\": \"/some/made/up/path\",\n" " \"is_executable_v1\": \"/some/made/up/path\",\n" " \"is_executable_v2\": {\n" " \"class\": \"File\",\n" " \"path\": \"/some/made/up/path\"\n" " }\n" "}\n"; ofs.close(); ParamJSONFile::load(filename.c_str(), param); TEST_EQUAL(param.getValue("test:1:bool1").toBool(), true); TEST_EQUAL(param.getValue("test:1:bool2").toBool(), false); TEST_EQUAL(param.getValue("test:1:bool3").toBool(), true); TEST_EQUAL(param.getValue("test:1:bool4").toBool(), false); TEST_EQUAL(int(param.getValue("test:1:int")), 5); TEST_EQUAL(double(param.getValue("test:1:double")), 6.1); TEST_STRING_EQUAL(std::string(param.getValue("test:1:string")), "Hello OpenMS"); std::vector<int> int_list = param.getValue("test:1:int_list").toIntVector(); TEST_EQUAL(int_list.size(), 3); TEST_EQUAL(int_list[0], 10); TEST_EQUAL(int_list[1], 11); TEST_EQUAL(int_list[2], 12); std::vector<double> double_list = param.getValue("test:1:double_list").toDoubleVector(); TEST_EQUAL(double_list.size(), 2); TEST_EQUAL(double_list[0], 13.25); TEST_EQUAL(double_list[1], 15.125); std::vector<std::string> string_list = param.getValue("test:1:string_list").toStringVector(); TEST_EQUAL(string_list.size(), 2); TEST_EQUAL(string_list[0], "SeqAn"); TEST_EQUAL(string_list[1], "rocks"); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST #ifdef __clang__ #pragma clang diagnostic pop #endif
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IDConflictResolverAlgorithm_test.cpp
.cpp
2,851
108
// 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/ANALYSIS/ID/IDConflictResolverAlgorithm.h> using namespace OpenMS; using namespace std; START_TEST(IDConflictResolverAlgorithm, "$Id$") START_SECTION(resolveBetweenFeatures()) { FeatureMap map; Feature f1; Feature f2; Feature f3; Feature f4; PeptideHit hit; hit.setScore(23); hit.setSequence(AASequence::fromString("MORRISSEY")); PeptideIdentification id; id.insertHit(hit); PeptideIdentificationList ids; ids.push_back(id); PeptideHit hit2; hit2.setScore(23); hit2.setSequence(AASequence::fromString("M(Oxidation)ORRISSEY")); PeptideIdentification id2; id2.insertHit(hit2); PeptideIdentificationList ids2; ids2.push_back(id2); f1.setRT(1600.5); f1.setMZ(400.7); f1.setIntensity(1000.0); f1.setCharge(2); f1.setOverallQuality(1.0); f1.setPeptideIdentifications(ids); f2.setRT(1600.5); f2.setMZ(400.7); f2.setIntensity(10000.0); f2.setCharge(2); f2.setOverallQuality(1.0); f2.setPeptideIdentifications(ids); f3.setRT(1600.5); f3.setMZ(400.7); f3.setIntensity(1000.0); f3.setCharge(3); f3.setOverallQuality(1.0); f3.setPeptideIdentifications(ids); f4.setRT(1600.5); f4.setMZ(400.7); f4.setIntensity(1001.0); f4.setCharge(2); f4.setOverallQuality(1.0); f4.setPeptideIdentifications(ids2); map.push_back(f1); map.push_back(f2); IDConflictResolverAlgorithm::resolveBetweenFeatures(map); for (FeatureMap::ConstIterator it = map.begin(); it != map.end(); ++it) { if ((it->getIntensity() == 1000.0) && (it->getCharge() == 2)) { // This identification was removed by the resolveBetweenFeatures() method. TEST_EQUAL(it->getPeptideIdentifications().empty(), true) } if ((it->getIntensity() == 10000.0) && (it->getCharge() == 2)) { // This identification remains unchanged by the resolveBetweenFeatures() method. TEST_EQUAL(it->getPeptideIdentifications().empty(), false) } if ((it->getIntensity() == 1000.0) && (it->getCharge() == 3)) { // This identification remains unchanged by the resolveBetweenFeatures() method. TEST_EQUAL(it->getPeptideIdentifications().empty(), false) } if ((it->getIntensity() == 1001.0) && (it->getCharge() == 2)) { // This identification remains unchanged by the resolveBetweenFeatures() method. TEST_EQUAL(it->getPeptideIdentifications().empty(), false) } } } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FLASHDeconvHelperStructs_test.cpp
.cpp
17,136
531
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Jihyung Kim$ // $Authors: Jihyung Kim$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> /////////////////////////// using namespace OpenMS; using namespace std; typedef FLASHHelperClasses::LogMzPeak LogMzPeak; typedef FLASHHelperClasses::PrecalculatedAveragine PrecalculatedAveragine; typedef FLASHHelperClasses::MassFeature MassFeature; typedef FLASHHelperClasses::IsobaricQuantities IsobaricQuantities; START_TEST(FLASHDeconvHelperStructs, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FLASHHelperClasses* ptr = 0; FLASHHelperClasses* null_ptr = 0; START_SECTION(FLASHHelperClasses()) { ptr = new FLASHHelperClasses(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~FLASHHelperClasses()) { delete ptr; } END_SECTION START_SECTION((static double getLogMz(const double mz, const bool positive))) { double mz = 1300; double tmp_lmz1 = OpenMS::FLASHHelperClasses::getLogMz(mz, true); double tmp_lmz2 = OpenMS::FLASHHelperClasses::getLogMz(mz, false); TOLERANCE_ABSOLUTE(0.1); TEST_REAL_SIMILAR(tmp_lmz1, 7.169344415063863); TEST_REAL_SIMILAR(tmp_lmz2, 7.170119121465); } END_SECTION START_SECTION((static double getChargeMass(const bool positive))) { double temp_pos = OpenMS::FLASHHelperClasses::getChargeMass(true); double temp_neg = OpenMS::FLASHHelperClasses::getChargeMass(false); TEST_REAL_SIMILAR(temp_pos, Constants::PROTON_MASS_U); TEST_REAL_SIMILAR(temp_neg, -Constants::PROTON_MASS_U); } END_SECTION /// testing LogMzPeak START_SECTION(([FLASHDeconvHelperStructs::LogMzPeak] LogMzPeak()=default)) { LogMzPeak* lmp_ptr = new LogMzPeak(); LogMzPeak* lmp_null_ptr = 0; TEST_NOT_EQUAL(lmp_ptr, lmp_null_ptr); delete lmp_ptr; } END_SECTION // test data Peak1D tmp_p1; tmp_p1.setIntensity(443505.625); tmp_p1.setMZ(1125.5118055019082); START_SECTION(([FLASHDeconvHelperStructs::LogMzPeak] LogMzPeak(const Peak1D &peak, const bool positive))) { // Test positive mode LogMzPeak tmp_peak(tmp_p1, true); TEST_REAL_SIMILAR(tmp_peak.mz, 1125.5118055019082); TEST_REAL_SIMILAR(tmp_peak.intensity, 443505.625); TEST_REAL_SIMILAR(tmp_peak.logMz, 7.0250977989903145); TEST_EQUAL(tmp_peak.is_positive, true); TEST_EQUAL(tmp_peak.abs_charge, 0); TEST_EQUAL(tmp_peak.isotopeIndex, 0); // Test negative mode LogMzPeak tmp_peak_neg(tmp_p1, false); TEST_REAL_SIMILAR(tmp_peak_neg.mz, 1125.5118055019082); TEST_REAL_SIMILAR(tmp_peak_neg.intensity, 443505.625); TEST_EQUAL(tmp_peak_neg.is_positive, false); // logMz should be different for negative mode due to charge mass difference TEST_NOT_EQUAL(tmp_peak_neg.logMz, tmp_peak.logMz); } END_SECTION LogMzPeak test_peak(tmp_p1, true); START_SECTION(([FLASHDeconvHelperStructs::LogMzPeak] LogMzPeak(const LogMzPeak &))) { LogMzPeak tmp_p(test_peak); TEST_REAL_SIMILAR(test_peak.mz, tmp_p.mz); TEST_REAL_SIMILAR(test_peak.intensity, tmp_p.intensity); TEST_REAL_SIMILAR(test_peak.logMz, tmp_p.logMz); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::LogMzPeak] double getUnchargedMass())) { // Test with charge set test_peak.abs_charge = 2; TEST_REAL_SIMILAR(test_peak.getUnchargedMass(), 2249.0090580702745); // Test when abs_charge is 0 - should return 0.0 LogMzPeak zero_charge_peak(tmp_p1, true); zero_charge_peak.abs_charge = 0; TEST_REAL_SIMILAR(zero_charge_peak.getUnchargedMass(), 0.0); // Test when mass is already set (mass > 0) - should return mass directly LogMzPeak preset_mass_peak(tmp_p1, true); preset_mass_peak.abs_charge = 2; preset_mass_peak.mass = 5000.0; TEST_REAL_SIMILAR(preset_mass_peak.getUnchargedMass(), 5000.0); // Test negative mode LogMzPeak neg_peak(tmp_p1, false); neg_peak.abs_charge = 2; double neg_mass = neg_peak.getUnchargedMass(); // Negative mode should give different mass due to -PROTON_MASS_U TEST_NOT_EQUAL(neg_mass, test_peak.getUnchargedMass()); } END_SECTION LogMzPeak test_peak2(test_peak); test_peak2.logMz = 8.; START_SECTION(([FLASHDeconvHelperStructs::LogMzPeak] bool operator<(const LogMzPeak &a) const)) { // Test when logMz values are different bool is_p2_larger = test_peak < test_peak2; TEST_EQUAL(is_p2_larger, true); // Test when logMz values are equal - falls back to intensity comparison LogMzPeak peak_a(tmp_p1, true); LogMzPeak peak_b(tmp_p1, true); peak_a.logMz = 5.0; peak_b.logMz = 5.0; peak_a.intensity = 100.0f; peak_b.intensity = 200.0f; TEST_EQUAL(peak_a < peak_b, true); TEST_EQUAL(peak_b < peak_a, false); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::LogMzPeak] bool operator>(const LogMzPeak &a) const)) { // Test when logMz values are different bool is_p2_larger = test_peak2 > test_peak; TEST_EQUAL(is_p2_larger, true); // Test when logMz values are equal - falls back to intensity comparison LogMzPeak peak_a(tmp_p1, true); LogMzPeak peak_b(tmp_p1, true); peak_a.logMz = 5.0; peak_b.logMz = 5.0; peak_a.intensity = 200.0f; peak_b.intensity = 100.0f; TEST_EQUAL(peak_a > peak_b, true); TEST_EQUAL(peak_b > peak_a, false); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::LogMzPeak] bool operator==(const LogMzPeak &other) const)) { test_peak2 = test_peak; bool are_two_ps_same = test_peak2 == test_peak; TEST_EQUAL(are_two_ps_same, true); // Test inequality when logMz same but intensity different LogMzPeak peak_a(tmp_p1, true); LogMzPeak peak_b(tmp_p1, true); peak_a.logMz = 5.0; peak_b.logMz = 5.0; peak_a.intensity = 100.0f; peak_b.intensity = 200.0f; TEST_EQUAL(peak_a == peak_b, false); // Test inequality when intensity same but logMz different peak_b.intensity = 100.0f; peak_b.logMz = 6.0; TEST_EQUAL(peak_a == peak_b, false); } END_SECTION /// /// testing PrecalculatedAveragine START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] PrecalculatedAveragine())) { PrecalculatedAveragine* p_avg_ptr = new PrecalculatedAveragine(); PrecalculatedAveragine* p_avg_null_ptr = 0; TEST_NOT_EQUAL(p_avg_ptr, p_avg_null_ptr) delete p_avg_ptr; } END_SECTION // test data CoarseIsotopePatternGenerator generator = CoarseIsotopePatternGenerator(); PrecalculatedAveragine p_avg_test; START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] PrecalculatedAveragine(const double min_mass, const double max_mass, const double delta, CoarseIsotopePatternGenerator& generator, const bool use_RNA_averagine))) { p_avg_test = PrecalculatedAveragine(50, 100, 25, generator, false, -1); Size temp_a_idx = p_avg_test.getApexIndex(75); double temp_m_diff = p_avg_test.getAverageMassDelta(75); TEST_EQUAL(temp_a_idx, 0); TOLERANCE_ABSOLUTE(0.3); TEST_REAL_SIMILAR(temp_m_diff, 0.04); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] IsotopeDistribution get(const double mass) const)) { IsotopeDistribution tmp_iso = p_avg_test.get(60); TOLERANCE_ABSOLUTE(2); TEST_REAL_SIMILAR(tmp_iso.getMin(), 53.); TEST_REAL_SIMILAR(tmp_iso.getMax(), 59.); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] void setMaxIsotopeIndex(const int index))) { p_avg_test.setMaxIsotopeIndex(4); TEST_EQUAL(p_avg_test.getMaxIsotopeIndex(), 4); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] int getMaxIsotopeIndex() const)) { int tmp_max_idx = p_avg_test.getMaxIsotopeIndex(); TEST_EQUAL(tmp_max_idx, 4); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] Size getLeftCountFromApex(const double mass) const)) { Size tmp_left = p_avg_test.getLeftCountFromApex(75); TEST_EQUAL(tmp_left, 2); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] Size getRightCountFromApex(const double mass) const)) { Size temp_right = p_avg_test.getRightCountFromApex(75); TEST_EQUAL(temp_right, 2); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] Size getApexIndex(const double mass) const)) { Size tmp_apex = p_avg_test.getApexIndex(75); TEST_EQUAL(tmp_apex, 0); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] double getAverageMassDelta(const double mass) const)) { double tmp_m_delta = p_avg_test.getAverageMassDelta(50); TOLERANCE_ABSOLUTE(0.1); TEST_REAL_SIMILAR(tmp_m_delta, 0.025); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] double getMostAbundantMassDelta(const double mass) const)) { double tmp_m_delta = p_avg_test.getMostAbundantMassDelta(1000); TOLERANCE_ABSOLUTE(0.1); TEST_REAL_SIMILAR(tmp_m_delta, 0); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] Size getLastIndex(const double mass) const)) { double last_index = p_avg_test.getLastIndex(50); TEST_EQUAL(last_index, 2); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] PrecalculatedAveragine(const PrecalculatedAveragine&))) { // Test copy constructor PrecalculatedAveragine p_avg_copy(p_avg_test); TEST_EQUAL(p_avg_copy.getApexIndex(75), p_avg_test.getApexIndex(75)); TEST_EQUAL(p_avg_copy.getMaxIsotopeIndex(), p_avg_test.getMaxIsotopeIndex()); TEST_REAL_SIMILAR(p_avg_copy.getAverageMassDelta(75), p_avg_test.getAverageMassDelta(75)); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] PrecalculatedAveragine(PrecalculatedAveragine&&))) { // Test move constructor CoarseIsotopePatternGenerator gen; PrecalculatedAveragine p_avg_temp(50, 100, 25, gen, false, -1); Size original_apex = p_avg_temp.getApexIndex(75); PrecalculatedAveragine p_avg_moved(std::move(p_avg_temp)); TEST_EQUAL(p_avg_moved.getApexIndex(75), original_apex); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] PrecalculatedAveragine& operator=(const PrecalculatedAveragine&))) { // Test copy assignment operator PrecalculatedAveragine p_avg_assigned; p_avg_assigned = p_avg_test; TEST_EQUAL(p_avg_assigned.getApexIndex(75), p_avg_test.getApexIndex(75)); TEST_EQUAL(p_avg_assigned.getMaxIsotopeIndex(), p_avg_test.getMaxIsotopeIndex()); TEST_REAL_SIMILAR(p_avg_assigned.getAverageMassDelta(75), p_avg_test.getAverageMassDelta(75)); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] PrecalculatedAveragine& operator=(PrecalculatedAveragine&&))) { // Test move assignment operator CoarseIsotopePatternGenerator gen; PrecalculatedAveragine p_avg_temp(50, 100, 25, gen, false, -1); Size original_apex = p_avg_temp.getApexIndex(75); PrecalculatedAveragine p_avg_move_assigned; p_avg_move_assigned = std::move(p_avg_temp); TEST_EQUAL(p_avg_move_assigned.getApexIndex(75), original_apex); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] double getSNRMultiplicationFactor(const double mass) const)) { double snr_factor = p_avg_test.getSNRMultiplicationFactor(75); // SNR multiplication factor should be positive TEST_EQUAL(snr_factor > 0, true); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] PrecalculatedAveragine with RNA averagine)) { // Test RNA averagine mode CoarseIsotopePatternGenerator gen_rna; PrecalculatedAveragine p_avg_rna(50, 100, 25, gen_rna, true, -1); // RNA averagine should produce different isotope patterns than peptide IsotopeDistribution iso_rna = p_avg_rna.get(75); IsotopeDistribution iso_peptide = p_avg_test.get(75); // The distributions should exist and be valid TEST_EQUAL(iso_rna.size() > 0, true); TEST_EQUAL(iso_peptide.size() > 0, true); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::PrecalculatedAveragine] PrecalculatedAveragine with decoy isotope distance)) { // Test decoy mode with positive decoy_iso_distance CoarseIsotopePatternGenerator gen_decoy; PrecalculatedAveragine p_avg_decoy(50, 100, 25, gen_decoy, false, 1.5); // Decoy isotope patterns should be generated IsotopeDistribution iso_decoy = p_avg_decoy.get(75); TEST_EQUAL(iso_decoy.size() > 0, true); // The decoy distribution should differ from normal due to scaled m/z values IsotopeDistribution iso_normal = p_avg_test.get(75); // Decoy patterns have scaled isotope distances TEST_NOT_EQUAL(iso_decoy.getMin(), iso_normal.getMin()); } END_SECTION /// /// testing MassFeature START_SECTION(([FLASHDeconvHelperStructs::MassFeature] MassFeature default values)) { MassFeature mf; // Test that MassFeature can be default constructed MassFeature* mf_ptr = new MassFeature(); MassFeature* mf_null_ptr = nullptr; TEST_NOT_EQUAL(mf_ptr, mf_null_ptr); delete mf_ptr; } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::MassFeature] bool operator<(const MassFeature &a) const)) { MassFeature mf1; MassFeature mf2; mf1.avg_mass = 1000.0; mf2.avg_mass = 2000.0; TEST_EQUAL(mf1 < mf2, true); TEST_EQUAL(mf2 < mf1, false); // Test equal masses mf2.avg_mass = 1000.0; TEST_EQUAL(mf1 < mf2, false); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::MassFeature] bool operator>(const MassFeature &a) const)) { MassFeature mf1; MassFeature mf2; mf1.avg_mass = 2000.0; mf2.avg_mass = 1000.0; TEST_EQUAL(mf1 > mf2, true); TEST_EQUAL(mf2 > mf1, false); // Test equal masses mf2.avg_mass = 2000.0; TEST_EQUAL(mf1 > mf2, false); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::MassFeature] bool operator==(const MassFeature &other) const)) { MassFeature mf1; MassFeature mf2; mf1.avg_mass = 1000.0; mf2.avg_mass = 1000.0; TEST_EQUAL(mf1 == mf2, true); mf2.avg_mass = 2000.0; TEST_EQUAL(mf1 == mf2, false); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::MassFeature] member variables)) { MassFeature mf; // Test setting and getting member variables mf.index = 42; mf.iso_offset = 1; mf.scan_number = 100; mf.min_scan_number = 90; mf.max_scan_number = 110; mf.rep_charge = 5; mf.avg_mass = 15000.0; mf.min_charge = 3; mf.max_charge = 10; mf.charge_count = 8; mf.isotope_score = 0.95; mf.qscore = 0.88; mf.rep_mz = 1500.5; mf.is_decoy = false; mf.ms_level = 1; TEST_EQUAL(mf.index, 42); TEST_EQUAL(mf.iso_offset, 1); TEST_EQUAL(mf.scan_number, 100); TEST_EQUAL(mf.min_scan_number, 90); TEST_EQUAL(mf.max_scan_number, 110); TEST_EQUAL(mf.rep_charge, 5); TEST_REAL_SIMILAR(mf.avg_mass, 15000.0); TEST_EQUAL(mf.min_charge, 3); TEST_EQUAL(mf.max_charge, 10); TEST_EQUAL(mf.charge_count, 8); TEST_REAL_SIMILAR(mf.isotope_score, 0.95); TEST_REAL_SIMILAR(mf.qscore, 0.88); TEST_REAL_SIMILAR(mf.rep_mz, 1500.5); TEST_EQUAL(mf.is_decoy, false); TEST_EQUAL(mf.ms_level, 1); // Test per_charge_intensity and per_isotope_intensity vectors mf.per_charge_intensity = {100.0f, 200.0f, 300.0f}; mf.per_isotope_intensity = {50.0f, 100.0f, 75.0f, 25.0f}; TEST_EQUAL(mf.per_charge_intensity.size(), 3); TEST_EQUAL(mf.per_isotope_intensity.size(), 4); TEST_REAL_SIMILAR(mf.per_charge_intensity[1], 200.0f); TEST_REAL_SIMILAR(mf.per_isotope_intensity[2], 75.0f); } END_SECTION /// /// testing IsobaricQuantities START_SECTION(([FLASHDeconvHelperStructs::IsobaricQuantities] IsobaricQuantities default values)) { IsobaricQuantities iq; // Test that IsobaricQuantities can be default constructed IsobaricQuantities* iq_ptr = new IsobaricQuantities(); IsobaricQuantities* iq_null_ptr = nullptr; TEST_NOT_EQUAL(iq_ptr, iq_null_ptr); delete iq_ptr; } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::IsobaricQuantities] bool empty() const)) { IsobaricQuantities iq; // Should be empty initially (quantities vector is empty) TEST_EQUAL(iq.empty(), true); // Add quantities iq.quantities.push_back(100.0); TEST_EQUAL(iq.empty(), false); // Clear quantities iq.quantities.clear(); TEST_EQUAL(iq.empty(), true); } END_SECTION START_SECTION(([FLASHDeconvHelperStructs::IsobaricQuantities] member variables)) { IsobaricQuantities iq; // Test setting and getting member variables iq.scan = 500; iq.rt = 120.5; iq.precursor_mz = 750.25; iq.precursor_mass = 1498.48; iq.quantities = {100.0, 200.0, 150.0, 175.0}; iq.merged_quantities = {450.0, 375.0}; TEST_EQUAL(iq.scan, 500); TEST_REAL_SIMILAR(iq.rt, 120.5); TEST_REAL_SIMILAR(iq.precursor_mz, 750.25); TEST_REAL_SIMILAR(iq.precursor_mass, 1498.48); TEST_EQUAL(iq.quantities.size(), 4); TEST_EQUAL(iq.merged_quantities.size(), 2); TEST_REAL_SIMILAR(iq.quantities[0], 100.0); TEST_REAL_SIMILAR(iq.quantities[3], 175.0); TEST_REAL_SIMILAR(iq.merged_quantities[0], 450.0); } END_SECTION /// ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TransformationModelBSpline_test.cpp
.cpp
5,087
115
// 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, Stephan Aiche $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h> #include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelBSpline.h> /////////////////////////// START_TEST(TransformationModelBSpline, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; TransformationModelBSpline* ptr = nullptr; TransformationModel::DataPoints data, empty; data.push_back(make_pair(1.2, 5.2)); data.push_back(make_pair(3.2, 7.3)); data.push_back(make_pair(2.2, 6.25)); data.push_back(make_pair(2.2, 3.1)); data.push_back(make_pair(2.2, 7.25)); data.push_back(make_pair(3.0, 8.5)); data.push_back(make_pair(3.1, 4.7)); data.push_back(make_pair(1.7, 6.0)); data.push_back(make_pair(2.9, 4.7)); data.push_back(make_pair(4.2, 5.0)); data.push_back(make_pair(3.7, -2.4)); START_SECTION((TransformationModelBSpline(const DataPoints&, const Param&))) { TEST_EXCEPTION(Exception::IllegalArgument, TransformationModelBSpline tm(empty, Param())); // need data ptr = new TransformationModelBSpline(data, Param()); TEST_NOT_EQUAL(ptr, 0) } END_SECTION START_SECTION((~TransformationModelBSpline())) { delete ptr; } END_SECTION START_SECTION((virtual double evaluate(double value) const)) { // test data: sine function with added noise double x[] = {-0.547062107104045, -2.14564213748743, -3.07082880304281, 0.470273389368586, 1.79367651606654, 0.595846950617167, 1.58738829599701, -3.11534942614546, -2.55761408378404, -0.996199010293142, -0.553164304142189, 3.11858532047631, 0.74970539948485, 0.276411185223925, 1.85962696821902, 0.960234253336655, -1.62536120645258, -2.72457034250236, 1.67812366716942, -0.838775352531627, -0.654629712755158, 1.8220799029759, -1.8653140724926, -0.235789436296459, -0.29890807257244, 0.405216494893513, 0.233453956340058, -2.82471832316488, -3.08393846252989, -1.41524590344969, -0.199886448130033}; double y[] = {-0.584809756448807, -0.866407723341462, -0.0471640435125096, 0.435337754412529, 0.861949333280581, 0.616243288851563, 1.1228424073836, -0.0483419751019981, -0.532873307735754, -0.917205998701872, -0.301045308942404, 0.0120964875551685, 0.758584328691163, 0.405241179450931, 1.00118722437611, 0.765459021914008, -1.03191739643009, -0.477999500942485, 0.872168291767237, -0.770691257861706, -0.496027498267174, 0.743777383059081, -0.982264617804229, -0.398462173815226, -0.40498973770553, 0.348305878579121, 0.0755855659375029, -0.457381746018402, 0.245483195014945, -1.07618910469392, -0.0880708165561682}; // results validated by visual inspection: double pred[] = {0.846137, 0.689856, 0.5094, 0.31183, 0.10421, -0.106399, -0.312921, -0.508271, -0.685362, -0.837111, -0.95643, -1.03623, -1.06944, -1.05016, -0.981868, -0.872412, -0.729666, -0.561505, -0.375803, -0.180434, 0.016728, 0.20827, 0.38867, 0.55289, 0.695895, 0.812645, 0.898104, 0.947234, 0.955013, 0.919484, 0.845545, 0.739022, 0.60574, 0.451526, 0.282206, 0.103606, -0.0784482, -0.258084, -0.429374, -0.586387, -0.723191}; data.resize(31); for (Size i = 0; i < 31; ++i) { data[i] = make_pair(x[i], y[i]); } Param params; params.setValue("wavelength", 0.0); params.setValue("num_nodes", 5); params.setValue("extrapolate", "b_spline"); TransformationModelBSpline tm(data, params); vector<double> results; Size index = 0; for (double v = -4; v < 4.1; v += 0.2, index++) { // cout << v << ", " << tm.evaluate(v) << ", "; TEST_REAL_SIMILAR(tm.evaluate(v), pred[index]); } // test extrapolation: params.setValue("extrapolate", "linear"); TransformationModelBSpline tm_lin(data, params); TEST_REAL_SIMILAR(tm_lin.evaluate(-4.0), 0.947997); TEST_REAL_SIMILAR(tm_lin.evaluate(4.0), -0.807806); params.setValue("extrapolate", "constant"); TransformationModelBSpline tm_const(data, params); TEST_REAL_SIMILAR(tm_const.evaluate(-4.0), 0.0150243); TEST_REAL_SIMILAR(tm_const.evaluate(4.0), -0.00429613); params.setValue("extrapolate", "global_linear"); TransformationModelBSpline tm_global(data, params); TEST_REAL_SIMILAR(tm_global.evaluate(-4.0), -0.959617); TEST_REAL_SIMILAR(tm_global.evaluate(4.0), 1.10039); } END_SECTION START_SECTION((void getParameters(Param& params) const)) { Param p_in; p_in.setValue("num_nodes", 5); TransformationModelBSpline tm(data, p_in); TEST_EQUAL(tm.getParameters().getValue("num_nodes"), p_in.getValue("num_nodes")); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/XQuestResultXMLFile_test.cpp
.cpp
6,371
100
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Eugen Netz $ // $Authors: Eugen Netz $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/XQuestResultXMLFile.h> #include <OpenMS/CONCEPT/Constants.h> #include <QStringList> using namespace OpenMS; START_TEST(XQuestResultXMLFile, "$Id$") START_SECTION(void store(const String& filename, const std::vector<ProteinIdentification>& poid, const PeptideIdentificationList& peid) const) std::vector<ProteinIdentification> protein_ids; PeptideIdentificationList peptide_ids; String xquest_input_file= OPENMS_GET_TEST_DATA_PATH("XQuestResultXMLFile_test_data.xquest.xml"); XQuestResultXMLFile().load(xquest_input_file, peptide_ids, protein_ids); String out_file; NEW_TMP_FILE(out_file) XQuestResultXMLFile().store(out_file, protein_ids, peptide_ids); PeptideIdentificationList peptide_id_vector; std::vector< ProteinIdentification > protein_id_vector; XQuestResultXMLFile().load(out_file, peptide_id_vector, protein_id_vector); for (Size i = 0; i < peptide_id_vector.size(); i+=20) { std::vector<PeptideHit> hits = peptide_id_vector[i].getHits(); for (Size k = 0; k < hits.size(); ++k) { TEST_REAL_SIMILAR(hits[k].getScore(), peptide_ids[i].getHits()[k].getScore()) TEST_EQUAL(hits[k].getCharge(), peptide_ids[i].getHits()[k].getCharge()) TEST_EQUAL(hits[k].getMetaValue(Constants::UserParam::OPENPEPXL_XL_RANK), peptide_ids[i].getHits()[k].getMetaValue(Constants::UserParam::OPENPEPXL_XL_RANK)) TEST_EQUAL(hits[k].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE), peptide_ids[i].getHits()[k].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE)) TEST_EQUAL(hits[k].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), peptide_ids[i].getHits()[k].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1)) TEST_EQUAL(hits[k].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), peptide_ids[i].getHits()[k].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2)) TEST_EQUAL(hits[k].getSequence().toString(), peptide_ids[i].getHits()[k].getSequence().toString()) TEST_EQUAL(hits[k].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE), peptide_ids[i].getHits()[k].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE)) TEST_REAL_SIMILAR(hits[k].getMetaValue("OpenPepXL:match-odds"), peptide_ids[i].getHits()[k].getMetaValue("OpenPepXL:match-odds")) TEST_REAL_SIMILAR(hits[k].getMetaValue("OpenPepXL:intsum"), peptide_ids[i].getHits()[k].getMetaValue("OpenPepXL:intsum")) } } TEST_EQUAL(peptide_id_vector.size(), 296) TEST_EQUAL(peptide_id_vector[0].getHits().size(), 1) TEST_EQUAL(peptide_id_vector[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE), "cross-link") TEST_EQUAL(peptide_id_vector[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), 14) TEST_EQUAL(peptide_id_vector[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), 5) TEST_EQUAL(peptide_id_vector[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA), "ANYWHERE") TEST_EQUAL(peptide_id_vector[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA), "ANYWHERE") TEST_EQUAL(peptide_id_vector[0].getHits()[0].getSequence().toString(), "LTEIISHDPNIELHKK") TEST_EQUAL(peptide_id_vector[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE), "VEGCPKHPK") TEST_EQUAL(peptide_id_vector[17].getHits().size(), 1) TEST_EQUAL(peptide_id_vector[17].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE), "cross-link") TEST_EQUAL(peptide_id_vector[17].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), 15) TEST_EQUAL(peptide_id_vector[17].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), 11) TEST_EQUAL(peptide_id_vector[17].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA), "C_TERM") TEST_EQUAL(peptide_id_vector[17].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA), "ANYWHERE") TEST_EQUAL(peptide_id_vector[17].getHits()[0].getSequence().toString(), "VILHLKEDQTEYLEER") TEST_EQUAL(peptide_id_vector[17].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE), "EYGCAPWPMVEKLIK") TEST_EQUAL(peptide_id_vector[289].getHits().size(), 1) TEST_EQUAL(peptide_id_vector[289].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE), "cross-link") TEST_EQUAL(peptide_id_vector[289].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), 15) TEST_EQUAL(peptide_id_vector[289].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), 0) TEST_EQUAL(peptide_id_vector[289].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA), "ANYWHERE") TEST_EQUAL(peptide_id_vector[289].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA), "ANYWHERE") TEST_EQUAL(peptide_id_vector[289].getHits()[0].getSequence().toString(), "DYHFVNATEESDALAKLR") TEST_EQUAL(peptide_id_vector[289].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE), "KETFDDLPK") TEST_EQUAL(peptide_id_vector[279].getHits().size(), 2) TEST_EQUAL(peptide_id_vector[279].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE), "cross-link") TEST_EQUAL(peptide_id_vector[279].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1), 0) TEST_EQUAL(peptide_id_vector[279].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2), 6) TEST_EQUAL(peptide_id_vector[279].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA), "N_TERM") TEST_EQUAL(peptide_id_vector[279].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA), "ANYWHERE") TEST_EQUAL(peptide_id_vector[279].getHits()[0].getSequence().toString(), "MASGSCQGCEEDEETLKK") TEST_EQUAL(peptide_id_vector[279].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE), "NTEGTQKQK") END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConsensusMap_test.cpp
.cpp
26,305
800
// 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/ConsensusFeature.h> /////////////////////////// #include <OpenMS/KERNEL/ConsensusMap.h> #include <OpenMS/KERNEL/FeatureMap.h> /////////////////////////// #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/DataProcessing.h> using namespace OpenMS; using namespace std; START_TEST(ConsensusMap, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ConsensusMap* ptr = nullptr; ConsensusMap* nullPointer = nullptr; START_SECTION((ConsensusMap())) ptr = new ConsensusMap(); TEST_NOT_EQUAL(ptr, nullPointer) TEST_TRUE(ptr->isMetaEmpty()) END_SECTION START_SECTION((~ConsensusMap())) delete ptr; END_SECTION START_SECTION((const std::vector<ProteinIdentification>& getProteinIdentifications() const)) FeatureMap tmp; TEST_EQUAL(tmp.getProteinIdentifications().size(),0) END_SECTION START_SECTION((std::vector<ProteinIdentification>& getProteinIdentifications())) FeatureMap tmp; tmp.getProteinIdentifications().resize(1); TEST_EQUAL(tmp.getProteinIdentifications().size(),1) END_SECTION START_SECTION((void setProteinIdentifications(const std::vector<ProteinIdentification>& protein_identifications))) FeatureMap tmp; tmp.setProteinIdentifications(std::vector<ProteinIdentification>(2)); TEST_EQUAL(tmp.getProteinIdentifications().size(),2) END_SECTION START_SECTION((const PeptideIdentificationList& getUnassignedPeptideIdentifications() const)) FeatureMap tmp; TEST_EQUAL(tmp.getUnassignedPeptideIdentifications().size(),0) END_SECTION START_SECTION((PeptideIdentificationList& getUnassignedPeptideIdentifications())) FeatureMap tmp; tmp.getUnassignedPeptideIdentifications().resize(1); TEST_EQUAL(tmp.getUnassignedPeptideIdentifications().size(),1) END_SECTION START_SECTION((void setUnassignedPeptideIdentifications(const PeptideIdentificationList& unassigned_peptide_identifications))) FeatureMap tmp; tmp.setUnassignedPeptideIdentifications(PeptideIdentificationList(2)); TEST_EQUAL(tmp.getUnassignedPeptideIdentifications().size(),2) END_SECTION START_SECTION((const std::vector<DataProcessing>& getDataProcessing() const)) ConsensusMap tmp; TEST_EQUAL(tmp.getDataProcessing().size(),0); END_SECTION START_SECTION((std::vector<DataProcessing>& getDataProcessing())) ConsensusMap tmp; tmp.getDataProcessing().resize(1); TEST_EQUAL(tmp.getDataProcessing().size(),1); END_SECTION START_SECTION((void setDataProcessing(const std::vector< DataProcessing > &processing_method))) ConsensusMap tmp; std::vector<DataProcessing> dummy; dummy.resize(1); tmp.setDataProcessing(dummy); TEST_EQUAL(tmp.getDataProcessing().size(),1); END_SECTION Feature feature1; feature1.getPosition()[0] = 2.0; feature1.getPosition()[1] = 3.0; feature1.setIntensity(1.0f); Feature feature2; feature2.getPosition()[0] = 0.0; feature2.getPosition()[1] = 2.5; feature2.setIntensity(0.5f); Feature feature3; feature3.getPosition()[0] = 10.5; feature3.getPosition()[1] = 0.0; feature3.setIntensity(0.01f); Feature feature4; feature4.getPosition()[0] = 5.25; feature4.getPosition()[1] = 1.5; feature4.setIntensity(0.5f); START_SECTION((void updateRanges())) ConsensusMap map; feature1.setUniqueId(1); ConsensusFeature f; f.setIntensity(1.0f); f.setRT(2.0); f.setMZ(3.0); f.insert(1,feature1); map.push_back(f); map.updateRanges(); TEST_REAL_SIMILAR(map.getMinIntensity(), 1.0) TEST_REAL_SIMILAR(map.getMaxIntensity(), 1.0) TEST_REAL_SIMILAR(map.getMaxRT(),2.0) TEST_REAL_SIMILAR(map.getMaxMZ(),3.0) TEST_REAL_SIMILAR(map.getMinRT(),2.0) TEST_REAL_SIMILAR(map.getMinMZ(),3.0) // second time to check the initialization map.updateRanges(); TEST_REAL_SIMILAR(map.getMinIntensity(), 1.0) TEST_REAL_SIMILAR(map.getMaxIntensity(), 1.0) TEST_REAL_SIMILAR(map.getMaxRT(), 2.0) TEST_REAL_SIMILAR(map.getMaxMZ(), 3.0) TEST_REAL_SIMILAR(map.getMinRT(), 2.0) TEST_REAL_SIMILAR(map.getMinMZ(), 3.0) // two points feature2.setUniqueId(2); f.insert(1,feature2); map.push_back(f); map.updateRanges(); TEST_REAL_SIMILAR(map.getMinIntensity(), 0.5) TEST_REAL_SIMILAR(map.getMaxIntensity(), 1.0) TEST_REAL_SIMILAR(map.getMaxRT(), 2.0) TEST_REAL_SIMILAR(map.getMaxMZ(), 3.0) TEST_REAL_SIMILAR(map.getMinRT(), 0.0) TEST_REAL_SIMILAR(map.getMinMZ(), 2.5) // four points feature3.setUniqueId(3); f.insert(1,feature3); feature4.setUniqueId(4); f.insert(1,feature4); map.push_back(f); map.updateRanges(); TEST_REAL_SIMILAR(map.getMinIntensity(), 0.01) TEST_REAL_SIMILAR(map.getMaxIntensity(), 1.0) TEST_REAL_SIMILAR(map.getMaxRT(), 10.5) TEST_REAL_SIMILAR(map.getMaxMZ(), 3.0) TEST_REAL_SIMILAR(map.getMinRT(), 0.0) TEST_REAL_SIMILAR(map.getMinMZ(), 0.0) END_SECTION START_SECTION((ConsensusMap& appendRows(const ConsensusMap &rhs))) { ConsensusMap m1, m2, m3; // adding empty maps has no effect: m1.appendRows(m2) ; TEST_EQUAL(m1, m3); // with content: ConsensusFeature f1; f1.setMZ(100.12); m1.push_back(f1); m3 = m1; m1.appendRows(m2); TEST_EQUAL(m1, m3); // test basic classes m1.setIdentifier ("123"); m1.getDataProcessing().resize(1); m1.getProteinIdentifications().resize(1); m1.getUnassignedPeptideIdentifications().resize(1); m1.ensureUniqueId(); m1.getColumnHeaders()[0].filename = "m1"; m2.setIdentifier ("321"); m2.getDataProcessing().resize(2); m2.getProteinIdentifications().resize(2); m2.getUnassignedPeptideIdentifications().resize(2); m2.push_back(ConsensusFeature()); m2.push_back(ConsensusFeature()); m2.getColumnHeaders()[1].filename = "m2"; m1.appendRows(m2); TEST_EQUAL(m1.getIdentifier(), ""); TEST_EQUAL(UniqueIdInterface::isValid(m1.getUniqueId()), false); TEST_EQUAL(m1.getDataProcessing().size(), 3); TEST_EQUAL(m1.getProteinIdentifications().size(),3); TEST_EQUAL(m1.getUnassignedPeptideIdentifications().size(),3); TEST_EQUAL(m1.size(),3); TEST_EQUAL(m1.getColumnHeaders().size(), 2); } END_SECTION START_SECTION((ConsensusMap& appendColumns(const ConsensusMap &rhs))) { ConsensusMap m1, m2; // Test1: adding empty map has no effect: m1.appendColumns(ConsensusMap()) ; TEST_EQUAL(m1, ConsensusMap()); // one consensus feature with one element referencing the first map Feature f1; f1.setRT(1); f1.setMZ(1); f1.setIntensity(1); f1.setUniqueId(1); ConsensusFeature cf1; cf1.insert(0, f1, 0); // map = 0, feature 1, element = 0 cf1.setMZ(100.12); m1.push_back(cf1); // m1 now contains one consensus feature with one element associated with map 0 // Test2: adding empty map to map with content ConsensusMap old_m1 = m1; m1.appendColumns(ConsensusMap()); TEST_EQUAL(m1, old_m1); m1.setIdentifier("123"); m1.getDataProcessing().resize(1); m1.getProteinIdentifications().resize(1); m1.getUnassignedPeptideIdentifications().resize(1); m1.ensureUniqueId(); m1.getColumnHeaders()[0].filename = "m1"; m2.setIdentifier("321"); m2.getDataProcessing().resize(2); m2.getProteinIdentifications().resize(2); m2.getUnassignedPeptideIdentifications().resize(2); m2.getColumnHeaders()[0].filename = "m2_1"; m2.getColumnHeaders()[1].filename = "m2_2"; // one consensus feature with two elements referencing the first and second map Feature f2, f3; f2.setRT(2); f2.setMZ(2); f2.setIntensity(2); f2.setUniqueId(2); f3.setRT(3); f3.setMZ(3); f3.setIntensity(3); f3.setUniqueId(3); ConsensusFeature cf2; cf2.insert(0, f2, 0); // first map, feature2, first element cf2.insert(1, f3, 1); // second map, feature3, second element m2.push_back(cf2); // append columns of m2 to m1 m1.appendColumns(m2); // now contains 1 (m1) + 2 columns (m2) TEST_EQUAL(m1.getIdentifier(), ""); TEST_EQUAL(UniqueIdInterface::isValid(m1.getUniqueId()), false); TEST_EQUAL(m1.getDataProcessing().size(), 3); TEST_EQUAL(m1.getProteinIdentifications().size(), 3); TEST_EQUAL(m1.getUnassignedPeptideIdentifications().size(), 3); TEST_EQUAL(m1.size(), 2); TEST_EQUAL(m1.getColumnHeaders().size(), 3); TEST_EQUAL(m1.getColumnHeaders()[0].filename, "m1"); TEST_EQUAL(m1.getColumnHeaders()[1].filename, "m2_1"); TEST_EQUAL(m1.getColumnHeaders()[2].filename, "m2_2"); auto cfh1 = m1[0].getFeatures(); TEST_EQUAL(cfh1.begin()->getIntensity(), 1); TEST_EQUAL(cfh1.begin()->getUniqueId(), 0); TEST_EQUAL(cfh1.begin()->getMapIndex(), 0); // test the second consensus feature with two elements // they should now reference to the second and third map (map index 1 and 2) auto cfh2 = m1[1].getFeatures(); Size element(0); for (auto & h : cfh2) { if (element == 0) { TEST_EQUAL(h.getIntensity(), 2); TEST_EQUAL(h.getUniqueId(), 0); // references the unique id of the original feature TEST_EQUAL(h.getMapIndex(), 1); } else { TEST_EQUAL(h.getIntensity(), 3); TEST_EQUAL(h.getUniqueId(), 1); // references the unique id of the original feature TEST_EQUAL(h.getMapIndex(), 2); } ++element; } } END_SECTION const ConsensusMap map_const_1 = []() { ConsensusMap map1; map1.resize(3); map1.setMetaValue("meta", String("value")); map1.setIdentifier("lsid"); map1.getColumnHeaders()[0].filename = "blub"; map1.getColumnHeaders()[0].size = 47; map1.getColumnHeaders()[0].label = "label"; map1.getColumnHeaders()[0].setMetaValue("meta", String("meta")); map1.getDataProcessing().resize(1); map1.setExperimentType("labeled_MS2"); map1.getProteinIdentifications().resize(1); map1.getUnassignedPeptideIdentifications().resize(1); return map1; }(); START_SECTION((ConsensusMap& operator = (const ConsensusMap& source))) //assignment ConsensusMap map2; map2 = map_const_1; TEST_EQUAL(map2.size(), 3) TEST_EQUAL(map2.getIdentifier(), "lsid") TEST_EQUAL(map2.getMetaValue("meta").toString(),"value") TEST_EQUAL(map2.getColumnHeaders()[0].filename == "blub", true) TEST_EQUAL(map2.getColumnHeaders()[0].label == "label", true) TEST_EQUAL(map2.getColumnHeaders()[0].size == 47, true) TEST_EQUAL(map2.getColumnHeaders()[0].getMetaValue("meta") == "meta", true) TEST_EQUAL(map2.getExperimentType(), "labeled_MS2") TEST_EQUAL(map2.getDataProcessing().size(),1) TEST_EQUAL(map2.getProteinIdentifications().size(),1) TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),1) //assignment of empty object ConsensusMap map2_empty; map2 = map2_empty; TEST_EQUAL(map2.getIdentifier(),"") TEST_EQUAL(map2.getColumnHeaders().size(),0) TEST_EQUAL(map2.getExperimentType(),"label-free") // default TEST_EQUAL(map2.getDataProcessing().size(),0) TEST_EQUAL(map2.getProteinIdentifications().size(),0) TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),0) END_SECTION START_SECTION((ConsensusMap(const ConsensusMap& source))) ConsensusMap map2(map_const_1); TEST_EQUAL(map2.getIdentifier(),"lsid") TEST_EQUAL(map2.getMetaValue("meta").toString(),"value") TEST_EQUAL(map2.getColumnHeaders()[0].filename == "blub", true) TEST_EQUAL(map2.getColumnHeaders()[0].label == "label", true) TEST_EQUAL(map2.getColumnHeaders()[0].size == 47, true) TEST_EQUAL(map2.getColumnHeaders()[0].getMetaValue("meta") == "meta", true) TEST_EQUAL(map2.getExperimentType(),"labeled_MS2") TEST_EQUAL(map2.getDataProcessing().size(),1) TEST_EQUAL(map2.getProteinIdentifications().size(),1); TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),1); END_SECTION START_SECTION((ConsensusMap& operator = (ConsensusMap&& source))) static_assert(std::is_move_assignable_v<ConsensusMap>); //assignment ConsensusMap map2; map2 = ConsensusMap(map_const_1); // move TEST_EQUAL(map2.size(), 3) TEST_EQUAL(map2.getIdentifier(), "lsid") TEST_EQUAL(map2.getMetaValue("meta").toString(),"value") TEST_EQUAL(map2.getColumnHeaders()[0].filename == "blub", true) TEST_EQUAL(map2.getColumnHeaders()[0].label == "label", true) TEST_EQUAL(map2.getColumnHeaders()[0].size == 47, true) TEST_EQUAL(map2.getColumnHeaders()[0].getMetaValue("meta") == "meta", true) TEST_EQUAL(map2.getExperimentType(), "labeled_MS2") TEST_EQUAL(map2.getDataProcessing().size(),1) TEST_EQUAL(map2.getProteinIdentifications().size(),1) TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),1) //assignment of empty object ConsensusMap map2_empty; map2 = std::move(map2_empty); // move TEST_EQUAL(map2.getIdentifier(), "") TEST_EQUAL(map2.getColumnHeaders().size(), 0) TEST_EQUAL(map2.getExperimentType(), "label-free") // default TEST_EQUAL(map2.getDataProcessing().size(), 0) TEST_EQUAL(map2.getProteinIdentifications().size(), 0) TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(), 0) END_SECTION START_SECTION((ConsensusMap(ConsensusMap && source))) static_assert(std::is_move_constructible_v<ConsensusMap>); ConsensusMap mp_source(map_const_1); ConsensusMap map2(std::move(mp_source)); TEST_EQUAL(map2.getIdentifier(),"lsid") TEST_EQUAL(map2.getMetaValue("meta").toString(),"value") TEST_EQUAL(map2.getColumnHeaders()[0].filename == "blub", true) TEST_EQUAL(map2.getColumnHeaders()[0].label == "label", true) TEST_EQUAL(map2.getColumnHeaders()[0].size == 47, true) TEST_EQUAL(map2.getColumnHeaders()[0].getMetaValue("meta") == "meta", true) TEST_EQUAL(map2.getExperimentType(),"labeled_MS2") TEST_EQUAL(map2.getDataProcessing().size(),1) TEST_EQUAL(map2.getProteinIdentifications().size(),1); TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),1); END_SECTION START_SECTION((ConsensusMap(size_type n))) ConsensusMap cons_map(5); TEST_EQUAL(cons_map.size(),5) END_SECTION ///// START_SECTION(([ConsensusMap::ColumnHeader] ColumnHeader())) ConsensusMap::ColumnHeader* fd_ptr = new ConsensusMap::ColumnHeader();; ConsensusMap::ColumnHeader* fd_nullPointer = nullptr; TEST_NOT_EQUAL(fd_ptr, fd_nullPointer) delete fd_ptr; END_SECTION START_SECTION((const ColumnHeaders& getColumnHeaders() const)) ConsensusMap cons_map; TEST_EQUAL(cons_map.getColumnHeaders().size(),0) END_SECTION START_SECTION((ColumnHeaders& getColumnHeaders())) ConsensusMap cons_map; cons_map.getColumnHeaders()[0].filename = "blub"; TEST_EQUAL(cons_map.getColumnHeaders()[0].filename == "blub", true) END_SECTION START_SECTION((const String& getExperimentType() const)) ConsensusMap cons_map; TEST_EQUAL(cons_map.getExperimentType() == "label-free", true) END_SECTION START_SECTION((void setExperimentType(const String& experiment_type))) ConsensusMap cons_map; cons_map.setExperimentType("labeled_MS2"); TEST_EQUAL(cons_map.getExperimentType(),"labeled_MS2") END_SECTION START_SECTION((void swap(ConsensusMap& from))) ConsensusMap map1, map2; ConsensusFeature f; f.insert(1,Feature()); map1.push_back(f); map1.getColumnHeaders()[1].filename = "bla"; map1.getColumnHeaders()[1].size = 5; map1.setIdentifier("LSID"); map1.setExperimentType("labeled_MS2"); map1.getDataProcessing().resize(1); map1.getProteinIdentifications().resize(1); map1.getUnassignedPeptideIdentifications().resize(1); map1.swap(map2); TEST_EQUAL(map1.size(),0) TEST_EQUAL(map1.getColumnHeaders().size(),0) TEST_EQUAL(map1.getIdentifier(),"") TEST_EQUAL(map1.getDataProcessing().size(),0) TEST_EQUAL(map1.getProteinIdentifications().size(),0); TEST_EQUAL(map1.getUnassignedPeptideIdentifications().size(),0); TEST_EQUAL(map2.size(),1) TEST_EQUAL(map2.getColumnHeaders().size(),1) TEST_EQUAL(map2.getIdentifier(),"LSID") TEST_EQUAL(map2.getExperimentType(),"labeled_MS2") TEST_EQUAL(map2.getDataProcessing().size(),1) TEST_EQUAL(map2.getProteinIdentifications().size(),1); TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),1); END_SECTION START_SECTION((bool operator == (const ConsensusMap& rhs) const)) ConsensusMap empty,edit; TEST_TRUE(empty == edit); edit.setIdentifier("lsid");; TEST_EQUAL(empty==edit, false); edit = empty; edit.push_back(ConsensusFeature(feature1)); TEST_EQUAL(empty==edit, false); edit = empty; edit.getDataProcessing().resize(1); TEST_EQUAL(empty==edit, false); edit = empty; edit.setMetaValue("bla", 4.1); TEST_EQUAL(empty==edit, false); edit = empty; edit.getColumnHeaders()[0].filename = "bla"; TEST_EQUAL(empty==edit, false); edit = empty; edit.setExperimentType("labeled_MS2"); TEST_EQUAL(empty==edit, false); edit = empty; edit.getProteinIdentifications().resize(10); TEST_EQUAL(empty==edit, false); edit = empty; edit.getUnassignedPeptideIdentifications().resize(10); TEST_EQUAL(empty==edit, false); edit = empty; edit.setExperimentType("labeled_MS2"); TEST_EQUAL(empty==edit, false); edit = empty; edit.push_back(ConsensusFeature(feature1)); edit.push_back(ConsensusFeature(feature2)); edit.updateRanges(); edit.clear(false); TEST_EQUAL(empty==edit, false); END_SECTION START_SECTION((bool operator != (const ConsensusMap& rhs) const)) ConsensusMap empty,edit; TEST_EQUAL(empty!=edit, false); edit.setIdentifier("lsid");; TEST_FALSE(empty == edit); edit = empty; edit.push_back(ConsensusFeature(feature1)); TEST_FALSE(empty == edit); edit = empty; edit.getDataProcessing().resize(1); TEST_FALSE(empty == edit); edit = empty; edit.setMetaValue("bla", 4.1); TEST_FALSE(empty == edit); edit = empty; edit.getColumnHeaders()[0].filename = "bla"; TEST_FALSE(empty == edit) edit = empty; edit.setExperimentType("labeled_MS2"); TEST_FALSE(empty == edit); edit = empty; edit.getProteinIdentifications().resize(10); TEST_FALSE(empty == edit); edit = empty; edit.getUnassignedPeptideIdentifications().resize(10); TEST_FALSE(empty == edit); edit = empty; edit.push_back(ConsensusFeature(feature1)); edit.push_back(ConsensusFeature(feature2)); edit.updateRanges(); edit.clear(false); TEST_FALSE(empty == edit); END_SECTION START_SECTION((void sortByIntensity(bool reverse=false))) { NOT_TESTABLE; // tested within TOPP TextExporter } END_SECTION START_SECTION((void sortByRT())) { NOT_TESTABLE; // tested within TOPP TextExporter } END_SECTION START_SECTION((void sortByMZ())) { NOT_TESTABLE; // tested within TOPP TextExporter } END_SECTION START_SECTION((void sortByPosition())) { NOT_TESTABLE; // tested within TOPP TextExporter } END_SECTION START_SECTION((void sortByQuality(bool reverse=false))) { NOT_TESTABLE; // tested within TOPP TextExporter } END_SECTION START_SECTION((void sortBySize())) { NOT_TESTABLE; // tested within TOPP TextExporter } END_SECTION START_SECTION((void sortByMaps())) { NOT_TESTABLE; // tested within TOPP TextExporter } END_SECTION START_SECTION((void sortPeptideIdentificationsByMapIndex())) { NOT_TESTABLE; // tested within TOPP IDMapper } END_SECTION START_SECTION((void clear(bool clear_meta_data = true))) { ConsensusMap map1; ConsensusFeature f; f.insert(1,Feature()); map1.push_back(f); map1.getColumnHeaders()[1].filename = "bla"; map1.getColumnHeaders()[1].size = 5; map1.setIdentifier("LSID"); map1.setExperimentType("labeled_MS2"); map1.getDataProcessing().resize(1); map1.getProteinIdentifications().resize(1); map1.getUnassignedPeptideIdentifications().resize(1); map1.clear(false); TEST_EQUAL(map1.size(), 0) TEST_EQUAL(map1 == ConsensusMap(),false) TEST_EQUAL(map1.empty(),true) map1.clear(true); TEST_EQUAL(map1.size(), 0) TEST_EQUAL(map1 == ConsensusMap(),true) TEST_EQUAL(map1.empty(),true) } END_SECTION START_SECTION((template < typename Type > Size applyMemberFunction(Size(Type::*member_function)()))) { ConsensusMap cm; cm.push_back(ConsensusFeature()); cm.push_back(ConsensusFeature()); cm.push_back(ConsensusFeature()); TEST_EQUAL(cm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),4); cm.setUniqueId(); TEST_EQUAL(cm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),3); cm.applyMemberFunction(&UniqueIdInterface::setUniqueId); TEST_EQUAL(cm.applyMemberFunction(&UniqueIdInterface::hasValidUniqueId),4); TEST_EQUAL(cm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),0); cm.begin()->clearUniqueId(); TEST_EQUAL(cm.applyMemberFunction(&UniqueIdInterface::hasValidUniqueId),3); TEST_EQUAL(cm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),1); } END_SECTION START_SECTION((template < typename Type > Size applyMemberFunction(Size(Type::*member_function)() const ) const )) { ConsensusMap cm; ConsensusMap const & cmc(cm); cm.push_back(ConsensusFeature()); cm.push_back(ConsensusFeature()); cm.push_back(ConsensusFeature()); TEST_EQUAL(cmc.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),4); cm.setUniqueId(); TEST_EQUAL(cmc.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),3); cm.applyMemberFunction(&UniqueIdInterface::setUniqueId); TEST_EQUAL(cmc.applyMemberFunction(&UniqueIdInterface::hasValidUniqueId),4); TEST_EQUAL(cm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),0); cm.begin()->clearUniqueId(); TEST_EQUAL(cmc.applyMemberFunction(&UniqueIdInterface::hasValidUniqueId),3); TEST_EQUAL(cmc.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),1); } END_SECTION START_SECTION(void split(std::vector<FeatureMap>& fmaps, SplitMeta mode = SplitMeta::DISCARD) const) { // prepare test data ConsensusMap cm; auto& headers = cm.getColumnHeaders(); headers[0].filename = "file.FeatureXML"; headers[1].filename = "file2.FeatureXML"; ConsensusFeature cf1, cf2; cf1.insert(FeatureHandle(0, Peak2D({ 10, 433.33 }, 100000), 0)); cf1.insert(FeatureHandle(1, Peak2D({ 11, 434.33 }, 200000), 0)); PeptideIdentification id1, id2; id1.setRT(10); id1.insertHit(PeptideHit(0.1, 1, 3, AASequence::fromString("AAA"))); id1.setMetaValue("map_index", 0); cf1.getPeptideIdentifications().push_back(id1); cf1.setMetaValue("test", "some information"); cm.push_back(cf1); cf2.insert(FeatureHandle(0, Peak2D({ 20, 433.33 }, 300000), 0)); cf2.insert(FeatureHandle(1, Peak2D({ 21, 433.33 }, 400000), 0)); id2.setRT(20); id2.insertHit(PeptideHit(0.1, 1, 3, AASequence::fromString("WWW"))); id2.setMetaValue("map_index", 1); cf2.getPeptideIdentifications().push_back(id2); cm.push_back(cf2); PeptideIdentification uid1, uid2; uid1.insertHit(PeptideHit(0.1, 1, 3, AASequence::fromString("LLL"))); uid1.setMetaValue("map_index", 0); uid2.insertHit(PeptideHit(0.1, 1, 3, AASequence::fromString("KKK"))); uid2.setMetaValue("map_index", 1); cm.getUnassignedPeptideIdentifications().push_back(uid1); cm.getUnassignedPeptideIdentifications().push_back(uid2); vector<FeatureMap> fmaps; // test with non iso analyze data fmaps = cm.split(ConsensusMap::SplitMeta::DISCARD); ABORT_IF(fmaps.size() != 2); ABORT_IF(fmaps[0].size() != 2); ABORT_IF(fmaps[1].size() != 2); // map 0 TEST_EQUAL(fmaps[0][0].getRT(), 10); TEST_EQUAL(fmaps[0][0].getIntensity(), 100000); TEST_EQUAL(fmaps[0][0].getPeptideIdentifications()[0].getHits()[0].getSequence().toString(), "AAA"); TEST_EQUAL(fmaps[0][0].metaValueExists("test"), false); TEST_EQUAL(fmaps[0][1].getRT(), 20); TEST_EQUAL(fmaps[0][1].getIntensity(), 300000); TEST_EQUAL(fmaps[0][1].getPeptideIdentifications().empty(), true); // map 1 TEST_EQUAL(fmaps[1][0].getRT(), 11); TEST_EQUAL(fmaps[1][0].getIntensity(), 200000); TEST_EQUAL(fmaps[1][0].getPeptideIdentifications().empty(), true); TEST_EQUAL(fmaps[1][1].getRT(), 21); TEST_EQUAL(fmaps[1][1].getIntensity(), 400000); TEST_EQUAL(fmaps[1][1].getPeptideIdentifications()[0].getHits()[0].getSequence().toString(), "WWW"); TEST_EQUAL(fmaps[0].getUnassignedPeptideIdentifications()[0].getHits()[0].getSequence().toString(), "LLL"); TEST_EQUAL(fmaps[1].getUnassignedPeptideIdentifications()[0].getHits()[0].getSequence().toString(), "KKK"); // test with iso analyze data DataProcessing p; set<DataProcessing::ProcessingAction> actions; actions.insert(DataProcessing::QUANTITATION); p.setProcessingActions(actions); p.setSoftware(Software("IsobaricAnalyzer")); cm.getDataProcessing().push_back(p); fmaps = cm.split(ConsensusMap::SplitMeta::DISCARD); ABORT_IF(fmaps.size() != 2); ABORT_IF(fmaps[0].size() != 2); ABORT_IF(fmaps[1].size() != 2); const auto pi00 = fmaps[0][0].getPeptideIdentifications(); const auto pi01 = fmaps[0][1].getPeptideIdentifications(); TEST_EQUAL(pi00[0].getHits()[0].getSequence(),AASequence::fromString("AAA")); TEST_EQUAL(pi01[0].getHits()[0].getSequence(),AASequence::fromString("WWW")); TEST_EQUAL(fmaps[0].getUnassignedPeptideIdentifications()[0].getHits()[0].getSequence(),AASequence::fromString("LLL")); TEST_EQUAL(fmaps[0].getUnassignedPeptideIdentifications()[1].getHits()[0].getSequence(),AASequence::fromString("KKK")); TEST_EQUAL(fmaps[1][0].getPeptideIdentifications().empty(), true); TEST_EQUAL(fmaps[1][1].getPeptideIdentifications().empty(), true); // test different all meta value modes fmaps = cm.split(ConsensusMap::SplitMeta::COPY_FIRST); ABORT_IF(fmaps.size() != 2); ABORT_IF(fmaps[0].size() != 2); ABORT_IF(fmaps[1].size() != 2); TEST_EQUAL(fmaps[0][0].metaValueExists("test"), true); TEST_EQUAL(fmaps[0][0].getMetaValue("test"), "some information"); TEST_EQUAL(fmaps[1][0].metaValueExists("test"), false); fmaps = cm.split(ConsensusMap::SplitMeta::COPY_ALL); ABORT_IF(fmaps.size() != 2); ABORT_IF(fmaps[0].size() != 2); ABORT_IF(fmaps[1].size() != 2); TEST_EQUAL(fmaps[0][0].metaValueExists("test"), true); TEST_EQUAL(fmaps[0][0].getMetaValue("test"),"some information"); TEST_EQUAL(fmaps[1][0].metaValueExists("test"), true); TEST_EQUAL(fmaps[1][0].getMetaValue("test"),"some information"); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ChargePair_test.cpp
.cpp
7,105
278
// 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/ChargePair.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/Compomer.h> #include <OpenMS/DATASTRUCTURES/Adduct.h> #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; START_TEST(ChargePair, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ChargePair* ptr = nullptr; ChargePair* nullPointer = nullptr; START_SECTION(ChargePair()) { ptr = new ChargePair(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~ChargePair()) { delete ptr; } END_SECTION Compomer cmp; cmp.setID(99); START_SECTION((ChargePair(const Size &index0, const Size &index1, const Int &charge0, const Int &charge1, const Compomer &compomer, const double &mass_diff, const bool active))) { ChargePair cp(34,45, 4,5, cmp, 12.34, false); TEST_EQUAL(cp.getElementIndex(0), 34); TEST_EQUAL(cp.getElementIndex(1), 45); TEST_EQUAL(cp.getCharge(0), 4); TEST_EQUAL(cp.getCharge(1), 5); TEST_EQUAL(cp.getCompomer(), cmp); TEST_REAL_SIMILAR(cp.getMassDiff(), 12.34); TEST_EQUAL(cp.isActive(), false); } END_SECTION START_SECTION((ChargePair(const ChargePair &rhs))) { ChargePair cp2(34,45, 4,5, cmp, 12.34, false); ChargePair cp (cp2); TEST_EQUAL(cp.getElementIndex(0), 34); TEST_EQUAL(cp.getElementIndex(1), 45); TEST_EQUAL(cp.getCharge(0), 4); TEST_EQUAL(cp.getCharge(1), 5); TEST_EQUAL(cp.getCompomer(), cmp); TEST_REAL_SIMILAR(cp.getMassDiff(), 12.34); TEST_EQUAL(cp.getEdgeScore(), 1); TEST_EQUAL(cp.isActive(), false); } END_SECTION START_SECTION((ChargePair& operator=(const ChargePair &rhs))) { ChargePair cp2(34,45, 4,5, cmp, 12.34, false); ChargePair cp = cp2; TEST_EQUAL(cp.getElementIndex(0), 34); TEST_EQUAL(cp.getElementIndex(1), 45); TEST_EQUAL(cp.getCharge(0), 4); TEST_EQUAL(cp.getCharge(1), 5); TEST_EQUAL(cp.getCompomer(), cmp); TEST_REAL_SIMILAR(cp.getMassDiff(), 12.34); TEST_EQUAL(cp.getEdgeScore(), 1); TEST_EQUAL(cp.isActive(), false); } END_SECTION START_SECTION((Int getCharge(UInt pairID) const )) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setCharge(UInt pairID, Int e))) { ChargePair cp; cp.setCharge(0,123); cp.setCharge(1,321); TEST_EQUAL(cp.getCharge(0), 123) TEST_EQUAL(cp.getCharge(1), 321) } END_SECTION START_SECTION((Size getElementIndex(UInt pairID) const )) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setElementIndex(UInt pairID, Size e))) { ChargePair cp; cp.setElementIndex(0,123); cp.setElementIndex(1,321); TEST_EQUAL(cp.getElementIndex(0), 123) TEST_EQUAL(cp.getElementIndex(1), 321) } END_SECTION START_SECTION((const Compomer& getCompomer() const)) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setCompomer(const Compomer &compomer))) { ChargePair cp; cp.setCompomer(cmp); TEST_EQUAL(cp.getCompomer(), cmp) } END_SECTION START_SECTION((double getMassDiff() const)) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setMassDiff(double mass_diff))) { ChargePair cp; cp.setMassDiff(123.432); TEST_REAL_SIMILAR(cp.getMassDiff(), 123.432) } END_SECTION START_SECTION((double getEdgeScore() const)) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setEdgeScore(double score))) { ChargePair cp; cp.setEdgeScore(1123.432f); TEST_REAL_SIMILAR(cp.getEdgeScore(), 1123.432) } END_SECTION START_SECTION((bool isActive() const)) { NOT_TESTABLE //well.. tested below... } END_SECTION START_SECTION((void setActive(const bool active))) { ChargePair cp; cp.setActive(true); TEST_EQUAL(cp.isActive(), true) cp.setActive(false); TEST_EQUAL(cp.isActive(), false) } END_SECTION START_SECTION((virtual bool operator==(const ChargePair &i) const)) { ChargePair cp1(34,45, 4,5, cmp, 12.34, false); ChargePair cp2(34,15, 4,5, cmp, 12.34, false); TEST_EQUAL(cp1==cp2, false); ChargePair cp3(34,15, 4,5, cmp, 12.34, true); ChargePair cp4(34,15, 4,5, cmp, 12.34, false); TEST_EQUAL(cp3==cp4, false); ChargePair cp5(34,15, 4,5, cmp, 12.34, false); ChargePair cp6(34,15, 4,5, cmp, 12.34, false); TEST_TRUE(cp5 == cp6); } END_SECTION START_SECTION((virtual bool operator!=(const ChargePair &i) const)) { ChargePair cp1(34,45, 4,5, cmp, 12.34, false); ChargePair cp2(34,15, 4,5, cmp, 12.34, false); TEST_FALSE(cp1 == cp2); ChargePair cp3(34,15, 4,5, cmp, 12.34, true); ChargePair cp4(34,15, 4,5, cmp, 12.34, false); TEST_FALSE(cp3 == cp4); ChargePair cp5(34,15, 4,5, cmp, 12.34, false); ChargePair cp6(34,15, 4,5, cmp, 12.34, false); TEST_EQUAL(cp5!=cp6, false); } END_SECTION START_SECTION(([EXTRA] std::hash<ChargePair>)) { std::hash<ChargePair> hasher; // Test that equal objects have equal hashes ChargePair cp1(34,45, 4,5, cmp, 12.34, false); ChargePair cp2(34,45, 4,5, cmp, 12.34, false); TEST_TRUE(cp1 == cp2); TEST_EQUAL(hasher(cp1), hasher(cp2)); // Test that different objects (likely) have different hashes ChargePair cp3(34,15, 4,5, cmp, 12.34, false); TEST_FALSE(cp1 == cp3); TEST_NOT_EQUAL(hasher(cp1), hasher(cp3)); // Test with different charges ChargePair cp4(34,45, 3,5, cmp, 12.34, false); TEST_FALSE(cp1 == cp4); TEST_NOT_EQUAL(hasher(cp1), hasher(cp4)); // Test with different active state ChargePair cp5(34,45, 4,5, cmp, 12.34, true); TEST_FALSE(cp1 == cp5); TEST_NOT_EQUAL(hasher(cp1), hasher(cp5)); // Test with different mass_diff ChargePair cp6(34,45, 4,5, cmp, 99.99, false); TEST_FALSE(cp1 == cp6); TEST_NOT_EQUAL(hasher(cp1), hasher(cp6)); // Test that score_ (not in operator==) does not affect hash ChargePair cp7(34,45, 4,5, cmp, 12.34, false); cp7.setEdgeScore(999.0); ChargePair cp8(34,45, 4,5, cmp, 12.34, false); cp8.setEdgeScore(1.0); TEST_TRUE(cp7 == cp8); TEST_EQUAL(hasher(cp7), hasher(cp8)); // Test use in unordered_set std::unordered_set<ChargePair> cp_set; cp_set.insert(cp1); cp_set.insert(cp2); // duplicate, should not increase size cp_set.insert(cp3); TEST_EQUAL(cp_set.size(), 2); TEST_EQUAL(cp_set.count(cp1), 1); TEST_EQUAL(cp_set.count(cp3), 1); // Test use in unordered_map std::unordered_map<ChargePair, int> cp_map; cp_map[cp1] = 100; cp_map[cp3] = 200; TEST_EQUAL(cp_map.size(), 2); TEST_EQUAL(cp_map[cp1], 100); TEST_EQUAL(cp_map[cp3], 200); cp_map[cp2] = 150; // cp2 == cp1, should overwrite TEST_EQUAL(cp_map.size(), 2); TEST_EQUAL(cp_map[cp1], 150); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CVMappingFile_test.cpp
.cpp
6,277
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/FORMAT/CVMappingFile.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/CVMappingTerm.h> #include <OpenMS/DATASTRUCTURES/CVReference.h> using namespace OpenMS; using namespace std; START_TEST(CVMappingFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CVMappingFile* ptr = nullptr; CVMappingFile* nullPointer = nullptr; START_SECTION(CVMappingFile()) { ptr = new CVMappingFile(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~CVMappingFile()) { delete ptr; } END_SECTION START_SECTION((void load(const String &filename, CVMappings &cv_mappings, bool strip_namespaces=false))) { CVMappings mappings; CVMappingFile().load(OPENMS_GET_TEST_DATA_PATH("cv_mapping_test_file.xml"), mappings); TEST_EQUAL(mappings.getMappingRules().size(), 9) vector<CVMappingRule> rules = mappings.getMappingRules(); TEST_STRING_EQUAL(rules[0].getIdentifier(), "0") TEST_STRING_EQUAL(rules[1].getIdentifier(), "1") TEST_STRING_EQUAL(rules[2].getIdentifier(), "2") TEST_STRING_EQUAL(rules[3].getIdentifier(), "3") TEST_STRING_EQUAL(rules[4].getIdentifier(), "4") TEST_STRING_EQUAL(rules[5].getIdentifier(), "5") TEST_STRING_EQUAL(rules[6].getIdentifier(), "6") TEST_STRING_EQUAL(rules[7].getIdentifier(), "7") TEST_STRING_EQUAL(rules[8].getIdentifier(), "8") TEST_EQUAL(rules[0].getCVTerms().size(), 14) TEST_STRING_EQUAL(rules[0].getElementPath(), "/mzData/description/admin/sampleDescription/cvParam/@accession") TEST_EQUAL(rules[0].getRequirementLevel(), CVMappingRule::MAY) TEST_STRING_EQUAL(rules[0].getScopePath(), "/mzData/description/admin/sampleDescription") TEST_EQUAL(rules[0].getCombinationsLogic(), CVMappingRule::OR) TEST_EQUAL(rules[1].getCVTerms().size(), 32) TEST_STRING_EQUAL(rules[1].getElementPath(), "/mzData/description/instrument/source/cvParam/@accession") TEST_EQUAL(rules[1].getRequirementLevel(), CVMappingRule::SHOULD) TEST_STRING_EQUAL(rules[1].getScopePath(), "/mzData/description/instrument/source") TEST_EQUAL(rules[1].getCombinationsLogic(), CVMappingRule::XOR) TEST_EQUAL(rules[2].getCVTerms().size(), 46) TEST_STRING_EQUAL(rules[2].getElementPath(), "/mzData/description/instrument/analyzerList/analyzer/cvParam/@accession") TEST_EQUAL(rules[2].getRequirementLevel(), CVMappingRule::MUST) TEST_STRING_EQUAL(rules[2].getScopePath(), "/mzData/description/instrument/analyzerList/analyzer") TEST_EQUAL(rules[2].getCombinationsLogic(), CVMappingRule::AND) TEST_STRING_EQUAL(rules[0].getCVTerms()[0].getAccession(), "PSI:1000001") TEST_EQUAL(rules[0].getCVTerms()[0].getUseTermName(), false) TEST_EQUAL(rules[0].getCVTerms()[0].getUseTerm(), true) TEST_STRING_EQUAL(rules[0].getCVTerms()[0].getTermName(), "Sample Number") TEST_EQUAL(rules[0].getCVTerms()[0].getIsRepeatable(), true) TEST_EQUAL(rules[0].getCVTerms()[0].getAllowChildren(), true) TEST_STRING_EQUAL(rules[0].getCVTerms()[0].getCVIdentifierRef(), "PSI") TEST_STRING_EQUAL(rules[0].getCVTerms()[1].getAccession(), "PSI:1000002") TEST_EQUAL(rules[0].getCVTerms()[1].getUseTermName(), true) TEST_EQUAL(rules[0].getCVTerms()[1].getUseTerm(), true) TEST_STRING_EQUAL(rules[0].getCVTerms()[1].getTermName(), "Sample Name") TEST_EQUAL(rules[0].getCVTerms()[1].getIsRepeatable(), true) TEST_EQUAL(rules[0].getCVTerms()[1].getAllowChildren(), true) TEST_STRING_EQUAL(rules[0].getCVTerms()[1].getCVIdentifierRef(), "PSI") TEST_STRING_EQUAL(rules[0].getCVTerms()[2].getAccession(), "PSI:1000003") TEST_EQUAL(rules[0].getCVTerms()[2].getUseTermName(), true) TEST_EQUAL(rules[0].getCVTerms()[2].getUseTerm(), false) TEST_STRING_EQUAL(rules[0].getCVTerms()[2].getTermName(), "Sample State") TEST_EQUAL(rules[0].getCVTerms()[2].getIsRepeatable(), true) TEST_EQUAL(rules[0].getCVTerms()[2].getAllowChildren(), true) TEST_STRING_EQUAL(rules[0].getCVTerms()[2].getCVIdentifierRef(), "PSI") TEST_STRING_EQUAL(rules[0].getCVTerms()[3].getAccession(), "PSI:1000004") TEST_EQUAL(rules[0].getCVTerms()[3].getUseTermName(), true) TEST_EQUAL(rules[0].getCVTerms()[3].getUseTerm(), false) TEST_STRING_EQUAL(rules[0].getCVTerms()[3].getTermName(), "Sample Mass") TEST_EQUAL(rules[0].getCVTerms()[3].getIsRepeatable(), false) TEST_EQUAL(rules[0].getCVTerms()[3].getAllowChildren(), true) TEST_STRING_EQUAL(rules[0].getCVTerms()[3].getCVIdentifierRef(), "PSI") TEST_STRING_EQUAL(rules[0].getCVTerms()[4].getAccession(), "PSI:1000005") TEST_EQUAL(rules[0].getCVTerms()[4].getUseTermName(), true) TEST_EQUAL(rules[0].getCVTerms()[4].getUseTerm(), false) TEST_STRING_EQUAL(rules[0].getCVTerms()[4].getTermName(), "Sample Volume") TEST_EQUAL(rules[0].getCVTerms()[4].getIsRepeatable(), false) TEST_EQUAL(rules[0].getCVTerms()[4].getAllowChildren(), false) TEST_STRING_EQUAL(rules[0].getCVTerms()[4].getCVIdentifierRef(), "PSI") TEST_STRING_EQUAL(rules[0].getCVTerms()[5].getAccession(), "PSI:1000006") TEST_EQUAL(rules[0].getCVTerms()[5].getUseTermName(), false) TEST_EQUAL(rules[0].getCVTerms()[5].getUseTerm(), true) TEST_STRING_EQUAL(rules[0].getCVTerms()[5].getTermName(), "Sample Concentration") TEST_EQUAL(rules[0].getCVTerms()[5].getIsRepeatable(), true) TEST_EQUAL(rules[0].getCVTerms()[5].getAllowChildren(), true) TEST_STRING_EQUAL(rules[0].getCVTerms()[5].getCVIdentifierRef(), "PSI") TEST_EQUAL(mappings.getCVReferences().size(), 1) TEST_STRING_EQUAL(mappings.getCVReferences().begin()->getName(), "mzData CV") TEST_STRING_EQUAL(mappings.getCVReferences().begin()->getIdentifier(), "PSI") TEST_EQUAL(mappings.hasCVReference("PSI"), true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PrecursorPurity_test.cpp
.cpp
8,961
191
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Eugen Netz $ // $Authors: Eugen Netz $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/ANALYSIS/ID/PrecursorPurity.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/MzMLFile.h> START_TEST(PrecursorPurity, "$Id$") using namespace OpenMS; using namespace std; PeakMap spectra; MzMLFile f; PeakFileOptions options; options.clearMSLevels(); options.addMSLevel(1); options.addMSLevel(2); f.getOptions() = options; // the file is a copy of OPENMS_GET_TEST_DATA_PATH("IsobaricChannelExtractor_6.mzML") // which contains two MS1 spectra and 5 MS2 spectra between them f.load(OPENMS_GET_TEST_DATA_PATH("PrecursorPurity_input.mzML"), spectra); START_SECTION(static PurityScores computePrecursorPurity(const PeakSpectrum& ms1, const Precursor& pre, const double precursor_mass_tolerance, const bool precursor_mass_tolerance_unit_ppm)) TEST_EQUAL(spectra.size(), 7) // the MS1 spectra are soectra[0] and spectra[6] Precursor pre = spectra[2].getPrecursors()[0]; PrecursorPurity::PurityScores score = PrecursorPurity::computePrecursorPurity(spectra[6], pre, 10, true); TEST_REAL_SIMILAR(score.total_intensity, 11557777.1875) TEST_REAL_SIMILAR(score.target_intensity, 8923915) TEST_REAL_SIMILAR(score.signal_proportion, 0.77211) TEST_EQUAL(score.target_peak_count, 1) TEST_EQUAL(score.interfering_peak_count, 3) pre = spectra[3].getPrecursors()[0]; score = PrecursorPurity::computePrecursorPurity(spectra[0], pre, 0.2, false); TEST_REAL_SIMILAR(score.total_intensity, 9098343.89062) TEST_REAL_SIMILAR(score.target_intensity, 7057944) TEST_REAL_SIMILAR(score.signal_proportion, 0.77573) TEST_EQUAL(score.target_peak_count, 1) TEST_EQUAL(score.interfering_peak_count, 4) END_SECTION START_SECTION(static computePrecursorPurities(const PeakMap& spectra, double precursor_mass_tolerance, bool precursor_mass_tolerance_unit_ppm)) map<String, PrecursorPurity::PurityScores> purityscores = PrecursorPurity::computePrecursorPurities(spectra, 0.1, false); TEST_EQUAL(purityscores.size(), 5) // using the ID of an MS1 spectrum, a new ID for the map, adds a new Score to the map, initialized to 0 TEST_REAL_SIMILAR(purityscores[spectra[0].getNativeID()].total_intensity, 0) TEST_REAL_SIMILAR(purityscores[spectra[0].getNativeID()].target_intensity, 0) TEST_REAL_SIMILAR(purityscores[spectra[0].getNativeID()].signal_proportion, 0) TEST_EQUAL(purityscores[spectra[0].getNativeID()].target_peak_count, 0) TEST_EQUAL(purityscores[spectra[0].getNativeID()].interfering_peak_count, 0) // 5 MS2 spectra between two MS1 spectra TEST_REAL_SIMILAR(purityscores[spectra[1].getNativeID()].total_intensity, 5517171) TEST_REAL_SIMILAR(purityscores[spectra[1].getNativeID()].target_intensity, 5517171) TEST_REAL_SIMILAR(purityscores[spectra[1].getNativeID()].signal_proportion, 1) TEST_EQUAL(purityscores[spectra[1].getNativeID()].target_peak_count, 1) TEST_EQUAL(purityscores[spectra[1].getNativeID()].interfering_peak_count, 0) TEST_REAL_SIMILAR(purityscores[spectra[2].getNativeID()].total_intensity, 11287967.625) TEST_REAL_SIMILAR(purityscores[spectra[2].getNativeID()].target_intensity, 7390478.5) TEST_REAL_SIMILAR(purityscores[spectra[2].getNativeID()].signal_proportion, 0.65472) TEST_EQUAL(purityscores[spectra[2].getNativeID()].target_peak_count, 1) TEST_EQUAL(purityscores[spectra[2].getNativeID()].interfering_peak_count, 3) TEST_REAL_SIMILAR(purityscores[spectra[3].getNativeID()].total_intensity, 9098343.89062) TEST_REAL_SIMILAR(purityscores[spectra[3].getNativeID()].target_intensity, 7057944) TEST_REAL_SIMILAR(purityscores[spectra[3].getNativeID()].signal_proportion, 0.77573) TEST_EQUAL(purityscores[spectra[3].getNativeID()].target_peak_count, 1) TEST_EQUAL(purityscores[spectra[3].getNativeID()].interfering_peak_count, 4) TEST_REAL_SIMILAR(purityscores[spectra[4].getNativeID()].total_intensity, 9762418.03906) TEST_REAL_SIMILAR(purityscores[spectra[4].getNativeID()].target_intensity, 7029896.5) TEST_REAL_SIMILAR(purityscores[spectra[4].getNativeID()].signal_proportion, 0.72009) TEST_EQUAL(purityscores[spectra[4].getNativeID()].target_peak_count, 1) TEST_EQUAL(purityscores[spectra[4].getNativeID()].interfering_peak_count, 5) TEST_REAL_SIMILAR(purityscores[spectra[5].getNativeID()].total_intensity, 5465177) TEST_REAL_SIMILAR(purityscores[spectra[5].getNativeID()].target_intensity, 5465177) TEST_REAL_SIMILAR(purityscores[spectra[5].getNativeID()].signal_proportion, 1) TEST_EQUAL(purityscores[spectra[5].getNativeID()].target_peak_count, 1) TEST_EQUAL(purityscores[spectra[5].getNativeID()].interfering_peak_count, 0) // using the ID of an MS1 spectrum, a new ID for the map, adds a new Score to the map, initialized to 0 TEST_REAL_SIMILAR(purityscores[spectra[6].getNativeID()].total_intensity, 0) TEST_REAL_SIMILAR(purityscores[spectra[6].getNativeID()].target_intensity, 0) TEST_REAL_SIMILAR(purityscores[spectra[6].getNativeID()].signal_proportion, 0) TEST_EQUAL(purityscores[spectra[6].getNativeID()].target_peak_count, 0) TEST_EQUAL(purityscores[spectra[6].getNativeID()].interfering_peak_count, 0) TEST_REAL_SIMILAR(purityscores["randomString"].total_intensity, 0) TEST_REAL_SIMILAR(purityscores["randomString"].target_intensity, 0) TEST_REAL_SIMILAR(purityscores["randomString"].signal_proportion, 0) TEST_EQUAL(purityscores["randomString"].target_peak_count, 0) TEST_EQUAL(purityscores["randomString"].interfering_peak_count, 0) PeakMap spectra_copy = spectra; // If the PeakMap does not start with an MS1 spectrum, PrecursorPurity is not applicable and returns an empty vector spectra[0].setMSLevel(2); purityscores = PrecursorPurity::computePrecursorPurities(spectra, 0.1, false); TEST_EQUAL(purityscores.size(), 0) spectra[5].setMSLevel(1); purityscores = PrecursorPurity::computePrecursorPurities(spectra, 0.1, false); TEST_EQUAL(purityscores.size(), 0) spectra = spectra_copy; // duplicate IDs, skip the computation spectra = spectra_copy; TEST_EQUAL(spectra[2].getNativeID(), "controllerType=0 controllerNumber=1 scan=4") spectra[2].setNativeID(spectra[4].getNativeID()); TEST_EQUAL(spectra[2].getNativeID(), "controllerType=0 controllerNumber=1 scan=8") TEST_EQUAL(spectra[4].getNativeID(), "controllerType=0 controllerNumber=1 scan=8") purityscores = PrecursorPurity::computePrecursorPurities(spectra, 0.1, false); TEST_EQUAL(purityscores.size(), 0) // empty ID, skip the computation spectra = spectra_copy; spectra[3].setNativeID(""); purityscores = PrecursorPurity::computePrecursorPurities(spectra, 0.1, false); TEST_EQUAL(purityscores.size(), 0) START_SECTION(static computeInterpolatedPrecursorPurity edge cases with fallback to early scan purity) // Test case 1: next_ms1_spec_idx is out of range (too large) std::vector<double> early_purity = PrecursorPurity::computeSingleScanPrecursorPurities(1, 0, spectra, 20.0); std::vector<double> interpolated_invalid_idx = PrecursorPurity::computeInterpolatedPrecursorPurity(1, 0, 999, spectra, 20.0); TEST_EQUAL(early_purity.size(), interpolated_invalid_idx.size()) for (Size i = 0; i < early_purity.size(); ++i) { TEST_REAL_SIMILAR(early_purity[i], interpolated_invalid_idx[i]) } // Test case 2: next_ms1_spec_idx is negative std::vector<double> interpolated_negative_idx = PrecursorPurity::computeInterpolatedPrecursorPurity(1, 0, -1, spectra, 20.0); TEST_EQUAL(early_purity.size(), interpolated_negative_idx.size()) for (Size i = 0; i < early_purity.size(); ++i) { TEST_REAL_SIMILAR(early_purity[i], interpolated_negative_idx[i]) } // Test case 3: next_ms1_spec_idx points to an MS2 spectrum (not MS1) std::vector<double> interpolated_ms2_idx = PrecursorPurity::computeInterpolatedPrecursorPurity(1, 0, 2, spectra, 20.0); TEST_EQUAL(early_purity.size(), interpolated_ms2_idx.size()) for (Size i = 0; i < early_purity.size(); ++i) { TEST_REAL_SIMILAR(early_purity[i], interpolated_ms2_idx[i]) } // Test case 4: Valid interpolation case for comparison std::vector<double> interpolated_valid = PrecursorPurity::computeInterpolatedPrecursorPurity(1, 0, 6, spectra, 20.0); // The valid interpolation should differ from early_purity (unless by coincidence) // We just ensure it executes without error and returns reasonable values TEST_EQUAL(early_purity.size(), interpolated_valid.size()) for (Size i = 0; i < interpolated_valid.size(); ++i) { TEST_EQUAL(interpolated_valid[i] >= 0.0 && interpolated_valid[i] <= 1.0, true) } END_SECTION END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeakPickerIM_test.cpp
.cpp
6,849
150
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Author: Timo Sachsenberg $ // $Maintainer: Timo Sachsenberg $ // ------------------------------------------------------------------------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/CONCEPT/Constants.h> #include <cmath> /////////////////////////// #include <OpenMS/PROCESSING/CENTROIDING/PeakPickerIM.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(PeakPickerIM, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeakPickerIM* ptr = nullptr; PeakPickerIM* nullPointer = nullptr; START_SECTION((PeakPickerIM())) ptr = new PeakPickerIM(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~PeakPickerIM())) delete ptr; END_SECTION MSSpectrum input; // two m/z profile peaks at 300 and 800 m/z, each with 5 ion mobility scans (0.4 to 1.2 Vs/cm2) and Gaussian intensity distribution along IM // each m/z peak has 4 points per IM scan (0.01 m/z spacing, 0.1 Vs/cm2 spacing) ///std::vector<double> mzs = {299.91, 299.97, 300.03, 300.09, 299.91, 299.97, 300.03, 300.09, 299.91, 299.97, 300.03, 300.09, 299.91, 299.97, 300.03, 300.09, 299.91, 299.97, 300.03, 300.09, 799.88, 799.96, 800.04, 800.12, 799.88, 799.96, 800.04, 800.12, 799.88, 799.96, 800.04, 800.12, 799.88, 799.96, 800.04, 800.12, 799.88, 799.96, 800.04, 800.12}; ///std::vector<double> IMs = {0.4469780242779817, 0.4469780242779817, 0.4469780242779817, 0.4469780242779817, 0.5669780242779817, 0.5669780242779817, 0.5669780242779817, 0.5669780242779817, 0.6869780242779817, 0.6869780242779817, 0.6869780242779817, 0.6869780242779817, 0.8069780242779817, 0.8069780242779817, 0.8069780242779817, 0.8069780242779817, 0.9269780242779817, 0.9269780242779817, 0.9269780242779817, 0.9269780242779817, 0.21943921987602621, 0.21943921987602621, 0.21943921987602621, 0.21943921987602621, 0.36943921987602624, 0.36943921987602624, 0.36943921987602624, 0.36943921987602624, 0.5194392198760263, 0.5194392198760263, 0.5194392198760263, 0.5194392198760263, 0.6694392198760263, 0.6694392198760263, 0.6694392198760263, 0.6694392198760263, 0.8194392198760263, 0.8194392198760263, 0.8194392198760263, 0.8194392198760263}; ///std::vector<double> Intensities = {0.1234098040869882, 6.737946999091595, 6.737946999091595, 0.1234098040869882, 3.606563136024751, 196.91167520437313, 196.91167520437313, 3.606563136024751, 11.108996538270091, 606.530659713185, 606.530659713185, 11.108996538270091, 3.606563136024751, 196.91167520437313, 196.91167520437313, 3.606563136024751, 0.1234098040869882, 6.737946999091595, 6.737946999091595, 0.1234098040869882, 0.6170490204331873, 33.689734995457975, 33.689734995457975, 0.6170490204331873, 18.032815680072503, 984.5583760218657, 984.5583760218657, 18.032815680072503, 55.54498269119259, 3032.6532985659255, 3032.6532985659255, 55.54498269119259, 18.032815680072503, 984.5583760218657, 984.5583760218657, 18.032815680072503, 0.6170490204331873, 33.689734995457975, 33.689734995457975, 0.6170490204331873}; // Synthetic 2D Gaussian peak around m/z 300 with two IM peaks (0.8, 1.0) std::vector<double> mzs; std::vector<double> IMs; std::vector<double> Intensities; // --- Parameters for m/z Gaussian --- const double mz_center = 300.0; const double mz_sigma = 0.0025; const double mz_min = 299.99; const double mz_max = 300.01; const double mz_step = 0.0005; // --- Parameters for IM Gaussians --- const double im_center1 = 0.8; const double im_center2 = 1.0; const double im_sigma = 0.03; const double im_min = 0.7; const double im_max = 1.1; const double im_step = 0.01; // Build the 2D grid: for each m/z, duplicate across all IM scans for (double mz = mz_min; mz <= mz_max + 1e-9; mz += mz_step) { // 1D Gaussian in m/z const double mz_int = std::exp(-0.5 * std::pow((mz - mz_center) / mz_sigma, 2.0)); for (double im = im_min; im <= im_max + 1e-9; im += im_step) { // Two Gaussians in IM dimension const double im_int1 = std::exp(-0.5 * std::pow((im - im_center1) / im_sigma, 2.0)); const double im_int2 = std::exp(-0.5 * std::pow((im - im_center2) / im_sigma, 2.0)); const double im_int = im_int1 + im_int2; // Final separable 2D intensity const double intensity = mz_int * im_int; mzs.push_back(mz); IMs.push_back(im); Intensities.push_back(intensity); } } for (size_t i = 0; i < mzs.size(); ++i) { input.emplace_back(mzs[i], Intensities[i]); } input.getFloatDataArrays().resize(1); input.getFloatDataArrays()[0].setName(Constants::UserParam::ION_MOBILITY); for (size_t i = 0; i < IMs.size(); ++i) { input.getFloatDataArrays()[0].push_back(IMs[i]); } input.setIMFormat(IMFormat::CONCATENATED); /* TODO make it more robust to also handle sparse data (e.g. asymetrical or even only one m/z value per IM scan) // create dummy ion mobility spectrum with concatenated scans { const size_t points_per_im = 10; // For each ion mobility value (1.0 to 10.0) for (double im = 1.0; im <= 10.0; im += 1.0) { double baseIntensity = (im <= 5.0) ? 200.0 + ((im - 1.0) * 200.0) : // Increasing intensity from IM 1.0 to 5.0 1000.0 - ((im - 5.0) * 200.0); // Decreasing intensity from IM 6.0 to 10.0 // Create 10 data points for each ion mobility value for (size_t i = 0; i < points_per_im; i++) { double mz = 100.0 + (i * 0.01); double intensity = baseIntensity + (i * 20.0); input.emplace_back(mz, intensity); } } // Set up the ion mobility array input.getFloatDataArrays().resize(1); input.getFloatDataArrays()[0].setName(Constants::UserParam::ION_MOBILITY); // Add ion mobility values (each repeated 10 times) for (double im = 1.0; im <= 10.0; im += 1.0) { for (size_t i = 0; i < points_per_im; i++) { input.getFloatDataArrays()[0].push_back(im); } } } */ START_SECTION(void pickIMTraces(MSSpectrum& spectrum)) { PeakPickerIM pp_im; pp_im.pickIMTraces(input); TEST_EQUAL(input.size(), 2) TEST_REAL_SIMILAR(input[0].getIntensity(), 5.70646) TEST_REAL_SIMILAR(input[0].getMZ(), 300.0) TEST_EQUAL(input.getFloatDataArrays().size(), 1) TEST_EQUAL(input.getFloatDataArrays()[0].getName(), Constants::UserParam::ION_MOBILITY_CENTROID) TEST_REAL_SIMILAR(input.getFloatDataArrays()[0][0], 0.8) } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/RTAlignment_test.cpp
.cpp
4,876
133
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow // $Authors: Juliane Schmachtenberg $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/METADATA/DataProcessing.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/QC/RTAlignment.h> /////////////////////////// START_TEST(RTAlignment, "$Id$"); ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; RTAlignment* ptr = nullptr; RTAlignment* nullPointer = nullptr; START_SECTION(RTAlignment()) { ptr = new RTAlignment; TEST_NOT_EQUAL(ptr, nullPointer); } END_SECTION START_SECTION(~RTAlignment()) { delete ptr; } END_SECTION RTAlignment rtA; START_SECTION(QCBase::Status requirements() const override) { TEST_EQUAL(rtA.requirements() == (QCBase::Status() | QCBase::Requires::TRAFOALIGN | QCBase::Requires::POSTFDRFEAT), true); } END_SECTION START_SECTION(const String& getName() const override) {TEST_EQUAL(rtA.getName(), "RTAlignment")} END_SECTION START_SECTION((compute(FeatureMap & features, TransformationDescription& trafo))) { // Valid FeatureMap FeatureMap fmap; PeptideIdentification peptide_ID; PeptideIdentificationList identifications; PeptideIdentificationList unassignedIDs; Feature feature1, feature2; peptide_ID.setRT(0); identifications.push_back(peptide_ID); peptide_ID.setRT(1); identifications.push_back(peptide_ID); feature1.setPeptideIdentifications(identifications); identifications.clear(); fmap.push_back(feature1); peptide_ID.setRT(10); identifications.push_back(peptide_ID); peptide_ID.setRT(12); identifications.push_back(peptide_ID); feature2.setPeptideIdentifications(identifications); fmap.push_back(feature2); // unassigned PeptideHits peptide_ID.setRT(0.5); unassignedIDs.push_back(peptide_ID); peptide_ID.setRT(2.5); unassignedIDs.push_back(peptide_ID); fmap.setUnassignedPeptideIdentifications(unassignedIDs); // Transformation TransformationDescription td; td.fitModel("identity", Param()); td.setDataPoints(vector<pair<double, double>> {{0.0, 1.0}, {0.25, 1.5}, {0.5, 2.0}, {1.0, 3.0}}); td.fitModel("linear"); RTAlignment rtA; rtA.compute(fmap, td); // test features TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[0].getMetaValue("rt_align"), 1); TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[0].getMetaValue("rt_raw"), 0); TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[1].getMetaValue("rt_align"), 3); TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[1].getMetaValue("rt_raw"), 1); TEST_REAL_SIMILAR(fmap[1].getPeptideIdentifications()[0].getMetaValue("rt_align"), 21); TEST_REAL_SIMILAR(fmap[1].getPeptideIdentifications()[0].getMetaValue("rt_raw"), 10); // test unassigned TEST_REAL_SIMILAR(fmap.getUnassignedPeptideIdentifications()[0].getMetaValue("rt_align"), 2); TEST_REAL_SIMILAR(fmap.getUnassignedPeptideIdentifications()[0].getMetaValue("rt_raw"), 0.5); TEST_REAL_SIMILAR(fmap.getUnassignedPeptideIdentifications()[1].getMetaValue("rt_align"), 6); TEST_REAL_SIMILAR(fmap.getUnassignedPeptideIdentifications()[1].getMetaValue("rt_raw"), 2.5); // empty FeatureMap FeatureMap fmap_empty {}; rtA.compute(fmap_empty, td); // empty feature Feature feature_empty {}; fmap_empty.push_back(feature_empty); rtA.compute(fmap_empty, td); // empty PeptideIdentifications identifications.clear(); feature1.setPeptideIdentifications(identifications); fmap_empty.push_back(feature1); rtA.compute(fmap_empty, td); // empty PeptideIdentification PeptideIdentification peptide_ID_empty {}; identifications.push_back(peptide_ID_empty); feature1.setPeptideIdentifications(identifications); fmap_empty.push_back(feature1); rtA.compute(fmap_empty, td); // data processing: after alignment DataProcessing processing_method {}; std::set<DataProcessing::ProcessingAction> dp {DataProcessing::ProcessingAction::ALIGNMENT}; processing_method.setProcessingActions(dp); fmap.setDataProcessing({processing_method}); TEST_EXCEPTION_WITH_MESSAGE(Exception::IllegalArgument, rtA.compute(fmap, td), "Metric RTAlignment received a featureXML AFTER map alignment, but needs a featureXML BEFORE map alignment!"); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FeatureDeconvolution_test.cpp
.cpp
7,658
220
// 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 <map> /////////////////////////// #include <OpenMS/ANALYSIS/DECHARGING/FeatureDeconvolution.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> #include <OpenMS/CONCEPT/FuzzyStringComparator.h> /////////////////////////// namespace OpenMS { class FeatureDeconvolutionTest : public FeatureDeconvolution { public: /// List of adducts used to explain mass differences MassExplainer::AdductsType getPotentialAdducts() { return potential_adducts_;} /// labeling table std::map<Size, String> getMapLabels() { return map_label_;} /// labeling table inverse std::map<String, Size> getMapLabelInverse() { return map_label_inverse_;} /// status of intensity filter for edges bool isIntensityFilterEnabled() { return enable_intensity_filter_;} /// status of charge discovery CHARGEMODE getChargeMode() { return q_try_;} }; } using namespace OpenMS; using namespace std; START_TEST(FeatureDeconvolution, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FeatureDeconvolution* ptr = nullptr; FeatureDeconvolution* nullPointer = nullptr; START_SECTION(FeatureDeconvolution()) ptr = new FeatureDeconvolution(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~FeatureDeconvolution()) delete ptr; END_SECTION START_SECTION([EXTRA](void updateMembers_())) FeatureDeconvolutionTest fdt; Param p; p.setValue("charge_min", 11, "minimal possible charge"); p.setValue("charge_max", 13, "maximal possible charge"); p.setValue("retention_max_diff", 1.0, "maximum allowed RT difference between any two features if their relation shall be determined"); p.setValue("retention_max_diff_local", 2.0, "maxi"); p.setValue("potential_adducts", std::vector<std::string>{"H:+:0.7","Na:+:0.1","(2)H4H-4:0:0.1:-2:heavy"}, "Ad"); fdt.setParameters(p); { MassExplainer::AdductsType adducts = fdt.getPotentialAdducts(); std::map<Size, String> map = fdt.getMapLabels(); std::map<String, Size> map_i = fdt.getMapLabelInverse(); bool b_filter = fdt.isIntensityFilterEnabled(); FeatureDeconvolution::CHARGEMODE cm = fdt.getChargeMode(); TEST_EQUAL(adducts.size(), 3) TEST_EQUAL(adducts[0].getFormula(), "H1"); TEST_EQUAL(adducts[0].getRTShift(), 0); TEST_EQUAL(adducts[0].getCharge(), 1); TEST_REAL_SIMILAR(adducts[0].getLogProb(), log(0.7)); TEST_EQUAL(adducts[1].getFormula(), "Na1"); TEST_EQUAL(adducts[1].getRTShift(), 0); TEST_EQUAL(adducts[1].getCharge(), 1); TEST_REAL_SIMILAR(adducts[1].getLogProb(), log(0.1)); TEST_EQUAL(adducts[2].getFormula(), "(2)H4H-4"); TEST_EQUAL(adducts[2].getRTShift(), -2); TEST_EQUAL(adducts[2].getCharge(), 0); TEST_REAL_SIMILAR(adducts[2].getLogProb(), log(0.1)); TEST_EQUAL(cm, FeatureDeconvolution::CHARGEMODE::QFROMFEATURE) TEST_EQUAL(map.size(), 2) TEST_EQUAL(map_i.size(), 2) TEST_EQUAL(map[0], "decharged features"); TEST_EQUAL(map_i["decharged features"], 0); TEST_EQUAL(map[1], "heavy"); TEST_EQUAL(map_i["heavy"], 1); TEST_EQUAL(b_filter, false) Param p_internal = fdt.getParameters(); TEST_REAL_SIMILAR((double) p_internal.getValue("retention_max_diff"), 1.0); TEST_REAL_SIMILAR((double) p_internal.getValue("retention_max_diff_local"), 1.0); } // second param set p.setValue("charge_min", 11, "minimal possible charge"); p.setValue("charge_max", 13, "maximal possible charge"); p.setValue("q_try", "heuristic", "Try dif"); p.setValue("potential_adducts", std::vector<std::string>{"H:+:0.9","Na:++:0.1"}); p.setValue("retention_max_diff", 1.0, "maximum "); p.setValue("retention_max_diff_local", 1.0, "maxim"); p.setValue("intensity_filter", "true", "Enable"); p.setValue("default_map_label", "mylabel", "Label"); p.setValue("retention_max_diff", 2.0, "maximum allowed RT difference between any two features if their relation shall be determined"); p.setValue("retention_max_diff_local", 5.0, "maxi"); fdt.setParameters(p); { MassExplainer::AdductsType adducts = fdt.getPotentialAdducts(); std::map<Size, String> map = fdt.getMapLabels(); std::map<String, Size> map_i = fdt.getMapLabelInverse(); bool b_filter = fdt.isIntensityFilterEnabled(); FeatureDeconvolution::CHARGEMODE cm = fdt.getChargeMode(); TEST_EQUAL(adducts.size(), 2) TEST_EQUAL(adducts[0].getFormula(), "H1"); TEST_EQUAL(adducts[0].getRTShift(), 0); TEST_EQUAL(adducts[0].getCharge(), 1); TEST_REAL_SIMILAR(adducts[0].getLogProb(), log(0.9)); TEST_EQUAL(adducts[1].getFormula(), "Na1"); TEST_EQUAL(adducts[1].getRTShift(), 0); TEST_EQUAL(adducts[1].getCharge(), 2); TEST_REAL_SIMILAR(adducts[1].getLogProb(), log(0.1)); TEST_EQUAL(cm, FeatureDeconvolution::CHARGEMODE::QHEURISTIC) TEST_EQUAL(map.size(), 1) TEST_EQUAL(map_i.size(), 1) TEST_EQUAL(map[0], "mylabel"); TEST_EQUAL(map_i["mylabel"], 0); TEST_EQUAL(b_filter, true) Param p_internal = fdt.getParameters(); TEST_REAL_SIMILAR((double) p_internal.getValue("retention_max_diff"), 2.0); TEST_REAL_SIMILAR((double) p_internal.getValue("retention_max_diff_local"), 2.0); } END_SECTION START_SECTION(FeatureDeconvolution(const FeatureDeconvolution &source)) FeatureDeconvolution fd; Param p; p.setValue("charge_min", 11, "minimal possible charge"); p.setValue("charge_max", 13, "maximal possible charge"); fd.setParameters(p); FeatureDeconvolution fd2(fd); FeatureDeconvolution fd_untouched; TEST_EQUAL(fd2.getParameters(), fd.getParameters()) TEST_NOT_EQUAL(fd2.getParameters(), fd_untouched.getParameters()) END_SECTION START_SECTION(FeatureDeconvolution& operator=(const FeatureDeconvolution &source)) FeatureDeconvolution fd; Param p; p.setValue("charge_min", 11, "minimal possible charge"); p.setValue("charge_max", 13, "maximal possible charge"); fd.setParameters(p); FeatureDeconvolution fd2 = fd; FeatureDeconvolution fd_untouched; TEST_EQUAL(fd2.getParameters(), fd.getParameters()) TEST_NOT_EQUAL(fd2.getParameters(), fd_untouched.getParameters()) END_SECTION START_SECTION(void compute(const FeatureMapType &fm_in, FeatureMapType &fm_out, ConsensusMap &cons_map, ConsensusMap &cons_map_p)) //_CrtSetDbgFlag(_CrtSetDbgFlag(0)|_CRTDBG_CHECK_ALWAYS_DF); FeatureDeconvolution fd; Param p; p.setValue("potential_adducts", std::vector<std::string>{"H:+:0.7","Na:+:0.1","(2)H4H-4:0:0.1:-2:heavy"}, "Ad"); p.setValue("mass_max_diff", 0.1); fd.setParameters(p); FeatureMap fm_in, fm_out; ConsensusMap cm, cm2; FeatureXMLFile fl; fl.load(OPENMS_GET_TEST_DATA_PATH("FeatureDeconvolution_easy_input.featureXML"), fm_in); fd.compute(fm_in, fm_out, cm, cm2); String out_file; NEW_TMP_FILE(out_file) ConsensusXMLFile c1; c1.store(out_file,cm); WHITELIST("xml-stylesheet"); // WHITELIST("xml-stylesheet,consensusElement id="); // WHITELIST("xml-stylesheet,map id,consensusElement id="); TEST_FILE_SIMILAR(out_file, OPENMS_GET_TEST_DATA_PATH("FeatureDeconvolution_easy_output.consensusXML")); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MzIdentMLValidator_test.cpp
.cpp
1,368
47
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/VALIDATORS/MzIdentMLValidator.h> #include <OpenMS/DATASTRUCTURES/CVMappings.h> #include <OpenMS/FORMAT/ControlledVocabulary.h> /////////////////////////// START_TEST(MzIdentMLValidator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace OpenMS::Internal; using namespace std; CVMappings mapping; ControlledVocabulary cv; SemanticValidator* ptr = nullptr; SemanticValidator* nullPointer = nullptr; START_SECTION((MzIdentMLValidator(const CVMappings& mapping, const ControlledVocabulary& cv))) ptr = new MzIdentMLValidator(mapping,cv); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~MzIdentMLValidator())) delete ptr; END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ModifiedNASequenceGenerator_test.cpp
.cpp
4,328
101
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: $ // $Authors: Timo Sachsenberg $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/CHEMISTRY/ModifiedNASequenceGenerator.h> #include <OpenMS/CHEMISTRY/Ribonucleotide.h> #include <OpenMS/CHEMISTRY/RibonucleotideDB.h> /////////////////////////// #include <string> using namespace OpenMS; using namespace std; START_TEST(ModifiedNASequenceGenerator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// RibonucleotideDB* db = RibonucleotideDB::getInstance(); START_SECTION((static void applyFixedModifications(const std::set<ModifiedNASequenceGenerator::ConstRibonucleotidePtr>& fixed_mods, NASequence& sequence))) { set<ModifiedNASequenceGenerator::ConstRibonucleotidePtr> fixed_mods; // query modified ribos by code vector<string> fixed_mods_code = {"s4U"}; // 4-thiouridine for (auto const & f : fixed_mods_code) { fixed_mods.insert(db->getRibonucleotide(f)); } NASequence sequence = NASequence::fromString("AUAUAUA"); ModifiedNASequenceGenerator::applyFixedModifications(fixed_mods, sequence); TEST_STRING_EQUAL(sequence.toString(), "A[s4U]A[s4U]A[s4U]A"); // additional check if internal representation equal NASequence sequence2 = NASequence::fromString("A[s4U]A[s4U]A[s4U]A"); TEST_EQUAL(sequence, sequence2); } END_SECTION START_SECTION(static void applyVariableModifications(const std::set<ConstRibonucleotidePtr>& var_mods, const NASequence& seq, Size max_variable_mods_per_NASequence, std::vector<NASequence>& all_modified_NASequences, bool keep_original = true)) { set<ModifiedNASequenceGenerator::ConstRibonucleotidePtr> var_mods; // query modified ribos by code vector<string> mods_code = {"m3U", "s4U"}; // 3-methyluridine, 4-thiouridine for (auto const & f : mods_code) { var_mods.insert(db->getRibonucleotide(f)); } NASequence sequence = NASequence::fromString("AUAUAUA"); vector<NASequence> ams; // (1) Add at most one modification. (true) return the unmodified version ModifiedNASequenceGenerator::applyVariableModifications(var_mods, sequence, 1, ams, true); TEST_EQUAL(ams.size(), 7); TEST_STRING_EQUAL(ams[0].toString(), NASequence::fromString("AUAUAUA").toString()); // the order of "m3U" and "s4U" in "var_mods" is unclear (pointers ordered by // address) and determines the order of the result ("ams") - need to sort: sort(++ams.begin(), ams.end()); TEST_STRING_EQUAL(ams[1].toString(), NASequence::fromString("AUAUA[m3U]A").toString()); TEST_STRING_EQUAL(ams[2].toString(), NASequence::fromString("AUAUA[s4U]A").toString()); TEST_STRING_EQUAL(ams[3].toString(), NASequence::fromString("AUA[m3U]AUA").toString()); TEST_STRING_EQUAL(ams[4].toString(), NASequence::fromString("AUA[s4U]AUA").toString()); TEST_STRING_EQUAL(ams[5].toString(), NASequence::fromString("A[m3U]AUAUA").toString()); TEST_STRING_EQUAL(ams[6].toString(), NASequence::fromString("A[s4U]AUAUA").toString()); ams.clear(); // (1) Add at most one modification. (false) without the unmodified version ModifiedNASequenceGenerator::applyVariableModifications(var_mods, sequence, 1, ams, false); TEST_EQUAL(ams.size(), 6); // same as before but now without the unmodified version ams.clear(); // (3) Add at most three modification. (true) with the unmodified version ModifiedNASequenceGenerator::applyVariableModifications(var_mods, sequence, 3, ams, true); TEST_EQUAL(ams.size(), 3*3*3); // 3^3 sequences expected // test modification of A and U ams.clear(); var_mods.clear(); mods_code = {"s4U", "m3U", "m1A"}; for (auto const & f : mods_code) { var_mods.insert(db->getRibonucleotide(f)); } ModifiedNASequenceGenerator::applyVariableModifications(var_mods, sequence, 7, ams, true); TEST_EQUAL(ams.size(), 3*3*3*2*2*2*2); // 3^3 combinations for U times 2^4 for A } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IDScoreSwitcherAlgorithm_test.cpp
.cpp
6,162
182
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Immanuel Luhn$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/ID/IDScoreSwitcherAlgorithm.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <vector> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(IDRipper, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ///load input data std::vector< ProteinIdentification > protein_identifications; PeptideIdentificationList identifications; String document_id; IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDScoreSwitcherAlgorithm_test_input.idXML"), protein_identifications, identifications, document_id); PeptideIdentification identification = identifications[0]; ProteinIdentification protein_identification = protein_identifications[0]; IDScoreSwitcherAlgorithm* ptr = nullptr; IDScoreSwitcherAlgorithm* null_ptr = nullptr; START_SECTION(IDScoreSwitcherAlgorithm()) { ptr = new IDScoreSwitcherAlgorithm(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~IDScoreSwitcherAlgorithm()) { delete ptr; } END_SECTION START_SECTION(switchToGeneralScoreType) { IDScoreSwitcherAlgorithm switcher{}; Size c(0); switcher.switchToGeneralScoreType(identifications, IDScoreSwitcherAlgorithm::ScoreType::PEP, c); TEST_EQUAL(identifications[0].getScoreType(), "Posterior Error Probability"); } END_SECTION START_SECTION(findScoreType) { IDScoreSwitcherAlgorithm switcher{}; // Test case 1: When main score is already a PEP score PeptideIdentification pep_id_with_pep_main; pep_id_with_pep_main.setScoreType("Posterior Error Probability"); pep_id_with_pep_main.setHigherScoreBetter(false); PeptideHit hit1; hit1.setScore(0.05); pep_id_with_pep_main.insertHit(hit1); IDScoreSwitcherAlgorithm::ScoreSearchResult result1 = switcher.findScoreType(pep_id_with_pep_main, IDScoreSwitcherAlgorithm::ScoreType::PEP); TEST_EQUAL(result1.is_main_score_type, true); TEST_EQUAL(result1.score_name, "Posterior Error Probability"); // Test case 2: When main score is not PEP but PEP is available in meta values PeptideIdentification pep_id_with_pep_meta; pep_id_with_pep_meta.setScoreType("XTandem"); pep_id_with_pep_meta.setHigherScoreBetter(true); PeptideHit hit2; hit2.setScore(100.0); hit2.setMetaValue("pep", 0.01); hit2.setMetaValue("other_score", 0.5); pep_id_with_pep_meta.insertHit(hit2); auto result2 = switcher.findScoreType(pep_id_with_pep_meta, IDScoreSwitcherAlgorithm::ScoreType::PEP); TEST_EQUAL(result2.is_main_score_type, false); TEST_EQUAL(result2.score_name, "pep"); // Test case 3: When main score is not PEP and no PEP available in meta values PeptideIdentification pep_id_no_pep; pep_id_no_pep.setScoreType("Mascot"); pep_id_no_pep.setHigherScoreBetter(true); PeptideHit hit3; hit3.setScore(50.0); hit3.setMetaValue("e_value", 0.001); pep_id_no_pep.insertHit(hit3); auto result3 = switcher.findScoreType(pep_id_no_pep, IDScoreSwitcherAlgorithm::ScoreType::PEP); TEST_EQUAL(result3.is_main_score_type, false); TEST_EQUAL(result3.score_name.empty(), true); // Test case 4: Check various PEP score name variants from the enum collection PeptideIdentification pep_id_uppercase; pep_id_uppercase.setScoreType("Mascot"); PeptideHit hit4; hit4.setScore(75.0); hit4.setMetaValue("PEP", 0.02); // Uppercase variant pep_id_uppercase.insertHit(hit4); auto result4 = switcher.findScoreType(pep_id_uppercase, IDScoreSwitcherAlgorithm::ScoreType::PEP); TEST_EQUAL(result4.is_main_score_type, false); TEST_EQUAL(result4.score_name, "PEP"); // Test case 5: Check _score suffix variant PeptideIdentification pep_id_suffix; pep_id_suffix.setScoreType("SEQUEST:xcorr"); PeptideHit hit5; hit5.setScore(2.5); hit5.setMetaValue("pep_score", 0.03); // With _score suffix pep_id_suffix.insertHit(hit5); auto result5 = switcher.findScoreType(pep_id_suffix, IDScoreSwitcherAlgorithm::ScoreType::PEP); TEST_EQUAL(result5.is_main_score_type, false); TEST_EQUAL(result5.score_name, "pep_score"); // Test case 6: Test with Q-value score type PeptideIdentification qval_id_main; qval_id_main.setScoreType("q-value"); qval_id_main.setHigherScoreBetter(false); PeptideHit hit6; hit6.setScore(0.02); qval_id_main.insertHit(hit6); auto result6 = switcher.findScoreType(qval_id_main, IDScoreSwitcherAlgorithm::ScoreType::QVAL); TEST_EQUAL(result6.is_main_score_type, true); TEST_EQUAL(result6.score_name, "q-value"); // Test case 7: Test with Q-value in meta values PeptideIdentification qval_id_meta; qval_id_meta.setScoreType("Mascot"); qval_id_meta.setHigherScoreBetter(true); PeptideHit hit7; hit7.setScore(60.0); hit7.setMetaValue("qvalue", 0.05); qval_id_meta.insertHit(hit7); auto result7 = switcher.findScoreType(qval_id_meta, IDScoreSwitcherAlgorithm::ScoreType::QVAL); TEST_EQUAL(result7.is_main_score_type, false); TEST_EQUAL(result7.score_name, "qvalue"); // Test case 8: Test with FDR score type PeptideIdentification fdr_id_meta; fdr_id_meta.setScoreType("XTandem"); fdr_id_meta.setHigherScoreBetter(true); PeptideHit hit8; hit8.setScore(120.0); hit8.setMetaValue("FDR", 0.01); fdr_id_meta.insertHit(hit8); auto result8 = switcher.findScoreType(fdr_id_meta, IDScoreSwitcherAlgorithm::ScoreType::FDR); TEST_EQUAL(result8.is_main_score_type, false); TEST_EQUAL(result8.score_name, "FDR"); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ROCCurve_test.cpp
.cpp
2,638
103
// 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/ML/ROCCURVE/ROCCurve.h> /////////////////////////// #include <cmath> #include <ctime> #include <vector> /////////////////////////// START_TEST(ROCCurve, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; using namespace OpenMS::Math; ROCCurve* rcp = nullptr; ROCCurve* rcp_nullPointer = nullptr; START_SECTION((ROCCurve())) rcp = new ROCCurve(); TEST_NOT_EQUAL(rcp, rcp_nullPointer) END_SECTION START_SECTION((void insertPair(double score, bool clas))) srand((unsigned)time(nullptr)); for (Size i = 0; i < 1000; ++i) { double score = (double)rand()/RAND_MAX; bool clas = (rand() > RAND_MAX/2); rcp->insertPair(score, clas); } NOT_TESTABLE END_SECTION START_SECTION((double AUC())) // random test: double auc = rcp->AUC(); bool inBounds = ( auc >= 0 && auc <= 1 ); TEST_EQUAL(inBounds,true) // some real data: ROCCurve rc; TEST_EQUAL(rc.AUC(),0.5) END_SECTION START_SECTION((std::vector<std::pair<double, double> > curve(UInt resolution = 10))) vector<pair<double,double> > curvePoints = rcp->curve(100); TEST_EQUAL(curvePoints.size(),100) END_SECTION START_SECTION((double cutoffPos(double fraction=0.95))) double cop = rcp->cutoffPos(); bool inBounds( cop >=0 && cop <= 1 ); TEST_EQUAL(inBounds,true) END_SECTION START_SECTION((double cutoffNeg(double fraction=0.95))) double con = rcp->cutoffNeg(); bool inBounds( con >=0 && con <= 1 ); TEST_EQUAL(inBounds,true) END_SECTION START_SECTION((ROCCurve(const ROCCurve& source))) ROCCurve crc(*rcp); double ccop = crc.cutoffPos(); double cop = rcp->cutoffPos(); TEST_REAL_SIMILAR(ccop,cop) END_SECTION START_SECTION((ROCCurve& operator = (const ROCCurve& source))) ROCCurve crc = *rcp; double ccop = crc.cutoffPos(); double cop = rcp->cutoffPos(); TEST_REAL_SIMILAR(cop,ccop) END_SECTION START_SECTION((virtual ~ROCCurve())) delete rcp; END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TraMLValidator_test.cpp
.cpp
1,330
50
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/VALIDATORS/TraMLValidator.h> /////////////////////////// #include <OpenMS/FORMAT/ControlledVocabulary.h> using namespace OpenMS; using namespace OpenMS::Internal; using namespace std; START_TEST(TraMLValidator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CVMappings mapping; ControlledVocabulary cv; TraMLValidator* ptr = nullptr; TraMLValidator* nullPointer = nullptr; START_SECTION((TraMLValidator(const CVMappings &mapping, const ControlledVocabulary &cv))) { ptr = new TraMLValidator(mapping, cv); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~TraMLValidator()) { delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ContactPerson_test.cpp
.cpp
6,580
255
// 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/ContactPerson.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ContactPerson, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ContactPerson* ptr = nullptr; ContactPerson* nullPointer = nullptr; START_SECTION(ContactPerson()) ptr = new ContactPerson(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~ContactPerson()) delete ptr; END_SECTION START_SECTION(const String& getContactInfo() const) ContactPerson tmp; TEST_EQUAL(tmp.getContactInfo(),""); END_SECTION START_SECTION(void setContactInfo(const String& contact_info)) ContactPerson tmp; tmp.setContactInfo("bla"); TEST_EQUAL(tmp.getContactInfo(),"bla"); END_SECTION START_SECTION(const String& getEmail() const) ContactPerson tmp; TEST_EQUAL(tmp.getEmail(),""); END_SECTION START_SECTION(void setEmail(const String& email)) ContactPerson tmp; tmp.setEmail("bla"); TEST_EQUAL(tmp.getEmail(),"bla"); END_SECTION START_SECTION(const String& getURL() const) ContactPerson tmp; TEST_EQUAL(tmp.getURL(),""); END_SECTION START_SECTION(void setURL(const String& email)) ContactPerson tmp; tmp.setURL("bla"); TEST_EQUAL(tmp.getURL(),"bla"); END_SECTION START_SECTION(const String& getAddress() const) ContactPerson tmp; TEST_EQUAL(tmp.getAddress(),""); END_SECTION START_SECTION(void setAddress(const String& email)) ContactPerson tmp; tmp.setAddress("bla"); TEST_EQUAL(tmp.getAddress(),"bla"); END_SECTION START_SECTION(const String& getInstitution() const) ContactPerson tmp; TEST_EQUAL(tmp.getInstitution(),""); END_SECTION START_SECTION(void setInstitution(const String& institution)) ContactPerson tmp; tmp.setInstitution("Uni Tuebingen"); TEST_EQUAL(tmp.getInstitution(),"Uni Tuebingen"); END_SECTION START_SECTION(const String& getFirstName() const) ContactPerson tmp; TEST_EQUAL(tmp.getFirstName(),""); END_SECTION START_SECTION(void setFirstName(const String& name)) ContactPerson tmp; tmp.setFirstName("Meike"); TEST_EQUAL(tmp.getFirstName(),"Meike"); END_SECTION START_SECTION(const String& getLastName() const) ContactPerson tmp; TEST_EQUAL(tmp.getLastName(),""); END_SECTION START_SECTION(void setLastName(const String& name)) ContactPerson tmp; tmp.setLastName("Meier"); TEST_EQUAL(tmp.getLastName(),"Meier"); END_SECTION START_SECTION(void setName(const String& name)) ContactPerson tmp; tmp.setName("Diddl Maus"); TEST_EQUAL(tmp.getFirstName(),"Diddl"); TEST_EQUAL(tmp.getLastName(),"Maus"); tmp.setName("Normal, Otto"); TEST_EQUAL(tmp.getFirstName(),"Otto"); TEST_EQUAL(tmp.getLastName(),"Normal"); tmp.setName("Meiser, Hans F."); TEST_EQUAL(tmp.getFirstName(),"Hans F."); TEST_EQUAL(tmp.getLastName(),"Meiser"); END_SECTION START_SECTION(ContactPerson(const ContactPerson& source)) ContactPerson tmp; tmp.setEmail("ich@du.de"); tmp.setFirstName("Meike"); tmp.setLastName("Meier"); tmp.setInstitution("Uni Tuebingen"); tmp.setContactInfo("doo"); tmp.setURL("url"); tmp.setAddress("street"); tmp.setMetaValue("label",String("label")); ContactPerson tmp2(tmp); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_EQUAL(tmp2.getFirstName(),"Meike"); TEST_EQUAL(tmp2.getLastName(),"Meier"); TEST_EQUAL(tmp2.getEmail(),"ich@du.de"); TEST_EQUAL(tmp2.getInstitution(),"Uni Tuebingen"); TEST_EQUAL(tmp2.getContactInfo(),"doo"); TEST_EQUAL(tmp2.getURL(),"url"); TEST_EQUAL(tmp2.getAddress(),"street"); END_SECTION START_SECTION(ContactPerson& operator= (const ContactPerson& source)) ContactPerson tmp; tmp.setEmail("ich@du.de"); tmp.setFirstName("Meike"); tmp.setLastName("Meier"); tmp.setInstitution("Uni Tuebingen"); tmp.setContactInfo("doo"); tmp.setURL("url"); tmp.setAddress("street"); tmp.setMetaValue("label",String("label")); //normal assignment ContactPerson tmp2; tmp2 = tmp; TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_EQUAL(tmp2.getFirstName(),"Meike"); TEST_EQUAL(tmp2.getLastName(),"Meier"); TEST_EQUAL(tmp2.getEmail(),"ich@du.de"); TEST_EQUAL(tmp2.getInstitution(),"Uni Tuebingen"); TEST_EQUAL(tmp2.getContactInfo(),"doo"); TEST_EQUAL(tmp2.getURL(),"url"); TEST_EQUAL(tmp2.getAddress(),"street"); //assignment of empty object tmp2 = ContactPerson(); TEST_EQUAL(tmp2.getMetaValue("label").isEmpty(), true); TEST_EQUAL(tmp2.getFirstName(),""); TEST_EQUAL(tmp2.getLastName(),""); TEST_EQUAL(tmp2.getEmail(),""); TEST_EQUAL(tmp2.getInstitution(),""); TEST_EQUAL(tmp2.getContactInfo(),""); TEST_EQUAL(tmp2.getURL(),""); TEST_EQUAL(tmp2.getAddress(),""); END_SECTION START_SECTION(bool operator!= (const ContactPerson& rhs) const) ContactPerson tmp,tmp2; TEST_TRUE(tmp == tmp2); tmp.setEmail("ich@du.de"); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setFirstName("Meike"); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setLastName("Meier"); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setInstitution("Uni Tuebingen"); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setContactInfo("doo"); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setURL("url"); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setAddress("street"); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setMetaValue("label",String("label")); TEST_EQUAL(tmp==tmp2, false); END_SECTION START_SECTION(bool operator== (const ContactPerson& rhs) const) ContactPerson tmp,tmp2; TEST_EQUAL(tmp!=tmp2, false); tmp.setEmail("ich@du.de"); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setFirstName("Meike"); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setLastName("Meier"); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setInstitution("Uni Tuebingen"); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setContactInfo("doo"); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setMetaValue("label",String("label")); TEST_FALSE(tmp == tmp2); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/RANSACModelQuadratic_test.cpp
.cpp
6,336
160
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: George Rosenberger $ // $Authors: George Rosenberger, Hannes Roest, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ML/RANSAC/RANSAC.h> #include <OpenMS/ML/RANSAC/RANSACModelQuadratic.h> /////////////////////////// using namespace std; using namespace OpenMS; using namespace Math; /////////////////////////// // random number generator using srand (used in std::random_shuffle()) int myRNG(int n) { return std::rand() / (1.0 + RAND_MAX) * n; } START_TEST(RANSACModelQuadratic, "$Id$") // fixed seed across all platforms srand(123); ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// RansacModelQuadratic mod; /* R code to produce the test data: A = 15 B = 1.04 C = 0.00001 ppmSD = 2 p_outlier = 0.0 quad = function(xi, withError = 1, p_outlier = p_outlier, A=A, B=B,C=C) { errPPM = rnorm(1, 0, ppmSD) errDa = errPPM / 1e6 *xi yi = A + B*xi + C*xi*xi + errDa * withError ## make it an outlier (up to x10 times off)? if (p_outlier > runif(1)) yi = yi * runif(1, 0.1, 10) ## upscaling bias, but hey... yi } x = seq(300, 1200, by = 50) y = sapply(x, quad) yperfect = sapply(x, quad, withError=0, p_outlier = 0.0, A= 15.000922133127460, B=1.0399979867717661, C=1.0000728397741021e-005) plot(x, y-yperfect) plot(x,y) paste(x, collapse=", ") paste(y, collapse=", ") */ double tx[] = {300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200}; double ty[] = {327.899691196695, 380.224568059509, 432.60001240954, 485.025329595228, 537.500950780092, 590.025780790517, 642.599328692568, 695.226226189721, 747.901404527071, 800.628123375242, 853.398402241557, 906.221690051125, 959.098650822155, 1012.02444287071, 1064.99750095039, 1118.02244136503, 1171.10218429403, 1224.22697636988, 1277.3989501643}; // with outliers double tyo[] = {327.899129765285, 380.22505352209, 3107.92239745832, 485.025787154647, 4105.48012991713, 590.022752890109, 642.600208487572, 695.225450449224, 747.90063358956, 800.627835435032, 853.39930288619, 906.221242296453, 4676.76961970711, 1012.02448829764, 1765.7626054147, 1118.02258525226, 1171.09984462503, 1224.22603819705, 1277.40083805864}; std::vector<std::pair<double, double> > test_pairs; test_pairs.reserve(19); for (int i = 0; i < 19; ++i) { test_pairs.push_back(make_pair(tx[i], ty[i])); } std::vector<std::pair<double, double> > test_pairs_o; test_pairs_o.reserve(19); for (int i = 0; i < 19; ++i) { test_pairs_o.push_back(make_pair(tx[i], tyo[i])); } START_SECTION((static ModelParameters rm_fit_impl(const DVecIt& begin, const DVecIt& end))) { RansacModel<>::ModelParameters coeff = mod.rm_fit_impl(test_pairs.begin(), test_pairs.end()); TEST_REAL_SIMILAR( coeff[0], 15.0009) // should be 15.0 TEST_REAL_SIMILAR( coeff[1], 1.04) TEST_REAL_SIMILAR( coeff[2], 0.00001) double rss = mod.rm_rss_impl(test_pairs.begin(), test_pairs.end(), coeff); TEST_REAL_SIMILAR( rss, 5.2254915523925468e-005) RansacModel<>::DVec inliers = mod.rm_inliers(test_pairs.begin(), test_pairs.end(), coeff, 0.5); TEST_EQUAL(inliers.size(), test_pairs.size()) // all should be inliers inliers = mod.rm_inliers(test_pairs_o.begin(), test_pairs_o.end(), coeff, 0.5); TEST_EQUAL( inliers.size(), 15); // 19-15 = 4 outliers // just test the gaps TEST_REAL_SIMILAR( inliers[2].first, 450.0) TEST_REAL_SIMILAR( inliers[3].first, 550.0) TEST_REAL_SIMILAR( inliers[10].first, 950.0) TEST_REAL_SIMILAR( inliers[11].first, 1050) } END_SECTION START_SECTION((static double rm_rsq_impl(const DVecIt& begin, const DVecIt& end))) NOT_TESTABLE // tested above in rm_fit_impl END_SECTION START_SECTION((static double rm_rss_impl(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients))) NOT_TESTABLE // tested above in rm_fit_impl END_SECTION START_SECTION((static DVec rm_inliers_impl(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients, double max_threshold))) NOT_TESTABLE // tested above in rm_fit_impl END_SECTION START_SECTION([EXTRA](static Math::RANSAC<Math::RANSACModelQuadratic>::ransac(const std::vector<std::pair<double, double> >& pairs, size_t n, size_t k, double t, size_t d, bool relative_d = false, int (*rng)(int) = NULL))) { // full RANSAC with outliers /*@param n The minimum number of data points required to fit the model @param k The maximum number of iterations allowed in the algorithm @param t Threshold value for determining when a data point fits a model. Corresponds to the maximal squared deviation in units of the _second_ dimension (dim2). @param d The number of close data values (according to 't') required to assert that a model fits well to data @param rng Custom RNG function (useful for testing with fixed seeds) */ RANSAC<RansacModelQuadratic> r{0}; std::vector<std::pair<double, double> > test_pairs_out = r.ransac(test_pairs_o, 5, 50, 2.0, 3, false); TEST_EQUAL( test_pairs_out.size(), 15) ABORT_IF(test_pairs_out.size() != 15) // just test the gaps std::sort(test_pairs_out.begin(), test_pairs_out.end()); TEST_REAL_SIMILAR( test_pairs_out[2].first, 450.0) TEST_REAL_SIMILAR( test_pairs_out[3].first, 550.0) TEST_REAL_SIMILAR( test_pairs_out[10].first, 950.0) TEST_REAL_SIMILAR( test_pairs_out[11].first, 1050) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IsoSpec_test.cpp
.cpp
21,669
522
// 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, Michał Startek, Mateusz Łącki $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsoSpecWrapper.h> /////////////////////////// #include <OpenMS/CHEMISTRY/Element.h> #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> using namespace OpenMS; using namespace std; // ---------------------------------------------------------------------------------------------------------------------- // Setup for tests // ---------------------------------------------------------------------------------------------------------------------- typedef Peak1D isopair; std::vector<isopair> fructose_expected_oms; // A few initial isotopologues for the fructose molecule #define ISOSPEC_TEST_EPSILON 0.0000001 // Test with more precision than TEST::isRealSimilar, without side effects, and w/o being chatty about it. bool my_real_similar(double a, double b) { return a * (1.0-ISOSPEC_TEST_EPSILON) <= b && b <= a * (1.0+ISOSPEC_TEST_EPSILON); } #define ISOSPEC_TEST_ASSERTION(b) \ if(!(b)) \ { \ std::cout << "Failing assertion in line: " << __LINE__ << std::endl; \ return false; \ } bool compare_to_reference(IsotopeDistribution& ID, const std::vector<Peak1D>& reference) { std::sort(ID.begin(), ID.end(), [](isopair a, isopair b) {return a.getIntensity() > b.getIntensity();}); for (Size i = 0; i != reference.size(); ++i) { ISOSPEC_TEST_ASSERTION(my_real_similar(ID[i].getPos(), reference[i].getPos())); ISOSPEC_TEST_ASSERTION(my_real_similar(ID[i].getIntensity(), reference[i].getIntensity())); } return true; } Size generator_length(IsoSpecGeneratorWrapper& IW) { Size i = 0; while(IW.nextConf()) i++; return i; } // With empty vector as reference this function will just run some sanity checks on the generator output // confs_to_extract == -1 will test the generator until exhaustion, >0 will just test the initial n confs. bool compare_generator_to_reference(IsoSpecGeneratorWrapper& IW, const std::vector<Peak1D>& reference, UInt32 confs_to_extract) { Size matches_count = 0; std::vector<Peak1D> isoResult; while(IW.nextConf() && confs_to_extract != 0) { Peak1D p = IW.getConf(); ISOSPEC_TEST_ASSERTION(p.getPos() == IW.getMass()); ISOSPEC_TEST_ASSERTION(p.getIntensity() == static_cast<float>(IW.getIntensity())); ISOSPEC_TEST_ASSERTION(my_real_similar(IW.getIntensity(), exp(IW.getLogIntensity()))) for(auto it = reference.begin(); it != reference.end(); it++) if(my_real_similar(it->getPos(), IW.getMass()) && my_real_similar(it->getIntensity(), IW.getIntensity())) matches_count++; confs_to_extract--; } ISOSPEC_TEST_ASSERTION(matches_count == reference.size()); return true; } START_TEST(IsoSpecWrapper, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // A few initial isotopologues for the fructose molecule fructose_expected_oms.push_back(Peak1D( 180.06339038280000863778696 , 0.92263317941561073798339976 )); fructose_expected_oms.push_back(Peak1D( 181.06674538280000774648215 , 0.059873700450778437331944559 )); fructose_expected_oms.push_back(Peak1D( 181.06760738279999145561305 , 0.0021087279716237856790062022 )); fructose_expected_oms.push_back(Peak1D( 181.06966713090000098418386 , 0.001273380225742650438680581 )); fructose_expected_oms.push_back(Peak1D( 182.06764438280001172643097 , 0.011376032168236337518973933 )); fructose_expected_oms.push_back(Peak1D( 182.07010038280000685517734 , 0.0016189442373783591386932068 )); fructose_expected_oms.push_back(Peak1D( 182.07096238279999056430825 , 0.00013684457672024180033450158 )); fructose_expected_oms.push_back(Peak1D( 182.07302213090000009287905 , 8.2635209633747614224076605e-05 )); fructose_expected_oms.push_back(Peak1D( 183.07099938280001083512616 , 0.00073824045954083467209472236 )); fructose_expected_oms.push_back(Peak1D( 183.07186138279999454425706 , 2.1667113372227351532611078e-05 )); fructose_expected_oms.push_back(Peak1D( 183.07345538280000596387254 , 2.3346748674918047107952959e-05 )); fructose_expected_oms.push_back(Peak1D( 183.07392113090000407282787 , 1.5700729969000005987024918e-05 )); fructose_expected_oms.push_back(Peak1D( 184.07189838280001481507497 , 5.8444185791655326584186775e-05 )); fructose_expected_oms.push_back(Peak1D( 184.07435438280000994382135 , 1.9961521148266482778097647e-05 )); std::sort(fructose_expected_oms.begin(), fructose_expected_oms.end(), [](isopair a, isopair b) {return a.getIntensity() > b.getIntensity();}); EmpiricalFormula ef_fructose("C6H12O6"); std::vector<int> fructose_isotopeNumbers; std::vector<int> fructose_atomCounts; std::vector<std::vector<double> > fructose_isotopeMasses; std::vector<std::vector<double> > fructose_isotopeProbabilities; for (const auto& elem : ef_fructose) { fructose_atomCounts.push_back( elem.second ); std::vector<double> masses; std::vector<double> probs; for (const auto& iso : elem.first->getIsotopeDistribution()) { if (iso.getIntensity() <= 0.0) continue; // Note: there will be an Isospec exception if one of the intensities is zero! masses.push_back(iso.getMZ()); probs.push_back(iso.getIntensity()); } fructose_isotopeNumbers.push_back( masses.size() ); fructose_isotopeMasses.push_back(masses); fructose_isotopeProbabilities.push_back(probs); } // Create an invalid molecule: where one of the isotopic intensities is defined to be zero std::vector<int> invalid_isotopeNumbers = fructose_isotopeNumbers; std::vector<int> invalid_atomCounts = fructose_atomCounts; std::vector<std::vector<double> > invalid_isotopeMasses = fructose_isotopeMasses; std::vector<std::vector<double> > invalid_isotopeProbabilities = fructose_isotopeProbabilities; invalid_isotopeNumbers[0] += 1; invalid_isotopeMasses[0].push_back(3.0160492699999998933435563); invalid_isotopeProbabilities[0].push_back(0.0); // ---------------------------------------------------------------------------------------------------------------------- // Tests: IsoSpecThresholdGeneratorWrapper // ---------------------------------------------------------------------------------------------------------------------- { IsoSpecGeneratorWrapper* ptr = nullptr; IsoSpecGeneratorWrapper* ptr2 = nullptr; IsoSpecGeneratorWrapper* nullPointer = nullptr; START_SECTION((IsoSpecThresholdGeneratorWrapper::IsoSpecThresholdGeneratorWrapper(const EmpiricalFormula&, double, bool))) ptr = new IsoSpecThresholdGeneratorWrapper(EmpiricalFormula("C10"), 0.5, false); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((IsoSpecThresholdGeneratorWrapper(std::vector<int>, std::vector<int>, std::vector<std::vector<double> >, std::vector<std::vector<double> >, double, bool))) ptr2 = new IsoSpecThresholdGeneratorWrapper(fructose_isotopeNumbers, fructose_atomCounts, fructose_isotopeMasses, fructose_isotopeProbabilities, 0.5, false); TEST_NOT_EQUAL(ptr2, nullPointer) TEST_EXCEPTION(Exception::IllegalArgument, IsoSpecThresholdGeneratorWrapper(invalid_isotopeNumbers, invalid_atomCounts, invalid_isotopeMasses, invalid_isotopeProbabilities, 0.5, false)); END_SECTION START_SECTION((IsoSpecThresholdGeneratorWrapper::~IsoSpecThresholdGeneratorWrapper())) delete ptr; delete ptr2; END_SECTION } START_SECTION(( bool IsoSpecThresholdGeneratorWrapper::nextConf() )) { double threshold = 1e-5; bool absolute = false; IsoSpecThresholdGeneratorWrapper ITW(EmpiricalFormula("C6H12O6"), threshold, absolute); TEST_EQUAL(compare_generator_to_reference(ITW, fructose_expected_oms, -1), true); IsoSpecThresholdGeneratorWrapper ITW2(EmpiricalFormula("C6H12O6"), threshold, absolute); TEST_EQUAL(generator_length(ITW2), 14); IsoSpecThresholdGeneratorWrapper ITW3(fructose_isotopeNumbers, fructose_atomCounts, fructose_isotopeMasses, fructose_isotopeProbabilities, threshold, absolute); TEST_EQUAL(compare_generator_to_reference(ITW3, fructose_expected_oms, -1), true); // human insulin IsoSpecThresholdGeneratorWrapper ITW4(EmpiricalFormula("C520H817N139O147S8"), threshold, absolute); TEST_EQUAL(generator_length(ITW4), 5513); IsoSpecThresholdGeneratorWrapper ITW5(EmpiricalFormula("C520H817N139O147S8"), 0.01, absolute); TEST_EQUAL(generator_length(ITW5), 267) } END_SECTION START_SECTION(( Peak1D IsoSpecThresholdGeneratorWrapper::getConf() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION START_SECTION(( double IsoSpecThresholdGeneratorWrapper::getMass() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION START_SECTION(( double IsoSpecThresholdGeneratorWrapper::getIntensity() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION START_SECTION(( double IsoSpecThresholdGeneratorWrapper::getLogIntensity() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION // ---------------------------------------------------------------------------------------------------------------------- // Tests: IsoSpecTotalProbGeneratorWrapper // ---------------------------------------------------------------------------------------------------------------------- { IsoSpecGeneratorWrapper* ptr = nullptr; IsoSpecGeneratorWrapper* ptr2 = nullptr; IsoSpecGeneratorWrapper* nullPointer = nullptr; START_SECTION((IsoSpecTotalProbGeneratorWrapper::IsoSpecTotalProbGeneratorWrapper(const EmpiricalFormula&, double))) ptr = new IsoSpecTotalProbGeneratorWrapper(EmpiricalFormula("C10"), 0.5); TEST_NOT_EQUAL(ptr, nullPointer); END_SECTION START_SECTION((IsoSpecTotalProbGeneratorWrapper::IsoSpecTotalProbGeneratorWrapper(std::vector<int>, std::vector<int>, std::vector<std::vector<double> >, std::vector<std::vector<double> >, double, bool))) ptr2 = new IsoSpecTotalProbGeneratorWrapper(fructose_isotopeNumbers, fructose_atomCounts, fructose_isotopeMasses, fructose_isotopeProbabilities, 0.5); TEST_NOT_EQUAL(ptr2, nullPointer); TEST_EXCEPTION(Exception::IllegalArgument, IsoSpecTotalProbGeneratorWrapper(invalid_isotopeNumbers, invalid_atomCounts, invalid_isotopeMasses, invalid_isotopeProbabilities, 0.5)); END_SECTION START_SECTION((IsoSpecTotalProbGeneratorWrapper::~IsoSpecTotalProbGeneratorWrapper())) delete ptr; delete ptr2; END_SECTION } START_SECTION(( bool IsoSpecTotalProbGeneratorWrapper::nextConf() )) { double total_prob = 0.99999; IsoSpecTotalProbGeneratorWrapper ITPW(EmpiricalFormula("C6H12O6"), total_prob); TEST_EQUAL(compare_generator_to_reference(ITPW, fructose_expected_oms, -1), true); IsoSpecTotalProbGeneratorWrapper ITPW2(EmpiricalFormula("C6H12O6"), total_prob); TEST_EQUAL(generator_length(ITPW2), 2548); // Total prob is a hint, if we keep extracting configurations // we will go over the entire configuration space IsoSpecTotalProbGeneratorWrapper ITPW3(fructose_isotopeNumbers, fructose_atomCounts, fructose_isotopeMasses, fructose_isotopeProbabilities, total_prob); TEST_EQUAL(compare_generator_to_reference(ITPW3, fructose_expected_oms, -1), true); } END_SECTION START_SECTION(( Peak1D IsoSpecTotalProbGeneratorWrapper::getConf() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION START_SECTION(( double IsoSpecTotalProbGeneratorWrapper::getMass() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION START_SECTION(( double IsoSpecTotalProbGeneratorWrapper::getIntensity() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION START_SECTION(( double IsoSpecTotalProbGeneratorWrapper::getLogIntensity() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION // ---------------------------------------------------------------------------------------------------------------------- { IsoSpecGeneratorWrapper* ptr = nullptr; IsoSpecGeneratorWrapper* ptr2 = nullptr; IsoSpecGeneratorWrapper* nullPointer = nullptr; START_SECTION((IsoSpecOrderedGeneratorWrapper::IsoSpecOrderedGeneratorWrapper(const EmpiricalFormula&))) ptr = new IsoSpecOrderedGeneratorWrapper(EmpiricalFormula("C10")); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((IsoSpecOrderedGeneratorWrapper::IsoSpecOrderedGeneratorWrapper(std::vector<int>, std::vector<int>, std::vector<std::vector<double> >, std::vector<std::vector<double> >))) ptr2 = new IsoSpecOrderedGeneratorWrapper(fructose_isotopeNumbers, fructose_atomCounts, fructose_isotopeMasses, fructose_isotopeProbabilities); TEST_NOT_EQUAL(ptr2, nullPointer); TEST_EXCEPTION(Exception::IllegalArgument, IsoSpecOrderedGeneratorWrapper(invalid_isotopeNumbers, invalid_atomCounts, invalid_isotopeMasses, invalid_isotopeProbabilities)); END_SECTION START_SECTION((~IsoSpecOrderedGeneratorWrapper())) delete ptr; delete ptr2; END_SECTION } START_SECTION(( bool IsoSpecOrderedGeneratorWrapper::nextConf() )) { IsoSpecOrderedGeneratorWrapper IOGW(EmpiricalFormula("C6H12O6")); TEST_EQUAL(compare_generator_to_reference(IOGW, fructose_expected_oms, fructose_expected_oms.size()), true); IsoSpecOrderedGeneratorWrapper IOGW2(EmpiricalFormula("C6H12O6")); TEST_EQUAL(generator_length(IOGW2), 2548); IsoSpecOrderedGeneratorWrapper IOGW3(fructose_isotopeNumbers, fructose_atomCounts, fructose_isotopeMasses, fructose_isotopeProbabilities); TEST_EQUAL(compare_generator_to_reference(IOGW3, fructose_expected_oms, -1), true); // human insulin IsoSpecOrderedGeneratorWrapper IOGW4(EmpiricalFormula("C520H817N139O147S8")); TEST_EQUAL(compare_generator_to_reference(IOGW4, std::vector<Peak1D>(), 10000), true); } END_SECTION START_SECTION(( Peak1D IsoSpecOrderedGeneratorWrapper::getConf() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION START_SECTION(( double IsoSpecOrderedGeneratorWrapper::getMass() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION START_SECTION(( double IsoSpecOrderedGeneratorWrapper::getIntensity() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION START_SECTION(( double IsoSpecOrderedGeneratorWrapper::getLogIntensity() )) NOT_TESTABLE; // Tested with nextConf(), above END_SECTION // ---------------------------------------------------------------------------------------------------------------------- // Tests: IsoSpecThresholdWrapper // ---------------------------------------------------------------------------------------------------------------------- { IsoSpecWrapper* ptr = nullptr; IsoSpecWrapper* ptr2 = nullptr; IsoSpecWrapper* nullPointer = nullptr; START_SECTION((IsoSpecThresholdWrapper::IsoSpecThresholdWrapper(const EmpiricalFormula&, double, bool))) ptr = new IsoSpecThresholdWrapper(EmpiricalFormula("C10"), 0.5, false); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((IsoSpecThresholdWrapper(std::vector<int>, std::vector<int>, std::vector<std::vector<double> >, std::vector<std::vector<double> >, double, bool))) ptr2 = new IsoSpecThresholdWrapper(fructose_isotopeNumbers, fructose_atomCounts, fructose_isotopeMasses, fructose_isotopeProbabilities, 0.5, false); TEST_NOT_EQUAL(ptr2, nullPointer) TEST_EXCEPTION(Exception::IllegalArgument, IsoSpecThresholdWrapper(invalid_isotopeNumbers, invalid_atomCounts, invalid_isotopeMasses, invalid_isotopeProbabilities, 0.5, false)); END_SECTION START_SECTION((IsoSpecThresholdWrapper::~IsoSpecThresholdWrapper())) delete ptr; delete ptr2; END_SECTION } START_SECTION(( void IsoSpecThresholdWrapper::run() )) { { double threshold = 1e-5; bool absolute = false; IsotopeDistribution iso_result(IsoSpecThresholdWrapper(EmpiricalFormula("C6H12O6"), threshold, absolute).run()); TEST_EQUAL(iso_result.size(), 14); TEST_EQUAL(compare_to_reference(iso_result, fructose_expected_oms), true); IsotopeDistribution iso_expl(IsoSpecThresholdWrapper(fructose_isotopeNumbers, fructose_atomCounts, fructose_isotopeMasses, fructose_isotopeProbabilities, threshold, absolute).run()); TEST_EQUAL(iso_expl.size(), 14); TEST_EQUAL(compare_to_reference(iso_expl, fructose_expected_oms), true); // human insulin IsotopeDistribution iso_result2 = IsoSpecThresholdWrapper(EmpiricalFormula("C520H817N139O147S8"), threshold, absolute).run(); TEST_EQUAL(iso_result2.size(), 5513) IsotopeDistribution iso_result3 = IsoSpecThresholdWrapper(EmpiricalFormula("C520H817N139O147S8"), 0.01, absolute).run(); TEST_EQUAL(iso_result3.size(), 267) } { double threshold = 1e-5; bool absolute = true; IsotopeDistribution iso_result(IsoSpecThresholdWrapper(EmpiricalFormula("C6H12O6"), threshold, absolute).run()); TEST_EQUAL(iso_result.size(), 14) TEST_EQUAL(compare_to_reference(iso_result, fructose_expected_oms), true); // human insulin IsotopeDistribution iso_result2(IsoSpecThresholdWrapper(EmpiricalFormula("C520H817N139O147S8"), threshold, absolute).run()); TEST_EQUAL(iso_result2.size(), 1734) IsotopeDistribution iso_result3(IsoSpecThresholdWrapper(EmpiricalFormula("C520H817N139O147S8"), 0.01, absolute).run()); TEST_EQUAL(iso_result3.size(), 21) } } END_SECTION // ---------------------------------------------------------------------------------------------------------------------- // Tests: IsoSpecTotalProbWrapper // ---------------------------------------------------------------------------------------------------------------------- { IsoSpecWrapper* ptr = nullptr; IsoSpecWrapper* ptr2 = nullptr; IsoSpecWrapper* nullPointer = nullptr; START_SECTION((IsoSpecTotalProbWrapper::IsoSpecTotalProbWrapper(const EmpiricalFormula&, double, bool))) ptr = new IsoSpecTotalProbWrapper(EmpiricalFormula("C10"), 0.5, true); TEST_NOT_EQUAL(ptr, nullPointer); END_SECTION START_SECTION((IsoSpecTotalProbWrapper::IsoSpecTotalProbWrapper(std::vector<int>, std::vector<int>, std::vector<std::vector<double> >, std::vector<std::vector<double> >, double, bool))) ptr2 = new IsoSpecTotalProbWrapper(fructose_isotopeNumbers, fructose_atomCounts, fructose_isotopeMasses, fructose_isotopeProbabilities, 0.5, false); TEST_NOT_EQUAL(ptr2, nullPointer); TEST_EXCEPTION(Exception::IllegalArgument, IsoSpecTotalProbWrapper(invalid_isotopeNumbers, invalid_atomCounts, invalid_isotopeMasses, invalid_isotopeProbabilities, 0.5, false)); END_SECTION START_SECTION((IsoSpecTotalProbWrapper::~IsoSpecTotalProbWrapper())) delete ptr; delete ptr2; END_SECTION } START_SECTION(( void IsoSpecTotalProbWrapper::run() )) { double total_prob = 0.99999; bool do_trim = true; // With do_trim == false the size of results is actually undefined, and may change as the underlying // non-trimming heuristic changes IsotopeDistribution iso_result(IsoSpecTotalProbWrapper(EmpiricalFormula("C6H12O6"), total_prob, do_trim).run()); TEST_EQUAL(iso_result.size(), 17); TEST_EQUAL(compare_to_reference(iso_result, fructose_expected_oms), true); IsotopeDistribution iso_result2(IsoSpecTotalProbWrapper(fructose_isotopeNumbers, fructose_atomCounts, fructose_isotopeMasses, fructose_isotopeProbabilities, total_prob, do_trim).run()); TEST_EQUAL(iso_result2.size(), 17); TEST_EQUAL(compare_to_reference(iso_result2, fructose_expected_oms), true); // human insulin IsotopeDistribution iso_result3 = IsoSpecTotalProbWrapper(EmpiricalFormula("C520H817N139O147S8"), total_prob, do_trim).run(); TEST_EQUAL(iso_result3.size(), 19615); IsotopeDistribution iso_result4 = IsoSpecTotalProbWrapper(EmpiricalFormula("C520H817N139O147S8"), 0.99, do_trim).run(); TEST_EQUAL(iso_result4.size(), 1756); } END_SECTION #if 0 START_SECTION(( [STRESSTEST] void run(const std::string&) )) { // Do some stress testing of the library... // this is close to the performance of IsoSpec by itself int sum = 0; for (Size k = 0; k < 2e5; k++) { double threshold = 1e-2; bool absolute = false; IsoSpecThresholdWrapper iso("C520H817N139O147", threshold, absolute); auto res = iso.run(); sum += res.size(); } TEST_EQUAL(sum, 140*2*1e5) } END_SECTION #endif ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TransformationDescription_test.cpp
.cpp
12,726
398
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Hendrik Weisser $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h> #include <OpenMS/CONCEPT/LogStream.h> #include <vector> #include <sstream> /////////////////////////// START_TEST(TransformationDescription, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; TransformationDescription* ptr = nullptr; TransformationDescription* nullPointer = nullptr; START_SECTION((TransformationDescription())) ptr = new TransformationDescription; TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~TransformationDescription())) delete ptr; END_SECTION TransformationDescription::DataPoints data; data.push_back(make_pair(0.0, 1.0)); data.push_back(make_pair(0.25, 1.5)); data.push_back(make_pair(0.5, 2.0)); data.push_back(make_pair(1.0, 3.0)); TransformationDescription::DataPoints data_nonlinear; data_nonlinear.push_back(make_pair(0.0, 1.0)); data_nonlinear.push_back(make_pair(0.25, 1.0625)); data_nonlinear.push_back(make_pair(0.5, 1.25)); data_nonlinear.push_back(make_pair(1.0, 2.0)); START_SECTION((TransformationDescription(const DataPoints& data))) { ptr = new TransformationDescription(data); TEST_NOT_EQUAL(ptr, nullPointer) TEST_EQUAL(ptr->getDataPoints() == data, true); delete ptr; } END_SECTION START_SECTION((const DataPoints& getDataPoints() const)) { TransformationDescription td; TEST_EQUAL(td.getDataPoints().empty(), true); } END_SECTION START_SECTION((void setDataPoints(const DataPoints& data))) { TransformationDescription td; td.fitModel("identity", Param()); TEST_EQUAL(td.getModelType(), "identity"); td.setDataPoints(data); // setting data points clears the model: TEST_EQUAL(td.getModelType(), "none"); TEST_EQUAL(td.getDataPoints().size(), 4) TEST_EQUAL(td.getDataPoints() == data, true); TransformationDescription::DataPoints empty; empty.clear(); td.setDataPoints(empty); TEST_EQUAL(td.getDataPoints().empty(), true); } END_SECTION START_SECTION((void setDataPoints(const vector<pair<double, double> >& data))) { TransformationDescription td; td.fitModel("identity", Param()); TEST_EQUAL(td.getModelType(), "identity"); vector<pair<double, double> > pairs; pairs.push_back(make_pair(0.0, 1.0)); pairs.push_back(make_pair(0.25, 1.5)); pairs.push_back(make_pair(0.5, 2.0)); pairs.push_back(make_pair(1.0, 3.0)); td.setDataPoints(pairs); // setting data points clears the model: TEST_EQUAL(td.getModelType(), "none"); TEST_EQUAL(td.getDataPoints().size(), 4) TEST_EQUAL(td.getDataPoints() == data, true); pairs.clear(); td.setDataPoints(pairs); TEST_EQUAL(td.getDataPoints().empty(), true); } END_SECTION START_SECTION((double apply(double value) const)) { TransformationDescription td; TEST_EQUAL(td.apply(-0.5), -0.5); TEST_EQUAL(td.apply(1000), 1000); // tested further together with "fitModel" } END_SECTION START_SECTION((const String& getModelType() const)) { TransformationDescription td; TEST_EQUAL(td.getModelType(), "none"); } END_SECTION START_SECTION((static void getModelTypes(StringList& result))) { StringList result; TransformationDescription::getModelTypes(result); TEST_EQUAL(result.size(), 4); TEST_EQUAL(result.at(0), "linear"); TEST_EQUAL(result.at(1), "b_spline"); TEST_EQUAL(result.at(2), "interpolated"); TEST_EQUAL(result.at(3), "lowess"); } END_SECTION START_SECTION((void fitModel(const String& model_type, const Param& params=Param()))) { TransformationDescription td(data); Param params; td.fitModel("linear", params); TEST_EQUAL(td.getModelType(), "linear"); TEST_REAL_SIMILAR(td.apply(0.0), 1.0); TEST_REAL_SIMILAR(td.apply(0.5), 2.0); TEST_REAL_SIMILAR(td.apply(1.0), 3.0); // non-linear model (b spline) td.fitModel("b_spline", params); TEST_EQUAL(td.getModelType(), "b_spline"); TEST_REAL_SIMILAR(td.apply(0.0), 1.064201730); TEST_REAL_SIMILAR(td.apply(0.5), 1.957836652); TEST_REAL_SIMILAR(td.apply(1.0), 2.927541901); // non-linear model (lowess) td.fitModel("lowess", params); TEST_EQUAL(td.getModelType(), "lowess"); TEST_REAL_SIMILAR(td.apply(0.0), 1.0); TEST_REAL_SIMILAR(td.apply(0.5), 2.0); TEST_REAL_SIMILAR(td.apply(1.0), 3.0); // special model type for reference files: td.fitModel("identity", Param()); TEST_EQUAL(td.getModelType(), "identity"); TEST_REAL_SIMILAR(td.apply(0.0), 0.0); TEST_REAL_SIMILAR(td.apply(0.5), 0.5); TEST_REAL_SIMILAR(td.apply(1.0), 1.0); // can't fit a different model to an "identity" transformation: td.fitModel("linear", params); TEST_EQUAL(td.getModelType(), "identity"); { // non-linear model (b spline) TransformationDescription td_nl(data_nonlinear); td_nl.fitModel("b_spline", params); TEST_EQUAL(td_nl.getModelType(), "b_spline"); TEST_REAL_SIMILAR(td_nl.apply(0.0), 1.01084556836969); TEST_REAL_SIMILAR(td_nl.apply(0.5), 1.26289804387079); TEST_REAL_SIMILAR(td_nl.apply(0.75), 1.53463130131214); TEST_REAL_SIMILAR(td_nl.apply(1.0), 1.94984504419826); // non-linear model (lowess) td_nl.fitModel("lowess", params); TEST_EQUAL(td_nl.getModelType(), "lowess"); TEST_REAL_SIMILAR(td_nl.apply(0.0), 1.0); TEST_REAL_SIMILAR(td_nl.apply(0.5), 1.25); TEST_REAL_SIMILAR(td_nl.apply(0.75), 1.58423913043478); TEST_REAL_SIMILAR(td_nl.apply(1.0), 2.0); } } END_SECTION START_SECTION(([EXTRA]void fitModel(const String& model_type, const Param& params=Param()))) { // Check whether we can change the parameters and get different behavior TransformationDescription td(data); Param params; // for lowess params.setValue("interpolation_type", "linear"); // for b spline params.setValue("extrapolate", "b_spline"); // non-linear model (b spline) TransformationDescription td_nl(data_nonlinear); td_nl.fitModel("b_spline", params); TEST_EQUAL(td_nl.getModelType(), "b_spline"); TEST_REAL_SIMILAR(td_nl.apply(0.0), 1.01084556836969); TEST_REAL_SIMILAR(td_nl.apply(0.5), 1.26289804387079); TEST_REAL_SIMILAR(td_nl.apply(0.75), 1.53463130131214); TEST_REAL_SIMILAR(td_nl.apply(1.0), 1.94984504419826); TEST_REAL_SIMILAR(td_nl.apply(2.0), 1.328125); // b-spline extrapolation // non-linear model (lowess) td_nl.fitModel("lowess", params); TEST_EQUAL(td_nl.getModelType(), "lowess"); TEST_REAL_SIMILAR(td_nl.apply(0.0), 1.0); TEST_REAL_SIMILAR(td_nl.apply(0.5), 1.25); TEST_REAL_SIMILAR(td_nl.apply(0.75), 1.625); // linear interpolation between points TEST_REAL_SIMILAR(td_nl.apply(1.0), 2.0); TEST_REAL_SIMILAR(td_nl.apply(2.0), 3.5); } END_SECTION START_SECTION((void getModelParameters(Param& params) const)) { TransformationDescription td; Param params = td.getModelParameters(); TEST_EQUAL(params, Param()); params.setValue("slope", 2.5); params.setValue("intercept", -100.0); params.setValue("x_weight", "x"); params.setValue("y_weight", "y"); params.setValue("x_datum_min", 1e-15); params.setValue("y_datum_min", 1e-15); params.setValue("x_datum_max", 1e15); params.setValue("y_datum_max", 1e15); const Param const_params = params; td.fitModel("linear", const_params); params = td.getModelParameters(); TEST_EQUAL(params, const_params); } END_SECTION START_SECTION((TransformationDescription(const TransformationDescription& rhs))) { TransformationDescription td(data); td.fitModel("linear", Param()); TransformationDescription td2 = td; TEST_EQUAL(td.getModelType(), td2.getModelType()); TEST_EQUAL(td.getDataPoints() == td2.getDataPoints(), true); Param params = td.getModelParameters(); Param params2 = td2.getModelParameters(); TEST_EQUAL(params, params2); } END_SECTION START_SECTION((TransformationDescription& operator=(const TransformationDescription& rhs))) { TransformationDescription td(data); td.fitModel("linear", Param()); TransformationDescription td2; td2 = td; TEST_EQUAL(td.getModelType(), td2.getModelType()); TEST_EQUAL(td.getDataPoints() == td2.getDataPoints(), true); Param params = td.getModelParameters(); Param params2 = td2.getModelParameters(); TEST_EQUAL(params, params2); } END_SECTION START_SECTION((void invert())) { // test null transformation: TransformationDescription td; td.fitModel("none", Param()); td.invert(); TEST_EQUAL(td.getModelType(), "none"); // test inversion of data points: TransformationDescription td1; td1.setDataPoints(data); td1.invert(); td1.invert(); TEST_EQUAL(td1.getDataPoints() == data, true); // test linear transformation: TransformationDescription td2; td2.setDataPoints(data); Param params2; params2.setValue("slope", 2.0); params2.setValue("intercept", 47.12); td2.fitModel("linear", params2); TEST_REAL_SIMILAR(params2.getValue("slope"), 2.0); TEST_REAL_SIMILAR(params2.getValue("intercept"), 47.12); TransformationDescription td3; td3.setDataPoints(data); Param params3; td3.fitModel("linear", params3); td3.invert(); TEST_EQUAL(td3.getModelType(), "linear"); TEST_REAL_SIMILAR(td3.apply(1.0), 0.0);//control input values TEST_REAL_SIMILAR(td3.apply(2.0), 0.5);//control input values TEST_REAL_SIMILAR(td3.apply(3.0), 1.0);//control input values TEST_REAL_SIMILAR(td3.apply(4.0), 1.5);//control interpolation values TEST_REAL_SIMILAR(td3.apply(5.0), 2.0);//control interpolation values // test interpolated-linear transformation: TransformationDescription td4; td4.setDataPoints(data); Param params4; params4.setValue("interpolation_type", "cspline"); td4.fitModel("interpolated", params4); td4.invert(); TEST_EQUAL(td4.getModelType(), "interpolated"); // pairs have changed... TEST_EQUAL(td4.getDataPoints() != data, true); td4.invert(); // ... now they're back to the original: TEST_EQUAL(td4.getDataPoints() == data, true); } END_SECTION START_SECTION((void getDeviations(std::vector<double>& diffs, bool do_apply = false, bool do_sort = true) const)) { vector<double> diffs; TransformationDescription td(data_nonlinear); td.fitModel("linear"); td.getDeviations(diffs); TEST_EQUAL(diffs.size(), 4); TEST_REAL_SIMILAR(diffs[0], 0.75); TEST_REAL_SIMILAR(diffs[1], 0.8125); TEST_REAL_SIMILAR(diffs[2], 1.0); TEST_REAL_SIMILAR(diffs[3], 1.0); td.getDeviations(diffs, true, false); TEST_EQUAL(diffs.size(), 4); TEST_REAL_SIMILAR(diffs[0], 0.125); TEST_REAL_SIMILAR(diffs[1], 0.0714286); TEST_REAL_SIMILAR(diffs[2], 0.142857); TEST_REAL_SIMILAR(diffs[3], 0.0892857); } END_SECTION START_SECTION((void printSummary(std::ostream& os) const)) { stringstream ss; TransformationDescription td(data_nonlinear); td.printSummary(ss); string expected = "Number of data points (x/y pairs): 4\n" "Data range (x): 0 to 1\n" "Data range (y): 1 to 2\n" "Summary of x/y deviations:\n" "- 100% of data points within (+/-)1\n" "- 99% of data points within (+/-)1\n" "- 95% of data points within (+/-)1\n" "- 90% of data points within (+/-)1\n" "- 75% of data points within (+/-)1\n" "- 50% of data points within (+/-)0.8125\n" "- 25% of data points within (+/-)0.75\n\n"; TEST_STRING_EQUAL(ss.str(), expected); ss.str(""); td.fitModel("linear"); td.printSummary(ss); expected = "Number of data points (x/y pairs): 4\n" "Data range (x): 0 to 1\n" "Data range (y): 1 to 2\n" "Summary of x/y deviations before transformation:\n" "- 100% of data points within (+/-)1\n" "- 99% of data points within (+/-)1\n" "- 95% of data points within (+/-)1\n" "- 90% of data points within (+/-)1\n" "- 75% of data points within (+/-)1\n" "- 50% of data points within (+/-)0.8125\n" "- 25% of data points within (+/-)0.75\n" "Summary of x/y deviations after applying 'linear' transformation:\n" "- 100% of data points within (+/-)0.142857\n" "- 99% of data points within (+/-)0.125\n" "- 95% of data points within (+/-)0.125\n" "- 90% of data points within (+/-)0.125\n" "- 75% of data points within (+/-)0.125\n" "- 50% of data points within (+/-)0.0892857\n" "- 25% of data points within (+/-)0.0714286\n\n"; TEST_STRING_EQUAL(ss.str(), expected); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/JavaInfo_test.cpp
.cpp
1,018
34
// 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/DATASTRUCTURES/String.h> #include <OpenMS/SYSTEM/JavaInfo.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(TextFile, "$Id$") ///////////////////////////////////////////////////////////// START_SECTION((static bool canRun(const String &file))) // test for missing java executable TEST_EQUAL(JavaInfo::canRun(""), false) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MRMFeaturePicker_test.cpp
.cpp
1,162
42
// 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/ANALYSIS/OPENSWATH/MRMFeaturePicker.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MRMFeaturePicker, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MRMFeaturePicker* ptr = nullptr; MRMFeaturePicker* null_ptr = nullptr; START_SECTION(MRMFeaturePicker()) { ptr = new MRMFeaturePicker(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~MRMFeaturePicker()) { delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/EmpiricalFormula_test.cpp
.cpp
25,790
665
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow, Ahmed Khalil $ // $Authors: Andreas Bertsch, Chris Bielow $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> /////////////////////////// #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h> #include <OpenMS/CHEMISTRY/Element.h> #include <OpenMS/CHEMISTRY/ElementDB.h> #include <OpenMS/CONCEPT/Constants.h> #include <sstream> #include <map> #include <unordered_set> #include <functional> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(ElementDB, "$Id$") ///////////////////////////////////////////////////////////// EmpiricalFormula* e_ptr = nullptr; EmpiricalFormula* e_nullPointer = nullptr; const ElementDB* db = ElementDB::getInstance(); EmpiricalFormula ef_empty; START_SECTION(EmpiricalFormula()) e_ptr = new EmpiricalFormula; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION(~EmpiricalFormula()) delete e_ptr; END_SECTION START_SECTION(EmpiricalFormula(const String& rhs)) // adding spaces and tabs to test sanitizeIfNotValidFormula. // test succeeds when sanitizeIfNotValidFormula has removed // all spaces, tabs and newlines from the provided formula e_ptr = new EmpiricalFormula("C4 "); TEST_NOT_EQUAL(e_ptr, e_nullPointer) // test isotopes (Carbon 13) EmpiricalFormula e0("C5(13)C4H2 "); EmpiricalFormula e1("C5(13)C4\n\n "); EmpiricalFormula e2("(12)C5(13)C4\t\n "); EmpiricalFormula e3("C9 "); TEST_REAL_SIMILAR(e1.getMonoWeight(), e2.getMonoWeight()) TEST_REAL_SIMILAR(e1.getMonoWeight(), 112.013419) TEST_REAL_SIMILAR(e2.getMonoWeight(), 112.013419) END_SECTION START_SECTION(EmpiricalFormula(const EmpiricalFormula& rhs)) EmpiricalFormula ef(*e_ptr); TEST_EQUAL(ef == *e_ptr, true) END_SECTION START_SECTION(EmpiricalFormula(EmpiricalFormula&&) = default) EmpiricalFormula e = EmpiricalFormula("C4"); EmpiricalFormula ef(e); EmpiricalFormula ef2(e); TEST_NOT_EQUAL(ef, ef_empty) // the move target should be equal, while the move source should be empty EmpiricalFormula ef_mv(std::move(ef)); TEST_EQUAL(ef_mv, ef2) TEST_EQUAL(ef, ef_empty) END_SECTION START_SECTION((EmpiricalFormula(SignedSize number, const Element* element, SignedSize charge=0))) EmpiricalFormula ef(4, db->getElement("C")); TEST_EQUAL(ef == *e_ptr, true) TEST_EQUAL(ef.getCharge(), 0) END_SECTION START_SECTION(const Element* getElement(UInt rounded_mass) const) const Element* e = db->getElement(6); TEST_EQUAL(e->getSymbol(), "C") END_SECTION START_SECTION(const Element* getElement(const String& name) const) const Element* e = db->getElement("C"); TEST_EQUAL(e->getSymbol(), "C") END_SECTION START_SECTION(SignedSize getNumberOf(const Element* element) const) Size num1 = e_ptr->getNumberOf(db->getElement(6)); TEST_EQUAL(num1, 4); Size num2 = e_ptr->getNumberOf(db->getElement("C")); TEST_EQUAL(num2, 4); END_SECTION START_SECTION(SignedSize getNumberOfAtoms() const) Size num4 = e_ptr->getNumberOfAtoms(); TEST_EQUAL(num4, 4); END_SECTION START_SECTION(EmpiricalFormula& operator<(const EmpiricalFormula& rhs)) // operator< compares pointers so this only works for same elements TEST_EQUAL(EmpiricalFormula("C5H2") < EmpiricalFormula("C6H2"), true) TEST_EQUAL(EmpiricalFormula("C5H2") < EmpiricalFormula("C5H3"), true) TEST_EQUAL(EmpiricalFormula("C5") < EmpiricalFormula("C5H2"), true) TEST_EQUAL(EmpiricalFormula("C5H2") < EmpiricalFormula("C4H2"), false) TEST_EQUAL(EmpiricalFormula("C5") < EmpiricalFormula("C5"), false) END_SECTION START_SECTION(EmpiricalFormula& operator=(const EmpiricalFormula& rhs)) EmpiricalFormula ef; ef = *e_ptr; TEST_EQUAL(*e_ptr == ef, true) END_SECTION START_SECTION(EmpiricalFormula& operator=(EmpiricalFormula&&) & = default) EmpiricalFormula e = EmpiricalFormula("C4"); EmpiricalFormula ef(e); EmpiricalFormula ef2(e); TEST_NOT_EQUAL(ef, ef_empty) // the move target should be equal, while the move source should be empty EmpiricalFormula ef_mv; ef_mv = std::move(ef); TEST_EQUAL(ef_mv, ef2) TEST_EQUAL(ef, ef_empty) END_SECTION START_SECTION(EmpiricalFormula operator*(const SignedSize& times) const) EmpiricalFormula ef("C3H8"); ef = ef * 3; TEST_EQUAL(ef, "C9H24") END_SECTION START_SECTION(EmpiricalFormula& operator+=(const EmpiricalFormula& rhs)) EmpiricalFormula ef("C3"); TEST_EQUAL(ef, "C3") ef += ef; TEST_EQUAL(ef, "C6") EmpiricalFormula ef2("C-6H2"); ef += ef2; TEST_EQUAL(ef, "H2"); ef = EmpiricalFormula("C"); TEST_EQUAL(ef, "C") ef += EmpiricalFormula("C5"); TEST_EQUAL(ef, "C6") ef += EmpiricalFormula("C-5"); TEST_EQUAL(ef, "C") ef += EmpiricalFormula("C-1H2"); TEST_EQUAL(ef, "H2") END_SECTION START_SECTION(EmpiricalFormula operator+(const EmpiricalFormula& rhs) const) EmpiricalFormula ef("C2"); EmpiricalFormula ef2; ef2 = ef + ef; TEST_EQUAL(ef2, "C4") ef2 = ef2 + EmpiricalFormula("C-4H2"); TEST_EQUAL(ef2, "H2") END_SECTION START_SECTION(EmpiricalFormula& operator-=(const EmpiricalFormula& rhs)) EmpiricalFormula ef1("C5H12"), ef2("CH12"); ef1 -= ef2; TEST_EQUAL(*e_ptr == ef1, true) ef1 -= EmpiricalFormula("C4H-2"); TEST_EQUAL(ef1, "H2"); END_SECTION START_SECTION(EmpiricalFormula operator-(const EmpiricalFormula& rhs) const) EmpiricalFormula ef1("C5H12"), ef2("CH12"); EmpiricalFormula ef3, ef4; ef3 = ef1 - ef2; cerr << *e_ptr << " " << ef3 << endl; TEST_EQUAL(*e_ptr == ef3, true) ef3 = ef3 - EmpiricalFormula("C4H-2"); TEST_EQUAL(ef3, "H2"); END_SECTION START_SECTION(bool isEmpty() const) EmpiricalFormula ef; TEST_EQUAL(ef.isEmpty(), true) TEST_EQUAL(e_ptr->isEmpty(), false) END_SECTION START_SECTION(bool hasElement(const Element* element) const) const Element* e = db->getElement(6); TEST_EQUAL(e_ptr->hasElement(e), true) e = db->getElement(1); TEST_EQUAL(e_ptr->hasElement(e), false) END_SECTION START_SECTION(bool contains(const EmpiricalFormula& ef)) EmpiricalFormula metabolite("C12H36N2"); TEST_EQUAL(metabolite.contains(metabolite), true) // contains itself? TEST_EQUAL(metabolite.contains(EmpiricalFormula("C-12H36N2")), true) TEST_EQUAL(metabolite.contains(EmpiricalFormula("C11H36N2")), true) TEST_EQUAL(metabolite.contains(EmpiricalFormula("N2")), true) TEST_EQUAL(metabolite.contains(EmpiricalFormula("H36")), true) TEST_EQUAL(metabolite.contains(EmpiricalFormula("H3")), true) TEST_EQUAL(metabolite.contains(EmpiricalFormula("P-1")), true) TEST_EQUAL(metabolite.contains(EmpiricalFormula()), true) TEST_EQUAL(metabolite.contains(EmpiricalFormula("P1")), false) // the 'adduct' test TEST_EQUAL(metabolite.contains(EmpiricalFormula("KH-2") * -1), true) // make sure we can loose 2H (i.e. we have 2H in the metabolite); K is adducted, so is does not need to be intrinsic TEST_EQUAL(metabolite.contains(EmpiricalFormula("K-1H2")), true) // same as above TEST_EQUAL(metabolite.contains(EmpiricalFormula("KH-2") * 1), false) // cannot loose K, since we don't have it END_SECTION START_SECTION(void setCharge(SignedSize charge)) e_ptr->setCharge(1); NOT_TESTABLE // will be tested in next check END_SECTION START_SECTION(SignedSize getCharge() const) TEST_EQUAL(e_ptr->getCharge(), 1) EmpiricalFormula ef1("C2+"); TEST_EQUAL(ef1.getCharge(), 1) EmpiricalFormula ef2("C2+3"); TEST_EQUAL(ef2.getCharge(), 3) END_SECTION START_SECTION(bool isCharged() const) TEST_EQUAL(e_ptr->isCharged(), true) e_ptr->setCharge(0); TEST_EQUAL(e_ptr->isCharged(), false) END_SECTION START_SECTION(double getAverageWeight() const) EmpiricalFormula ef("C2"); const Element* e = db->getElement("C"); TEST_REAL_SIMILAR(ef.getAverageWeight(), e->getAverageWeight() * 2) ef.setCharge(1); TEST_REAL_SIMILAR(ef.getAverageWeight(), e->getAverageWeight() * 2 + Constants::PROTON_MASS_U) ef.setCharge(-1); TEST_REAL_SIMILAR(ef.getAverageWeight(), e->getAverageWeight() * 2 - Constants::PROTON_MASS_U) END_SECTION START_SECTION(bool estimateFromWeightAndComp(double average_weight, double C, double H, double N, double O, double S, double P)) // Same stoichiometry as the averagine model EmpiricalFormula ef("C494H776N136O148S4"); EmpiricalFormula ef_approx; Int return_flag; return_flag = ef_approx.estimateFromWeightAndComp(ef.getAverageWeight(), 4.9384, 7.7583, 1.3577, 1.4773, 0.0417, 0); // average mass should be the same when using the same stoichiometry TOLERANCE_ABSOLUTE(1); TEST_REAL_SIMILAR(ef.getAverageWeight(), ef_approx.getAverageWeight()); // # of elements should be the same when using the same stoichiometry for (EmpiricalFormula::ConstIterator itr = ef.begin(); itr != ef.end(); ++itr) { TEST_EQUAL(itr->second, ef_approx.getNumberOf(itr->first)); } TEST_EQUAL(return_flag, true); // Very different stoichiometry than the averagine model EmpiricalFormula ef2("C100H100N100O100S100P100"); return_flag = ef_approx.estimateFromWeightAndComp(ef2.getAverageWeight(), 4.9384, 7.7583, 1.3577, 1.4773, 0.0417, 0); // average mass should be the same when using a different stoichiometry TEST_REAL_SIMILAR(ef2.getAverageWeight(), ef_approx.getAverageWeight()); // # of elements should be different when using a very different stoichiometry for (EmpiricalFormula::ConstIterator itr = ef2.begin(); itr != ef2.end(); ++itr) { TEST_NOT_EQUAL(itr->second, ef_approx.getNumberOf(itr->first)); } TEST_EQUAL(return_flag, true); // Small mass that the model can't fit without using a negative # of hydrogens return_flag = ef_approx.estimateFromWeightAndComp(50, 4.9384, 7.7583, 1.3577, 1.4773, 0.0417, 0); // The same mass can't be achieved because the # hydrogens needed to compensate is negative TEST_EQUAL(ef_approx.getAverageWeight() - 50 > 1, true); // Don't allow the EmpiricalFormula to have a negative # of hydrogens TEST_EQUAL(ef_approx.getNumberOf(db->getElement("H")) >= 0, true); // The return flag should now indicate that the estimated formula did not succeed without requesting a negative # of hydrogens TEST_EQUAL(return_flag, false); END_SECTION START_SECTION(bool estimateFromWeightAndCompAndS(double average_weight, UInt S, double C, double H, double N, double O, double P)) EmpiricalFormula ef("C494H776N136O148S4"); EmpiricalFormula ef_approx; EmpiricalFormula ef_approx_S; bool return_flag; // Using averagine stoichiometry, excluding sulfur. return_flag = ef_approx_S.estimateFromWeightAndCompAndS(ef.getAverageWeight(), 4, 4.9384, 7.7583, 1.3577, 1.4773, 0); TEST_EQUAL(4, ef_approx_S.getNumberOf(db->getElement("S"))); // Formula of methionine. EmpiricalFormula ef2("C5H9N1O1S1"); // Using averagine stoichiometry, excluding sulfur. return_flag = ef_approx_S.estimateFromWeightAndCompAndS(ef2.getAverageWeight(), 1, 4.9384, 7.7583, 1.3577, 1.4773, 0); // Shouldn't need negative hydrogens for this approximation. TEST_EQUAL(return_flag, true); ef_approx.estimateFromWeightAndComp(ef2.getAverageWeight(), 4.9384, 7.7583, 1.3577, 1.4773, 0.0417, 0); // The averagine approximation should result in 0 sulfurs. TEST_EQUAL(0, ef_approx.getNumberOf(db->getElement("S"))); // But with the sulfur-specified averagine version, we forced it be 1 TEST_EQUAL(1, ef_approx_S.getNumberOf(db->getElement("S"))); TOLERANCE_ABSOLUTE(1); TEST_REAL_SIMILAR(ef_approx.getAverageWeight(), ef_approx_S.getAverageWeight()); END_SECTION START_SECTION(double getMonoWeight() const) EmpiricalFormula ef("C2"); const Element* e = db->getElement("C"); TEST_REAL_SIMILAR(ef.getMonoWeight(), e->getMonoWeight() * 2) ef.setCharge(1); TEST_REAL_SIMILAR(ef.getMonoWeight(), e->getMonoWeight() * 2 + Constants::PROTON_MASS_U) ef.setCharge(-1); TEST_REAL_SIMILAR(ef.getMonoWeight(), e->getMonoWeight() * 2 - Constants::PROTON_MASS_U) TEST_REAL_SIMILAR(EmpiricalFormula("OH").getMonoWeight(), EmpiricalFormula("HO").getMonoWeight()); TEST_REAL_SIMILAR(EmpiricalFormula("").getMonoWeight(), 0.0) TEST_EQUAL(EmpiricalFormula("C5H2").getMonoWeight() < EmpiricalFormula("C5D2").getMonoWeight(), true) TEST_EQUAL(EmpiricalFormula("C5D2").getMonoWeight() < EmpiricalFormula("C5T2").getMonoWeight(), true) END_SECTION START_SECTION(double getLightestIsotopeWeight() const) EmpiricalFormula ef("C636H1007N167O178S5PtH-2"); TEST_REAL_SIMILAR(ef.getLightestIsotopeWeight(), ef.getMonoWeight() - Constants::NEUTRON_MASS_U * 3) END_SECTION START_SECTION(String toString() const) EmpiricalFormula ef("C2H5"); String str = ef.toString(); TEST_EQUAL(String(str).hasSubstring("H5"), true) TEST_EQUAL(String(str).hasSubstring("C2"), true) END_SECTION START_SECTION((std::map<std::string, int> toMap() const)) EmpiricalFormula ef("C2H5"); auto m = ef.toMap(); TEST_EQUAL(m["C"], 2) TEST_EQUAL(m["H"], 5) END_SECTION START_SECTION([EXTRA](friend std::ostream& operator<<(std::ostream&, const EmpiricalFormula&))) stringstream ss; EmpiricalFormula ef("C2H5"); ss << ef; TEST_EQUAL(String(ss.str()).hasSubstring("H5"), true); TEST_EQUAL(String(ss.str()).hasSubstring("C2"), true); END_SECTION START_SECTION(bool operator!=(const EmpiricalFormula& rhs) const) EmpiricalFormula ef1("C2H5"), ef2(*e_ptr); TEST_FALSE(ef1 == ef2) TEST_EQUAL(ef1 != ef1, false) ef2.setCharge(1); TEST_EQUAL(ef2 != *e_ptr, true) END_SECTION START_SECTION(bool operator==(const EmpiricalFormula& rhs) const) EmpiricalFormula ef1("C2H5"), ef2(*e_ptr); TEST_EQUAL(ef1 == ef2, false) TEST_TRUE(ef1 == ef1) ef2.setCharge(1); TEST_EQUAL(ef2 == *e_ptr, false) TEST_EQUAL(EmpiricalFormula("C5(2)H5") == EmpiricalFormula("C5D5"), true) TEST_EQUAL(EmpiricalFormula("C5(3)H5") == EmpiricalFormula("C5T5"), true) END_SECTION START_SECTION(ConstIterator begin() const) EmpiricalFormula ef("C6H12O6"); std::map<String, SignedSize> formula; formula["C"] = 6; formula["H"] = 12; formula["O"] = 6; for (EmpiricalFormula::ConstIterator it = ef.begin(); it != ef.end(); ++it) { TEST_EQUAL(it->second, formula[it->first->getSymbol()]) } END_SECTION START_SECTION(ConstIterator end() const) NOT_TESTABLE END_SECTION START_SECTION(IsotopeDistribution getIsotopeDistribution(UInt max_depth) const) EmpiricalFormula ef("C"); IsotopeDistribution iso = ef.getIsotopeDistribution(CoarseIsotopePatternGenerator(20)); double result_mass[] = { 12, 13.0033548378 }; double result_prob[] = { 0.9893, 0.0107 }; Size i = 0; for (IsotopeDistribution::ConstIterator it = iso.begin(); it != iso.end(); ++it, ++i) { TEST_REAL_SIMILAR(it->getIntensity(), result_prob[i]) // accurate masses should have been calculated TEST_REAL_SIMILAR(it->getMZ(), result_mass[i]) } IsotopeDistribution iso2 = ef.getIsotopeDistribution(CoarseIsotopePatternGenerator(20, true)); double result_rounded_mass[] = { 12, 13 }; i = 0; for (IsotopeDistribution::ConstIterator it = iso2.begin(); it != iso2.end(); ++it, ++i) { // probabilities should not change due to mass vs atomic number calculations TEST_REAL_SIMILAR(it->getIntensity(), result_prob[i]) // atomic numbers should have been calculated TEST_REAL_SIMILAR(it->getMZ(), result_rounded_mass[i]) } // Formula of Bovine Serum Albumin (BSA) that has been processed and is missing the first 24 AA EmpiricalFormula ef2("C2934H4615N781O897S39"); IsotopeDistribution iso3 = ef2.getIsotopeDistribution(CoarseIsotopePatternGenerator(100)); // monoisotopic mass TEST_REAL_SIMILAR(iso3.begin()->getMZ(), 66389.863) // the average mass of the IsotopeDistribution is computed from its masses and probabilities // and should be extremely close to the result from the EmpiricalFormula which uses the // average weights of each atom. TEST_REAL_SIMILAR(iso3.averageMass(), ef2.getAverageWeight()) Peak1D most_abundant = iso3.getMostAbundant(); // Partially a regression test. For such a large molecule, consecutive isotopes have very similar probabilities // and a small change could change the result by 1Da (e.g. numerical error, elemental isotope probabilities) TEST_REAL_SIMILAR(most_abundant.getMZ(), 66432.0037); TEST_REAL_SIMILAR(most_abundant.getIntensity(), 0.057); IsotopeDistribution iso4 = ef2.getIsotopeDistribution(CoarseIsotopePatternGenerator(100, true)); // rounded monoisotopic mass TEST_EQUAL(iso4.begin()->getMZ(), 66390) TEST_REAL_SIMILAR(iso4.averageMass(), ef2.getAverageWeight()) most_abundant = iso4.getMostAbundant(); TEST_EQUAL(most_abundant.getMZ(), 66432); TEST_REAL_SIMILAR(most_abundant.getIntensity(), 0.057); END_SECTION START_SECTION(IsotopeDistribution getConditionalFragmentIsotopeDist(const EmpiricalFormula& precursor, const std::set<UInt>& precursor_isotopes, const CoarseIsotopePatternGenerator& solver) const) EmpiricalFormula precursor("C2"); EmpiricalFormula fragment("C"); std::set<UInt> precursor_isotopes; precursor_isotopes.insert(0); // isolated precursor isotope is M0 IsotopeDistribution iso = fragment.getConditionalFragmentIsotopeDist(precursor, precursor_isotopes, CoarseIsotopePatternGenerator()); double result_prob[] = { 1.0 }; double result_mass[] = { 12.0 }; Size i = 0; for (IsotopeDistribution::ConstIterator it = iso.begin(); it != iso.end(); ++it, ++i) { TEST_REAL_SIMILAR(it->getIntensity(), result_prob[i]) TEST_REAL_SIMILAR(it->getMZ(), result_mass[i]) } precursor_isotopes.clear(); precursor_isotopes.insert(1); // isolated precursor isotope is M+1 iso = fragment.getConditionalFragmentIsotopeDist(precursor, precursor_isotopes, CoarseIsotopePatternGenerator()); double result_prob2[] = { 0.5, 0.5 }; double result_mass2[] = { 12.0, 13.0033548378 }; i = 0; for (IsotopeDistribution::ConstIterator it = iso.begin(); it != iso.end(); ++it, ++i) { TEST_REAL_SIMILAR(it->getIntensity(), result_prob2[i]) TEST_REAL_SIMILAR(it->getMZ(), result_mass2[i]) } precursor_isotopes.insert(0); // isolated precursor isotopes are M0 and M+1 iso = fragment.getConditionalFragmentIsotopeDist(precursor, precursor_isotopes, CoarseIsotopePatternGenerator()); double result_prob3[] = { 0.98941, 0.01059}; i = 0; for (IsotopeDistribution::ConstIterator it = iso.begin(); it != iso.end(); ++it, ++i) { TEST_REAL_SIMILAR(it->getIntensity(), result_prob3[i]) // The masses shouldn't change TEST_REAL_SIMILAR(it->getMZ(), result_mass2[i]) } precursor_isotopes.insert(2); // isolated precursor isotopes are M0, M+1, and M+2 // This is the example found in the comments of the getConditionalFragmentIsotopeDist function. // Since we're isolating all the possible precursor isotopes, the fragment isotope distribution // should be equivalent to the natural isotope abundances. iso = fragment.getConditionalFragmentIsotopeDist(precursor, precursor_isotopes, CoarseIsotopePatternGenerator()); double result4[] = { 0.9893, 0.0107}; i = 0; for (IsotopeDistribution::ConstIterator it = iso.begin(); it != iso.end(); ++it, ++i) { TEST_REAL_SIMILAR(it->getIntensity(), result4[i]) } precursor_isotopes.insert(3); // isolated precursor isotopes are M0, M+1, M+2, and M+3 // It's impossible for precursor C2 to have 3 extra neutrons (assuming only natural stable isotopes) // Invalid precursor isotopes are ignored and should give the answer as if they were not there iso = fragment.getConditionalFragmentIsotopeDist(precursor, precursor_isotopes, CoarseIsotopePatternGenerator()); i = 0; for (IsotopeDistribution::ConstIterator it = iso.begin(); it != iso.end(); ++it, ++i) { TEST_REAL_SIMILAR(it->getIntensity(), result4[i]) } // Testing rounded masses iso = fragment.getConditionalFragmentIsotopeDist(precursor, precursor_isotopes, CoarseIsotopePatternGenerator(0, true)); double result_rounded_masss[] = { 12, 13 }; i = 0; for (IsotopeDistribution::ConstIterator it = iso.begin(); it != iso.end(); ++it, ++i) { TEST_REAL_SIMILAR(it->getMZ(), result_rounded_masss[i]) } precursor = EmpiricalFormula("C10H10N10O10S2"); EmpiricalFormula big_fragment = EmpiricalFormula("C9H9N9O9S1"); EmpiricalFormula small_fragment = EmpiricalFormula("C1H1N1O1S1"); precursor_isotopes.clear(); precursor_isotopes.insert(1); // isolated precursor isotope is M+1 IsotopeDistribution big_iso = big_fragment.getConditionalFragmentIsotopeDist(precursor, precursor_isotopes, CoarseIsotopePatternGenerator()); IsotopeDistribution small_iso = small_fragment.getConditionalFragmentIsotopeDist(precursor, precursor_isotopes, CoarseIsotopePatternGenerator()); // When we isolate only the M+1 precursor isotope, the big_fragment is more likely to exist as M+1 than M0. TEST_EQUAL(big_iso.getContainer()[0].getIntensity() < 0.2, true) TEST_EQUAL(big_iso.getContainer()[1].getIntensity() > 0.8, true) // The small_fragment, however, is more likely to exist as M0 than M+1. TEST_EQUAL(small_iso.getContainer()[0].getIntensity() > 0.8, true) TEST_EQUAL(small_iso.getContainer()[1].getIntensity() < 0.2, true) // Since the two fragments also happen to be complementary, their probabilities are perfectly reversed. IsotopeDistribution::ConstIterator big_it = big_iso.begin(); IsotopeDistribution::ConstReverseIterator small_it = small_iso.rbegin(); for (; big_it != big_iso.end(); ++big_it, ++small_it) { TEST_REAL_SIMILAR(big_it->getIntensity(), small_it->getIntensity()) } END_SECTION START_SECTION(([EXTRA] Check correct charge semantics)) EmpiricalFormula ef1("H4C+"); // CH4 +1 charge const Element* H = db->getElement("H"); const Element* C = db->getElement("C"); TEST_EQUAL(ef1.getNumberOf(H), 4) TEST_EQUAL(ef1.getNumberOf(C), 1) TEST_EQUAL(ef1.getCharge(), 1) EmpiricalFormula ef2("H4C1+"); // "" TEST_EQUAL(ef2.getNumberOf(H), 4) TEST_EQUAL(ef2.getNumberOf(C), 1) TEST_EQUAL(ef2.getCharge(), 1) EmpiricalFormula ef3("H4C-1+"); // C-1 H4 +1 charge TEST_EQUAL(ef3.getNumberOf(H), 4) TEST_EQUAL(ef3.getNumberOf(C), -1) TEST_EQUAL(ef3.getCharge(), 1) EmpiricalFormula ef4("H4C-1"); // C-1 H4 0 charge TEST_EQUAL(ef4.getNumberOf(H), 4) TEST_EQUAL(ef4.getNumberOf(C), -1) TEST_EQUAL(ef4.getCharge(), 0) EmpiricalFormula ef5("H4C1-1"); // C1 H4 -1 charge TEST_EQUAL(ef5.getNumberOf(H), 4) TEST_EQUAL(ef5.getNumberOf(C), 1) TEST_EQUAL(ef5.getCharge(), -1) EmpiricalFormula ef6("H4C-1-1"); // C-1 H4 -1 charge TEST_EQUAL(ef6.getNumberOf(H), 4) TEST_EQUAL(ef6.getNumberOf(C), -1) TEST_EQUAL(ef6.getCharge(), -1) EmpiricalFormula ef7("H4C-1-"); // C-1 H4 -1 charge TEST_EQUAL(ef7.getNumberOf(H), 4) TEST_EQUAL(ef7.getNumberOf(C), -1) TEST_EQUAL(ef7.getCharge(), -1) EmpiricalFormula ef8("-"); // -1 Charge TEST_EQUAL(ef8.getNumberOf(H), 0) TEST_EQUAL(ef8.getNumberOf(C), 0) TEST_EQUAL(ef8.getCharge(), -1) EmpiricalFormula ef9("+"); // +1 Charge TEST_EQUAL(ef9.getNumberOf(H), 0) TEST_EQUAL(ef9.getNumberOf(C), 0) TEST_EQUAL(ef9.getCharge(), 1) EmpiricalFormula ef10("-3"); // -3 Charge TEST_EQUAL(ef10.getNumberOf(H), 0) TEST_EQUAL(ef10.getNumberOf(C), 0) TEST_EQUAL(ef10.getCharge(), -3) EmpiricalFormula ef11("+3"); // +3 Charge TEST_EQUAL(ef11.getNumberOf(H), 0) TEST_EQUAL(ef11.getNumberOf(C), 0) TEST_EQUAL(ef11.getCharge(), 3) END_SECTION START_SECTION((static EmpiricalFormula hydrogen(int n_atoms = 1))) { EmpiricalFormula f("H"); EmpiricalFormula h = EmpiricalFormula::hydrogen(); TEST_EQUAL(f, h); } END_SECTION START_SECTION((static EmpiricalFormula hydrogen(int n_atoms = 1))) { EmpiricalFormula f("H2O"); EmpiricalFormula w = EmpiricalFormula::water(); TEST_EQUAL(f, w); } END_SECTION START_SECTION(([EXTRA] std::hash<EmpiricalFormula>)) { // Test that equal formulas have equal hashes EmpiricalFormula ef1("C6H12O6"); EmpiricalFormula ef2("C6H12O6"); EmpiricalFormula ef3("H12C6O6"); // Same formula, different order std::hash<EmpiricalFormula> hasher; TEST_EQUAL(hasher(ef1), hasher(ef2)) TEST_EQUAL(hasher(ef1), hasher(ef3)) // Order shouldn't matter // Test that different formulas have different hashes (most likely) EmpiricalFormula ef4("C6H12O7"); // Different formula TEST_NOT_EQUAL(hasher(ef1), hasher(ef4)) // Test formulas with charges EmpiricalFormula ef5("C6H12O6+"); EmpiricalFormula ef6("C6H12O6+"); EmpiricalFormula ef7("C6H12O6-"); TEST_EQUAL(hasher(ef5), hasher(ef6)) TEST_NOT_EQUAL(hasher(ef5), hasher(ef7)) // Different charge TEST_NOT_EQUAL(hasher(ef1), hasher(ef5)) // Same formula, different charge // Test empty formula EmpiricalFormula ef_empty1; EmpiricalFormula ef_empty2; TEST_EQUAL(hasher(ef_empty1), hasher(ef_empty2)) // Test that formulas work in unordered_set std::unordered_set<EmpiricalFormula> formula_set; formula_set.insert(ef1); formula_set.insert(ef2); // Duplicate, should not increase size formula_set.insert(ef4); // Different formula TEST_EQUAL(formula_set.size(), 2) TEST_EQUAL(formula_set.count(ef1), 1) TEST_EQUAL(formula_set.count(ef3), 1) // Same as ef1 TEST_EQUAL(formula_set.count(ef4), 1) } END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SignalToNoiseEstimator_test.cpp
.cpp
2,599
111
// 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/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimator.h> /////////////////////////// using namespace OpenMS; using namespace std; class TestSignalToNoiseEstimator : public SignalToNoiseEstimator< > { public: TestSignalToNoiseEstimator() : SignalToNoiseEstimator< >() { } TestSignalToNoiseEstimator(const TestSignalToNoiseEstimator& bpf) : SignalToNoiseEstimator< >(bpf) { } TestSignalToNoiseEstimator& operator=(const TestSignalToNoiseEstimator& bpf) { if (&bpf==this) return *this; SignalToNoiseEstimator< >::operator=(bpf); return *this; } protected: void computeSTN_(const MSSpectrum& C) throw() override { if (C.begin() == C.end()) { std::cout << "bla"; } // do nothing here... } }; START_TEST(SignalToNoiseEstimator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TestSignalToNoiseEstimator* ptr = nullptr; TestSignalToNoiseEstimator* nullPointer = nullptr; START_SECTION((SignalToNoiseEstimator())) ptr = new TestSignalToNoiseEstimator(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((SignalToNoiseEstimator(const SignalToNoiseEstimator &source))) TestSignalToNoiseEstimator sne; MSSpectrum spec; sne.init(spec); TestSignalToNoiseEstimator sne_copy(sne); NOT_TESTABLE END_SECTION START_SECTION((SignalToNoiseEstimator& operator=(const SignalToNoiseEstimator &source))) TestSignalToNoiseEstimator sne; MSSpectrum spec; sne.init(spec); TestSignalToNoiseEstimator sne_copy; sne_copy = sne; NOT_TESTABLE END_SECTION START_SECTION((virtual ~SignalToNoiseEstimator())) delete ptr; END_SECTION START_SECTION((virtual void init(const Container& c))) TestSignalToNoiseEstimator sne; MSSpectrum spec; sne.init(spec); NOT_TESTABLE END_SECTION START_SECTION((virtual double getSignalToNoise(const Size index))) // hard to do without implementing computeSTN_ properly NOT_TESTABLE END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AnnotatedMSRun_test.cpp
.cpp
16,044
467
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: David Voigt $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/METADATA/AnnotatedMSRun.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/PeptideHit.h> #include <unordered_set> #include <unordered_map> START_TEST(AnnotatedMSRun, "$Id$") using namespace OpenMS; // Default constructor AnnotatedMSRun* ptr = nullptr; AnnotatedMSRun* nullPointer = nullptr; START_SECTION((AnnotatedMSRun())) ptr = new AnnotatedMSRun(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~AnnotatedMSRun())) delete ptr; END_SECTION START_SECTION((explicit AnnotatedMSRun(MSExperiment&& experiment))) MSExperiment exp; MSSpectrum spec; spec.setRT(42.0); spec.setMSLevel(2); exp.addSpectrum(spec); AnnotatedMSRun annotated_data(std::move(exp)); TEST_EQUAL(annotated_data.getMSExperiment().size(), 1) TEST_REAL_SIMILAR(annotated_data.getMSExperiment()[0].getRT(), 42.0) END_SECTION START_SECTION((ProteinIdentification& getProteinIdentifications())) AnnotatedMSRun annotated_data; auto& prot_id = annotated_data.getProteinIdentifications(); prot_id.resize(1); prot_id[0].setIdentifier("Test"); TEST_EQUAL(annotated_data.getProteinIdentifications()[0].getIdentifier(), "Test") END_SECTION START_SECTION((const ProteinIdentification& getProteinIdentifications() const)) AnnotatedMSRun annotated_data; auto& prot_id = annotated_data.getProteinIdentifications(); prot_id.resize(1); prot_id[0].setIdentifier("Test"); const AnnotatedMSRun& const_data = annotated_data; TEST_EQUAL(const_data.getProteinIdentifications()[0].getIdentifier(), "Test") END_SECTION START_SECTION((PeptideIdentification& getPeptideIdentification(size_t index))) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec1, spec2; exp.addSpectrum(spec1); exp.addSpectrum(spec2); annotated_data.getMSExperiment() = std::move(exp); // Resize peptide identifications to match spectra annotated_data.getPeptideIdentifications().resize(2); // Add data to the first peptide identification PeptideHit hit; hit.setSequence(AASequence::fromString("PEPTIDE")); annotated_data.getPeptideIdentifications()[0].insertHit(hit); TEST_EQUAL(annotated_data.getPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(annotated_data.getPeptideIdentifications()[0].getHits()[0].getSequence().toString(), "PEPTIDE") END_SECTION START_SECTION((const PeptideIdentification& getPeptideIdentification(size_t index) const)) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec1, spec2; exp.addSpectrum(spec1); exp.addSpectrum(spec2); annotated_data.getMSExperiment() = std::move(exp); // Resize peptide identifications to match spectra annotated_data.getPeptideIdentifications().resize(2); // Add data to the first peptide identification PeptideHit hit; hit.setSequence(AASequence::fromString("PEPTIDE")); annotated_data.getPeptideIdentifications()[0].insertHit(hit); const AnnotatedMSRun& const_data = annotated_data; TEST_EQUAL(const_data.getPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(const_data.getPeptideIdentifications()[0].getHits()[0].getSequence().toString(), "PEPTIDE") END_SECTION START_SECTION((PeptideIdentificationList& getPeptideIdentifications())) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec1, spec2; exp.addSpectrum(spec1); exp.addSpectrum(spec2); annotated_data.getMSExperiment() = std::move(exp); // Resize peptide identifications to match spectra annotated_data.getPeptideIdentifications().resize(2); // Add data to the peptide identifications PeptideHit hit1, hit2; hit1.setSequence(AASequence("PEPTIDER")); hit2.setSequence(AASequence("PEPTIDAR")); annotated_data.getPeptideIdentifications()[0].insertHit(hit1); annotated_data.getPeptideIdentifications()[1].insertHit(hit2); TEST_EQUAL(annotated_data.getPeptideIdentifications().size(), 2) TEST_EQUAL(annotated_data.getPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(annotated_data.getPeptideIdentifications()[1].getHits().size(), 1) TEST_EQUAL(annotated_data.getPeptideIdentifications()[0].getHits()[0].getSequence().toString(), "PEPTIDER") TEST_EQUAL(annotated_data.getPeptideIdentifications()[1].getHits()[0].getSequence().toString(), "PEPTIDAR") END_SECTION START_SECTION((const PeptideIdentificationList& getPeptideIdentifications() const)) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec1, spec2; exp.addSpectrum(spec1); exp.addSpectrum(spec2); annotated_data.getMSExperiment() = std::move(exp); // Resize peptide identifications to match spectra annotated_data.getPeptideIdentifications().resize(2); // Add data to the peptide identifications PeptideHit hit1, hit2; hit1.setSequence(AASequence::fromString("PEPTIDER")); hit2.setSequence(AASequence::fromString("PEPTIDAR")); annotated_data.getPeptideIdentifications()[0].insertHit(hit1); annotated_data.getPeptideIdentifications()[1].insertHit(hit2); const AnnotatedMSRun& const_data = annotated_data; TEST_EQUAL(const_data.getPeptideIdentifications().size(), 2) TEST_EQUAL(const_data.getPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(const_data.getPeptideIdentifications()[1].getHits().size(), 1) TEST_EQUAL(const_data.getPeptideIdentifications()[0].getHits()[0].getSequence().toString(), "PEPTIDER") TEST_EQUAL(const_data.getPeptideIdentifications()[1].getHits()[0].getSequence().toString(), "PEPTIDAR") END_SECTION START_SECTION((void setPeptideIdentification(PeptideIdentification&& id, size_t index))) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec1, spec2; exp.addSpectrum(spec1); exp.addSpectrum(spec2); annotated_data.getMSExperiment() = std::move(exp); // Resize peptide identifications to match spectra annotated_data.getPeptideIdentifications().resize(2); // Create a peptide identification PeptideIdentification pep_id; PeptideHit hit; hit.setSequence(AASequence::fromString("PEPTIDE")); pep_id.insertHit(hit); // Set the peptide identification annotated_data.getPeptideIdentifications()[0] = pep_id; TEST_EQUAL(annotated_data.getPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(annotated_data.getPeptideIdentifications()[0].getHits()[0].getSequence().toString(), "PEPTIDE") END_SECTION START_SECTION((void setPeptideIdentifications(PeptideIdentificationList&& ids))) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec1, spec2; exp.addSpectrum(spec1); exp.addSpectrum(spec2); annotated_data.getMSExperiment() = std::move(exp); // Create a vector of peptide identifications PeptideIdentificationList pep_ids; PeptideIdentification pep_id1, pep_id2; PeptideHit hit1, hit2; hit1.setSequence(AASequence::fromString("PEPTIDER")); hit2.setSequence(AASequence::fromString("PEPTIDAR")); pep_id1.insertHit(hit1); pep_id2.insertHit(hit2); pep_ids.push_back(pep_id1); pep_ids.push_back(pep_id2); // Set all peptide identifications annotated_data.setPeptideIdentifications(std::move(pep_ids)); TEST_EQUAL(annotated_data.getPeptideIdentifications().size(), 2) TEST_EQUAL(annotated_data.getPeptideIdentifications()[0].getHits().size(), 1) TEST_EQUAL(annotated_data.getPeptideIdentifications()[1].getHits().size(), 1) TEST_EQUAL(annotated_data.getPeptideIdentifications()[0].getHits()[0].getSequence().toString(), "PEPTIDER") TEST_EQUAL(annotated_data.getPeptideIdentifications()[1].getHits()[0].getSequence().toString(), "PEPTIDAR") END_SECTION START_SECTION((void clearAllPeptideIdentifications())) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec1, spec2; exp.addSpectrum(spec1); exp.addSpectrum(spec2); annotated_data.getMSExperiment() = std::move(exp); // Resize peptide identifications to match spectra annotated_data.getPeptideIdentifications().resize(2); // Add data to the peptide identifications PeptideHit hit1, hit2; hit1.setSequence(AASequence::fromString("PEPTIDER")); hit2.setSequence(AASequence::fromString("PEPTIDAR")); annotated_data.getPeptideIdentifications()[0].insertHit(hit1); annotated_data.getPeptideIdentifications()[1].insertHit(hit2); // Clear all peptide identifications annotated_data.getPeptideIdentifications().clear(); TEST_EQUAL(annotated_data.getPeptideIdentifications().size(), 0) END_SECTION START_SECTION((MSExperiment& getMSExperiment())) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec; spec.setRT(42.0); spec.setMSLevel(2); exp.addSpectrum(spec); annotated_data.getMSExperiment() = std::move(exp); TEST_EQUAL(annotated_data.getMSExperiment().size(), 1) TEST_REAL_SIMILAR(annotated_data.getMSExperiment()[0].getRT(), 42.0) END_SECTION START_SECTION((const MSExperiment& getMSExperiment() const)) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec; spec.setRT(42.0); spec.setMSLevel(2); exp.addSpectrum(spec); annotated_data.getMSExperiment() = std::move(exp); const AnnotatedMSRun& const_data = annotated_data; TEST_EQUAL(const_data.getMSExperiment().size(), 1) TEST_REAL_SIMILAR(const_data.getMSExperiment()[0].getRT(), 42.0) END_SECTION START_SECTION((Iterator functionality)) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec1, spec2; spec1.setRT(10.0); spec2.setRT(20.0); exp.addSpectrum(spec1); exp.addSpectrum(spec2); annotated_data.getMSExperiment() = std::move(exp); // Resize peptide identifications to match spectra annotated_data.getPeptideIdentifications().resize(2); // Add data to the peptide identifications PeptideHit hit1, hit2; hit1.setSequence(AASequence::fromString("PEPTIDER")); hit2.setSequence(AASequence::fromString("PEPTIDAR")); annotated_data.getPeptideIdentifications()[0].insertHit(hit1); annotated_data.getPeptideIdentifications()[1].insertHit(hit2); // Test iterator functionality size_t count = 0; for (auto [spectrum, peptide_id] : annotated_data) { if (count == 0) { TEST_REAL_SIMILAR(spectrum.getRT(), 10.0) TEST_EQUAL(peptide_id.getHits().size(), 1) TEST_EQUAL(peptide_id.getHits()[0].getSequence().toString(), "PEPTIDER") } else if (count == 1) { TEST_REAL_SIMILAR(spectrum.getRT(), 20.0) TEST_EQUAL(peptide_id.getHits().size(), 1) TEST_EQUAL(peptide_id.getHits()[0].getSequence().toString(), "PEPTIDAR") } count++; } TEST_EQUAL(count, 2) END_SECTION START_SECTION((Operator[] functionality)) AnnotatedMSRun annotated_data; MSExperiment exp; MSSpectrum spec1, spec2; spec1.setRT(10.0); spec2.setRT(20.0); exp.addSpectrum(spec1); exp.addSpectrum(spec2); annotated_data.getMSExperiment() = std::move(exp); // Resize peptide identifications to match spectra annotated_data.getPeptideIdentifications().resize(2); // Add data to the peptide identifications PeptideHit hit1, hit2; hit1.setSequence(AASequence::fromString("PEPTIDER")); hit2.setSequence(AASequence::fromString("PEPTIDAR")); annotated_data.getPeptideIdentifications()[0].insertHit(hit1); annotated_data.getPeptideIdentifications()[1].insertHit(hit2); // Test operator[] functionality auto [spectrum, peptide_id] = annotated_data[0]; TEST_REAL_SIMILAR(spectrum.getRT(), 10.0) TEST_EQUAL(peptide_id.getHits().size(), 1) TEST_EQUAL(peptide_id.getHits()[0].getSequence().toString(), "PEPTIDER") auto [spectrum2, peptide_id2] = annotated_data[1]; TEST_REAL_SIMILAR(spectrum2.getRT(), 20.0) TEST_EQUAL(peptide_id2.getHits().size(), 1) TEST_EQUAL(peptide_id2.getHits()[0].getSequence().toString(), "PEPTIDAR") // Test const operator[] functionality const AnnotatedMSRun& const_data = annotated_data; auto [const_spectrum, const_peptide_id] = const_data[0]; TEST_REAL_SIMILAR(const_spectrum.getRT(), 10.0) TEST_EQUAL(const_peptide_id.getHits().size(), 1) TEST_EQUAL(const_peptide_id.getHits()[0].getSequence().toString(), "PEPTIDER") END_SECTION START_SECTION((bool operator==(const AnnotatedMSRun& rhs) const)) // Create two identical AnnotatedMSRun objects AnnotatedMSRun run1, run2; // Set up MSExperiment MSExperiment exp; MSSpectrum spec; spec.setRT(42.0); spec.setMSLevel(2); exp.addSpectrum(spec); run1.setMSExperiment(exp); run2.setMSExperiment(exp); // Set up peptide identifications PeptideIdentificationList pep_ids; PeptideIdentification pep_id; PeptideHit hit; hit.setSequence(AASequence::fromString("PEPTIDE")); pep_id.insertHit(hit); pep_ids.push_back(pep_id); run1.setPeptideIdentifications(pep_ids); run2.setPeptideIdentifications(pep_ids); // Set up protein identifications std::vector<ProteinIdentification> prot_ids; ProteinIdentification prot_id; prot_id.setIdentifier("TestProtein"); prot_ids.push_back(prot_id); run1.setProteinIdentifications(prot_ids); run2.setProteinIdentifications(prot_ids); // Test equality TEST_EQUAL(run1 == run2, true) TEST_EQUAL(run1 != run2, false) // Test inequality - modify run2 run2.getMSExperiment()[0].setRT(100.0); TEST_EQUAL(run1 == run2, false) TEST_EQUAL(run1 != run2, true) END_SECTION START_SECTION(([EXTRA] std::hash<AnnotatedMSRun>)) // Test 1: Equal objects have equal hashes AnnotatedMSRun run1, run2; // Set up MSExperiment MSExperiment exp; MSSpectrum spec; spec.setRT(42.0); spec.setMSLevel(2); exp.addSpectrum(spec); run1.setMSExperiment(exp); run2.setMSExperiment(exp); // Set up peptide identifications PeptideIdentificationList pep_ids; PeptideIdentification pep_id; pep_id.setIdentifier("test_id"); pep_id.setScoreType("test_score"); PeptideHit hit; hit.setSequence(AASequence::fromString("PEPTIDE")); pep_id.insertHit(hit); pep_ids.push_back(pep_id); run1.setPeptideIdentifications(pep_ids); run2.setPeptideIdentifications(pep_ids); // Set up protein identifications std::vector<ProteinIdentification> prot_ids; ProteinIdentification prot_id; prot_id.setIdentifier("TestProtein"); prot_id.setSearchEngine("TestEngine"); prot_ids.push_back(prot_id); run1.setProteinIdentifications(prot_ids); run2.setProteinIdentifications(prot_ids); TEST_EQUAL(run1 == run2, true) TEST_EQUAL(std::hash<AnnotatedMSRun>{}(run1), std::hash<AnnotatedMSRun>{}(run2)) // Test 2: Different objects have different hashes (likely, not guaranteed) AnnotatedMSRun run3; MSExperiment exp3; MSSpectrum spec3; spec3.setRT(100.0); // Different RT spec3.setMSLevel(1); // Different MS level exp3.addSpectrum(spec3); run3.setMSExperiment(exp3); TEST_EQUAL(run1 == run3, false) TEST_NOT_EQUAL(std::hash<AnnotatedMSRun>{}(run1), std::hash<AnnotatedMSRun>{}(run3)) // Test 3: Test use in unordered_set std::unordered_set<AnnotatedMSRun> run_set; run_set.insert(run1); run_set.insert(run2); // Should not increase size (equal to run1) run_set.insert(run3); TEST_EQUAL(run_set.size(), 2) TEST_EQUAL(run_set.count(run1), 1) TEST_EQUAL(run_set.count(run3), 1) // Test 4: Test use in unordered_map std::unordered_map<AnnotatedMSRun, std::string> run_map; run_map[run1] = "first"; run_map[run3] = "third"; TEST_EQUAL(run_map.size(), 2) TEST_EQUAL(run_map[run1], "first") TEST_EQUAL(run_map[run2], "first") // run2 == run1, so should get same value TEST_EQUAL(run_map[run3], "third") // Test 5: Empty AnnotatedMSRun has consistent hash AnnotatedMSRun empty1, empty2; TEST_EQUAL(empty1 == empty2, true) TEST_EQUAL(std::hash<AnnotatedMSRun>{}(empty1), std::hash<AnnotatedMSRun>{}(empty2)) END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IonMobilityScoring_test.cpp
.cpp
20,683
540
// 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/IonMobilityScoring.h> /////////////////////////// using namespace std; using namespace OpenMS; using namespace OpenSwath; START_TEST(IonMobilityScoring, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// IonMobilityScoring* ptr = nullptr; IonMobilityScoring* nullPointer = nullptr; START_SECTION(IonMobilityScoring()) { ptr = new IonMobilityScoring(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~IonMobilityScoring()) { delete ptr; } END_SECTION OpenSwath::LightTransition mock_tr1; mock_tr1.product_mz = 500.2; mock_tr1.precursor_mz = 700.2; mock_tr1.fragment_charge = 1; mock_tr1.transition_name = "group1"; OpenSwath::LightTransition mock_tr2; mock_tr2.product_mz = 600.5; mock_tr2.precursor_mz = 700.2; mock_tr2.fragment_charge = 1; mock_tr2.transition_name = "group2"; // create transitions, e.g. library intensity std::vector<OpenSwath::LightTransition> transitions; transitions.push_back(mock_tr1); transitions.push_back(mock_tr2); OpenSwath::SpectrumPtr spec(new OpenSwath::Spectrum()); { OpenSwath::BinaryDataArrayPtr mass(new OpenSwath::BinaryDataArray); mass->data.push_back(500.2); mass->data.push_back(500.2); mass->data.push_back(500.2); mass->data.push_back(500.2); mass->data.push_back(500.2); mass->data.push_back(500.2); mass->data.push_back(500.2); mass->data.push_back(500.2); mass->data.push_back(500.3); mass->data.push_back(500.3); mass->data.push_back(500.3); mass->data.push_back(500.3); mass->data.push_back(500.3); mass->data.push_back(500.3); mass->data.push_back(500.3); mass->data.push_back(500.3); mass->data.push_back(600.2); mass->data.push_back(600.3); mass->data.push_back(600.4); mass->data.push_back(600.5); mass->data.push_back(600.6); mass->data.push_back(600.7); mass->data.push_back(600.8); mass->data.push_back(600.9); OpenSwath::BinaryDataArrayPtr intensity(new OpenSwath::BinaryDataArray); intensity->data.push_back(10); intensity->data.push_back(20); intensity->data.push_back(30); intensity->data.push_back(40); intensity->data.push_back(40); intensity->data.push_back(30); intensity->data.push_back(20); intensity->data.push_back(10); intensity->data.push_back(10); intensity->data.push_back(20); intensity->data.push_back(30); intensity->data.push_back(40); intensity->data.push_back(40); intensity->data.push_back(30); intensity->data.push_back(20); intensity->data.push_back(10); intensity->data.push_back(20); intensity->data.push_back(20); intensity->data.push_back(20); intensity->data.push_back(20); intensity->data.push_back(20); intensity->data.push_back(20); intensity->data.push_back(20); intensity->data.push_back(20); OpenSwath::BinaryDataArrayPtr ion_mobility(new OpenSwath::BinaryDataArray); ion_mobility->data.push_back(0.1); ion_mobility->data.push_back(0.2); ion_mobility->data.push_back(0.3); ion_mobility->data.push_back(0.4); // 40 ion_mobility->data.push_back(0.5); // 40 ion_mobility->data.push_back(0.6); ion_mobility->data.push_back(0.7); ion_mobility->data.push_back(0.8); ion_mobility->data.push_back(0.5); ion_mobility->data.push_back(0.6); ion_mobility->data.push_back(0.7); ion_mobility->data.push_back(0.8); // 40 ion_mobility->data.push_back(0.9); // 40 ion_mobility->data.push_back(1.1); ion_mobility->data.push_back(1.2); ion_mobility->data.push_back(1.3); ion_mobility->data.push_back(0.1); ion_mobility->data.push_back(0.2); ion_mobility->data.push_back(0.3); ion_mobility->data.push_back(0.4); ion_mobility->data.push_back(0.5); ion_mobility->data.push_back(0.6); ion_mobility->data.push_back(0.7); ion_mobility->data.push_back(0.8); ion_mobility->description = "Ion Mobility"; spec->setMZArray( mass); spec->setIntensityArray( intensity); spec->getDataArrays().push_back( ion_mobility ); } OpenSwath::SpectrumPtr ms1spec(new OpenSwath::Spectrum()); { OpenSwath::BinaryDataArrayPtr mass(new OpenSwath::BinaryDataArray); mass->data.push_back(700.2); mass->data.push_back(700.3); mass->data.push_back(700.4); mass->data.push_back(700.5); mass->data.push_back(700.6); mass->data.push_back(700.7); mass->data.push_back(700.8); mass->data.push_back(700.9); OpenSwath::BinaryDataArrayPtr intensity(new OpenSwath::BinaryDataArray); intensity->data.push_back(10); intensity->data.push_back(20); intensity->data.push_back(30); intensity->data.push_back(40); intensity->data.push_back(40); intensity->data.push_back(30); intensity->data.push_back(20); intensity->data.push_back(10); OpenSwath::BinaryDataArrayPtr ion_mobility(new OpenSwath::BinaryDataArray); ion_mobility->data.push_back(0.2); // shifted by one ion_mobility->data.push_back(0.3); ion_mobility->data.push_back(0.4); // 40 ion_mobility->data.push_back(0.5); // 40 ion_mobility->data.push_back(0.6); ion_mobility->data.push_back(0.7); ion_mobility->data.push_back(0.8); ion_mobility->data.push_back(0.9); ion_mobility->description = "Ion Mobility"; ms1spec->setMZArray( mass); ms1spec->setIntensityArray( intensity); ms1spec->getDataArrays().push_back( ion_mobility ); } START_SECTION(([EXTRA] static void driftScoring(const SpectrumSequence& spectrum, const std::vector<TransitionType> & transitions, OpenSwath_Scores & scores, const double drift_target, const RangeMobility im_range, const double dia_extraction_window_, const bool dia_extraction_ppm_, const double drift_extra, const bool apply_im_peak_picking) )) { OpenSwath_Scores scores; double drift_target = 1.0; OpenMS::RangeMobility im_range_1(1.0); im_range_1.minSpanIfSingular(1.); double im_drift_extra_pcnt_ = 0.25; double dia_extract_window_ = 0.3; bool dia_extraction_ppm_ = false; bool apply_im_peak_picking_ = false; // Test #1: Empty Spectrum OpenSwath::SpectrumPtr drift_spectrum(new OpenSwath::Spectrum()); OpenSwath::BinaryDataArrayPtr mass(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr ion_mobility(new OpenSwath::BinaryDataArray); drift_spectrum->setMZArray( mass); drift_spectrum->setIntensityArray( intensity); drift_spectrum->getDataArrays().push_back( ion_mobility ); std::vector<OpenSwath::SpectrumPtr> sptrArr; sptrArr.push_back(drift_spectrum); IonMobilityScoring::driftScoring(sptrArr, transitions, scores, drift_target, im_range_1, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_, apply_im_peak_picking_); TEST_REAL_SIMILAR(scores.im_drift, 0); TEST_REAL_SIMILAR(scores.im_drift_weighted, 0); TEST_REAL_SIMILAR(scores.im_delta_score, 0); TEST_REAL_SIMILAR(scores.im_xcorr_shape_score, 0) TEST_REAL_SIMILAR(scores.im_xcorr_coelution_score, 0) // Test #2: IM Scores (Condition 1/2) drift_spectrum = spec; std::vector<OpenSwath::SpectrumPtr> sptrArr2; sptrArr2.push_back(spec); // Test integrity of spectrum TEST_EQUAL(drift_spectrum->getMZArray()->data.size(), 24) TEST_EQUAL(drift_spectrum->getMZArray()->data.size(), drift_spectrum->getIntensityArray()->data.size()) TEST_EQUAL(drift_spectrum->getMZArray()->data.size(), drift_spectrum->getDriftTimeArray()->data.size()) IonMobilityScoring::driftScoring(sptrArr2, transitions, scores, drift_target, im_range_1, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_, apply_im_peak_picking_); TEST_REAL_SIMILAR(scores.im_drift, (0.705405 + 0.4)/2.0 ) TEST_REAL_SIMILAR(scores.im_drift_weighted, 0.662790697674419) TEST_REAL_SIMILAR(scores.im_delta_score, (0.294595 + 0.6)/2.0 ) TEST_REAL_SIMILAR(scores.im_xcorr_shape_score, 0.892124778448826) TEST_REAL_SIMILAR(scores.im_xcorr_coelution_score, 2.73205080756888) // Test #3: IM Scores (Condition 2/2) dia_extract_window_ = 0.1; IonMobilityScoring::driftScoring(sptrArr2, transitions, scores, drift_target, im_range_1, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_, apply_im_peak_picking_); TEST_REAL_SIMILAR(scores.im_drift, (0.5 + 0.4)/2.0 ) TEST_REAL_SIMILAR(scores.im_drift_weighted, 0.489473684210526) TEST_REAL_SIMILAR(scores.im_delta_score, (0.5 + 0.6)/2.0 ) TEST_REAL_SIMILAR(scores.im_xcorr_shape_score, 0.833513903989399) TEST_REAL_SIMILAR(scores.im_xcorr_coelution_score, 0.910683602522959) // Test #4: deal with exactly one entry in mobilogram dia_extract_window_ = 0.3; drift_target = 1.05; OpenMS::RangeMobility im_range_2(drift_target); im_range_2.minSpanIfSingular(0.1); IonMobilityScoring::driftScoring(sptrArr2, transitions, scores, drift_target, im_range_2, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_, apply_im_peak_picking_); TEST_REAL_SIMILAR(scores.im_drift, 1.1) TEST_REAL_SIMILAR(scores.im_drift_weighted, 1.1) TEST_REAL_SIMILAR(scores.im_delta_score, 0.05) TEST_REAL_SIMILAR(scores.im_xcorr_shape_score, 0.0) // higher is better TEST_REAL_SIMILAR(scores.im_xcorr_coelution_score, 1.) // lower is better // Test #5: deal with one zero transitions dia_extract_window_ = 0.3; OpenMS::RangeMobility im_range_3; im_range_3.setMin(1.0); im_range_3.setMax(1.3); drift_target = 1.1; IonMobilityScoring::driftScoring(sptrArr2, transitions, scores, drift_target, im_range_3, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_, apply_im_peak_picking_); TEST_REAL_SIMILAR(scores.im_drift, 1.16666666666667) TEST_REAL_SIMILAR(scores.im_drift_weighted, 1.16666666666667) TEST_REAL_SIMILAR(scores.im_delta_score, 0.0666666666666667) TEST_REAL_SIMILAR(scores.im_xcorr_shape_score, 1.0/3) TEST_REAL_SIMILAR(scores.im_xcorr_coelution_score, 3.73205080756888) // Test #6: deal with all-zero transitions // IM range from 2.5 to 3.5 OpenMS::RangeMobility im_range_4(3.0); im_range_4.minSpanIfSingular(1.); IonMobilityScoring::driftScoring(sptrArr2, transitions, scores, drift_target, im_range_4, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_, apply_im_peak_picking_); TEST_REAL_SIMILAR(scores.im_drift, -1) TEST_REAL_SIMILAR(scores.im_drift_weighted, -1) TEST_REAL_SIMILAR(scores.im_delta_score, -1) TEST_EQUAL(std::isnan(scores.im_xcorr_shape_score), true) TEST_REAL_SIMILAR(scores.im_xcorr_coelution_score, 0) } END_SECTION START_SECTION([EXTRA] static void driftScoringMS1(const SpectrumSequence& spectrum&, const std::vector<TransitionType> & transitions, OpenSwath_Scores & scores, const double drift_lower, const double drift_upper, const double drift_target, const double dia_extract_window_, const bool dia_extraction_ppm_, const double drift_extra)) { OpenSwath_Scores scores; // IM range from 0.5 to 1.5 double drift_target = 1.0; OpenMS::RangeMobility im_range(drift_target); im_range.minSpanIfSingular(1.); double im_drift_extra_pcnt_ = 0.25; double dia_extract_window_ = 0.3; bool dia_extraction_ppm_ = false; OpenSwath::SpectrumPtr drift_spectrum(new OpenSwath::Spectrum()); OpenSwath::BinaryDataArrayPtr ion_mobility(new OpenSwath::BinaryDataArray); drift_spectrum->getDataArrays().push_back( ion_mobility ); std::vector<OpenSwath::SpectrumPtr> sptrArr; sptrArr.push_back(drift_spectrum); IonMobilityScoring::driftScoringMS1(sptrArr, transitions, scores, drift_target, im_range, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_); OpenSwath::BinaryDataArrayPtr mass(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity(new OpenSwath::BinaryDataArray); drift_spectrum->setMZArray( mass); drift_spectrum->setIntensityArray( intensity); std::vector<OpenSwath::SpectrumPtr> sptrArr2; sptrArr2.push_back(drift_spectrum); IonMobilityScoring::driftScoringMS1(sptrArr2, transitions, scores, drift_target, im_range, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_); drift_spectrum = ms1spec; std::vector<OpenSwath::SpectrumPtr> sptrArr3; sptrArr3.push_back(drift_spectrum); TEST_EQUAL(drift_spectrum->getMZArray()->data.size(), 8) TEST_EQUAL(drift_spectrum->getMZArray()->data.size(), drift_spectrum->getIntensityArray()->data.size()) TEST_EQUAL(drift_spectrum->getMZArray()->data.size(), drift_spectrum->getDriftTimeArray()->data.size()) IonMobilityScoring::driftScoringMS1(sptrArr3, transitions, scores, drift_target, im_range, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_); TEST_REAL_SIMILAR(scores.im_ms1_delta_score, 0.7) } END_SECTION START_SECTION(([EXTRA] static void driftScoringMS1Contrast(std::vector<OpenSwath::SpectrumPtr> spectrum, OpenSwath::SpectrumPtr ms1spectrum, const std::vector<TransitionType> & transitions, OpenSwath_Scores & scores, const double drift_lower, const double drift_upper, const double drift_target, const double dia_extraction_window_, const bool dia_extraction_ppm_, const double drift_extra) )) { OpenSwath_Scores scores; // IM from 0.5 to 1.5 OpenMS::RangeMobility im_range_1(1); im_range_1.minSpanIfSingular(1.); double im_drift_extra_pcnt_ = 0.25; double dia_extract_window_ = 0.3; bool dia_extraction_ppm_ = false; OpenSwath::SpectrumPtr drift_spectrum(new OpenSwath::Spectrum()); OpenSwath::SpectrumPtr drift_spectrum_ms1(new OpenSwath::Spectrum()); OpenSwath::BinaryDataArrayPtr ion_mobility(new OpenSwath::BinaryDataArray); drift_spectrum_ms1->getDataArrays().push_back( ion_mobility ); drift_spectrum->getDataArrays().push_back( ion_mobility ); std::vector<OpenSwath::SpectrumPtr> sptrArr; std::vector<OpenSwath::SpectrumPtr> sptrArrMS1; sptrArr.push_back(drift_spectrum); sptrArrMS1.push_back(drift_spectrum_ms1); IonMobilityScoring::driftScoringMS1Contrast(sptrArr, sptrArrMS1, transitions, scores, im_range_1, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_); OpenSwath::BinaryDataArrayPtr mass(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intensity(new OpenSwath::BinaryDataArray); drift_spectrum->setMZArray( mass); drift_spectrum->setIntensityArray( intensity); drift_spectrum_ms1->setMZArray( mass); drift_spectrum_ms1->setIntensityArray( intensity); std::vector<OpenSwath::SpectrumPtr> sptrArr_2; std::vector<OpenSwath::SpectrumPtr> sptrArrMS1_2; sptrArr_2.push_back(drift_spectrum); sptrArrMS1_2.push_back(drift_spectrum_ms1); IonMobilityScoring::driftScoringMS1Contrast(sptrArr_2, sptrArrMS1, transitions, scores, im_range_1, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_); std::vector<OpenSwath::SpectrumPtr> sptrArr_3; std::vector<OpenSwath::SpectrumPtr> sptrArrMS1_3; drift_spectrum = spec; drift_spectrum_ms1 = ms1spec; sptrArr_3.push_back(drift_spectrum); sptrArrMS1_3.push_back(drift_spectrum_ms1); TEST_EQUAL(drift_spectrum->getMZArray()->data.size(), 24) TEST_EQUAL(drift_spectrum->getMZArray()->data.size(), drift_spectrum->getIntensityArray()->data.size()) TEST_EQUAL(drift_spectrum->getMZArray()->data.size(), drift_spectrum->getDriftTimeArray()->data.size()) IonMobilityScoring::driftScoringMS1Contrast(sptrArr_3, sptrArrMS1_3, transitions, scores, im_range_1, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_); TEST_REAL_SIMILAR(scores.im_ms1_contrast_coelution, 5.62132034355964) TEST_REAL_SIMILAR(scores.im_ms1_contrast_shape, 0.50991093654836) TEST_REAL_SIMILAR(scores.im_ms1_sum_contrast_coelution, 2) TEST_REAL_SIMILAR(scores.im_ms1_sum_contrast_shape, 0.56486260935015) dia_extract_window_ = 0.1; IonMobilityScoring::driftScoringMS1Contrast(sptrArr_3, sptrArrMS1_3, transitions, scores, im_range_1, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_); TEST_REAL_SIMILAR(scores.im_ms1_contrast_coelution, 6) TEST_REAL_SIMILAR(scores.im_ms1_contrast_shape, 0) TEST_REAL_SIMILAR(scores.im_ms1_sum_contrast_coelution, 6) TEST_REAL_SIMILAR(scores.im_ms1_sum_contrast_shape, 0) // deal with exactly one entry in mobilogram dia_extract_window_ = 0.3; // IM Span from 1.0 to 1.1 OpenMS::RangeMobility im_range_2(1.05); im_range_2.minSpanIfSingular(0.1); IonMobilityScoring::driftScoringMS1Contrast(sptrArr_3, sptrArrMS1_3, transitions, scores, im_range_2, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_); TEST_REAL_SIMILAR(scores.im_ms1_contrast_coelution, 1) TEST_REAL_SIMILAR(scores.im_ms1_contrast_shape, 0) TEST_REAL_SIMILAR(scores.im_ms1_sum_contrast_coelution, 1) TEST_REAL_SIMILAR(scores.im_ms1_sum_contrast_shape, 0) // deal with one zero transitions dia_extract_window_ = 0.3; //Im Span from 1.0 to 1.3 OpenMS::RangeMobility im_range_3(1.15); im_range_3.minSpanIfSingular(0.3); IonMobilityScoring::driftScoringMS1Contrast(sptrArr_3, sptrArrMS1_3, transitions, scores, im_range_3, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_); TEST_REAL_SIMILAR(scores.im_ms1_contrast_coelution, 3) TEST_REAL_SIMILAR(scores.im_ms1_contrast_shape, 0) TEST_REAL_SIMILAR(scores.im_ms1_sum_contrast_coelution, 3) TEST_REAL_SIMILAR(scores.im_ms1_sum_contrast_shape, 0) // deal with all-zero transitions // IM span from 2.5 to 3.5 OpenMS::RangeMobility im_range_4(3.); im_range_4.minSpanIfSingular(1.); IonMobilityScoring::driftScoringMS1Contrast(sptrArr_3, sptrArrMS1_3, transitions, scores, im_range_4, dia_extract_window_, dia_extraction_ppm_, im_drift_extra_pcnt_); TEST_REAL_SIMILAR(scores.im_ms1_contrast_coelution, 0) TEST_EQUAL(std::isnan(scores.im_ms1_contrast_shape), true) TEST_REAL_SIMILAR(scores.im_ms1_sum_contrast_coelution, 0) TEST_EQUAL(std::isnan(scores.im_ms1_sum_contrast_shape), true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Arrow_test.cpp
.cpp
8,332
348
#include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <arrow/api.h> #include <arrow/csv/api.h> #include <arrow/io/api.h> #include <arrow/ipc/api.h> #include <parquet/arrow/reader.h> #include <parquet/arrow/writer.h> #include <iostream> #include <vector> #include <memory> #include <arrow/status.h> #include <arrow/csv/reader.h> using namespace OpenMS; //example code used here can be found at: https://arrow.apache.org/docs/cpp/tutorials/io_tutorial.html static ::arrow::Status GenInitialFile() { // Make a couple 8-bit integer arrays and a 16-bit integer array -- just like // basic Arrow example. arrow::Int8Builder int8builder; int8_t days_raw[5] = {1, 12, 17, 23, 28}; ARROW_RETURN_NOT_OK(int8builder.AppendValues(days_raw, 5)); std::shared_ptr<arrow::Array> days; ARROW_ASSIGN_OR_RAISE(days, int8builder.Finish()); int8_t months_raw[5] = {1, 3, 5, 7, 1}; ARROW_RETURN_NOT_OK(int8builder.AppendValues(months_raw, 5)); std::shared_ptr<arrow::Array> months; ARROW_ASSIGN_OR_RAISE(months, int8builder.Finish()); arrow::Int16Builder int16builder; int16_t years_raw[5] = {1990, 2000, 1995, 2000, 1995}; ARROW_RETURN_NOT_OK(int16builder.AppendValues(years_raw, 5)); std::shared_ptr<arrow::Array> years; ARROW_ASSIGN_OR_RAISE(years, int16builder.Finish()); // Get a vector of our Arrays std::vector<std::shared_ptr<arrow::Array>> columns = {days, months, years}; // Make a schema to initialize the Table with std::shared_ptr<arrow::Field> field_day, field_month, field_year; std::shared_ptr<arrow::Schema> schema; field_day = arrow::field("Day", arrow::int8()); field_month = arrow::field("Month", arrow::int8()); field_year = arrow::field("Year", arrow::int16()); schema = arrow::schema({field_day, field_month, field_year}); // With the schema and data, create a Table std::shared_ptr<arrow::Table> table; table = arrow::Table::Make(schema, columns); // Write out test files in IPC, CSV, and Parquet for the example to use. std::shared_ptr<arrow::io::FileOutputStream> outfile; ARROW_ASSIGN_OR_RAISE(outfile, arrow::io::FileOutputStream::Open("test_in.arrow")); ARROW_ASSIGN_OR_RAISE(std::shared_ptr<arrow::ipc::RecordBatchWriter> ipc_writer, arrow::ipc::MakeFileWriter(outfile, schema)); ARROW_RETURN_NOT_OK(ipc_writer->WriteTable(*table)); ARROW_RETURN_NOT_OK(ipc_writer->Close()); ARROW_ASSIGN_OR_RAISE(outfile, arrow::io::FileOutputStream::Open("test_in.csv")); ARROW_ASSIGN_OR_RAISE(auto csv_writer, arrow::csv::MakeCSVWriter(outfile, table->schema())); ARROW_RETURN_NOT_OK(csv_writer->WriteTable(*table)); ARROW_RETURN_NOT_OK(csv_writer->Close()); ARROW_ASSIGN_OR_RAISE(outfile, arrow::io::FileOutputStream::Open("test_in.parquet")); PARQUET_THROW_NOT_OK( parquet::arrow::WriteTable(*table, arrow::default_memory_pool(), outfile, 5)); return ::arrow::Status::OK(); } static ::arrow::Status RunMain() { // (Doc section: RunMain) // (Doc section: Gen Files) // Generate initial files for each format with a helper function -- don't worry, // we'll also write a table in this example. ARROW_RETURN_NOT_OK(GenInitialFile()); //adapted a bit to the test std::shared_ptr<arrow::io::ReadableFile> infile; // (Doc section: ReadableFile Definition) // (Doc section: Arrow ReadableFile Open) // Get "test_in.arrow" into our file pointer ARROW_ASSIGN_OR_RAISE(infile, arrow::io::ReadableFile::Open( "test_in.arrow", arrow::default_memory_pool())); // (Doc section: Arrow ReadableFile Open) // (Doc section: Arrow Read Open) // Open up the file with the IPC features of the library, gives us a reader object. ARROW_ASSIGN_OR_RAISE(auto ipc_reader, arrow::ipc::RecordBatchFileReader::Open(infile)); // (Doc section: Arrow Read Open) // (Doc section: Arrow Read) // Using the reader, we can read Record Batches. Note that this is specific to IPC; // for other formats, we focus on Tables, but here, RecordBatches are used. std::shared_ptr<arrow::RecordBatch> rbatch; ARROW_ASSIGN_OR_RAISE(rbatch, ipc_reader->ReadRecordBatch(0)); // (Doc section: Arrow Read) // (Doc section: Arrow Write Open) // Just like with input, we get an object for the output file. std::shared_ptr<arrow::io::FileOutputStream> outfile; // Bind it to "test_out.arrow" ARROW_ASSIGN_OR_RAISE(outfile, arrow::io::FileOutputStream::Open("test_out.arrow")); // (Doc section: Arrow Write Open) // (Doc section: Arrow Writer) // Set up a writer with the output file -- and the schema! We're defining everything // here, loading to fire. ARROW_ASSIGN_OR_RAISE(std::shared_ptr<arrow::ipc::RecordBatchWriter> ipc_writer, arrow::ipc::MakeFileWriter(outfile, rbatch->schema())); // (Doc section: Arrow Writer) // (Doc section: Arrow Write) // Write the record batch. ARROW_RETURN_NOT_OK(ipc_writer->WriteRecordBatch(*rbatch)); // (Doc section: Arrow Write) // (Doc section: Arrow Close) // Specifically for IPC, the writer needs to be explicitly closed. ARROW_RETURN_NOT_OK(ipc_writer->Close()); // (Doc section: Arrow Close) // (Doc section: CSV Read Open) // Bind our input file to "test_in.csv" ARROW_ASSIGN_OR_RAISE(infile, arrow::io::ReadableFile::Open("test_in.csv")); // (Doc section: CSV Read Open) // (Doc section: CSV Table Declare) std::shared_ptr<arrow::Table> csv_table; // (Doc section: CSV Table Declare) // (Doc section: CSV Reader Make) // The CSV reader has several objects for various options. For now, we'll use defaults. ARROW_ASSIGN_OR_RAISE( auto csv_reader, arrow::csv::TableReader::Make( arrow::io::default_io_context(), infile, arrow::csv::ReadOptions::Defaults(), arrow::csv::ParseOptions::Defaults(), arrow::csv::ConvertOptions::Defaults())); // (Doc section: CSV Reader Make) // (Doc section: CSV Read) // Read the table. ARROW_ASSIGN_OR_RAISE(csv_table, csv_reader->Read()) // (Doc section: CSV Read) // (Doc section: CSV Write) // Bind our output file to "test_out.csv" ARROW_ASSIGN_OR_RAISE(outfile, arrow::io::FileOutputStream::Open("test_out.csv")); // The CSV writer has simpler defaults, review API documentation for more complex usage. ARROW_ASSIGN_OR_RAISE(auto csv_writer, arrow::csv::MakeCSVWriter(outfile, csv_table->schema())); ARROW_RETURN_NOT_OK(csv_writer->WriteTable(*csv_table)); // Not necessary, but a safe practice. ARROW_RETURN_NOT_OK(csv_writer->Close()); // (Doc section: CSV Write) // (Doc section: Parquet Read Open) // Bind our input file to "test_in.parquet" ARROW_ASSIGN_OR_RAISE(infile, arrow::io::ReadableFile::Open("test_in.parquet")); // (Doc section: Parquet Read Open) // (Doc section: Parquet FileReader) std::unique_ptr<parquet::arrow::FileReader> reader; // (Doc section: Parquet FileReader) // (Doc section: Parquet OpenFile) // Note that Parquet's OpenFile() takes the reader by reference, rather than returning // a reader. PARQUET_ASSIGN_OR_THROW(reader, parquet::arrow::OpenFile(infile, arrow::default_memory_pool())); // (Doc section: Parquet OpenFile) // (Doc section: Parquet Read) std::shared_ptr<arrow::Table> parquet_table; // Read the table. PARQUET_THROW_NOT_OK(reader->ReadTable(&parquet_table)); // (Doc section: Parquet Read) // (Doc section: Parquet Write) // Parquet writing does not need a declared writer object. Just get the output // file bound, then pass in the table, memory pool, output, and chunk size for // breaking up the Table on-disk. ARROW_ASSIGN_OR_RAISE(outfile, arrow::io::FileOutputStream::Open("test_out.parquet")); PARQUET_THROW_NOT_OK(parquet::arrow::WriteTable( *parquet_table, arrow::default_memory_pool(), outfile, 5)); // (Doc section: Parquet Write) // (Doc section: Return) return ::arrow::Status::OK(); } START_TEST(Arrow, "$Id$") START_SECTION(GenInitialFile()) { TEST_EQUAL(GenInitialFile().ok(), true) } END_SECTION START_SECTION(RunMain()) { TEST_EQUAL(RunMain().ok(), true) } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IMSAlphabetParser_test.cpp
.cpp
2,543
110
// 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/IMSAlphabetParser.h> /////////////////////////// using namespace OpenMS; using namespace ims; using namespace std; class IMSAlphabetParserImpl : public IMSAlphabetParser<> { private: ContainerType elements_; public: ContainerType& getElements() override { return elements_; } void parse(std::istream& ) override { // ignore istream, just enter something into the map elements_.insert(std::make_pair("A", 71.03711)); elements_.insert(std::make_pair("R", 156.10111)); } }; START_TEST(IMSAlphabetParser, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // this is an abstract class, that only provides the load method // it cannot be instanciated so it cannot be tested, therefor we // test the implementation from above IMSAlphabetParser<>* ptr = nullptr; IMSAlphabetParser<>* null_ptr = nullptr; START_SECTION(IMSAlphabetParser()) { ptr = new IMSAlphabetParserImpl(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~IMSAlphabetParser()) { delete ptr; } END_SECTION IMSAlphabetParser<> * parser = new IMSAlphabetParserImpl(); START_SECTION((void load(const std::string &fname))) { TEST_EXCEPTION(Exception::IOException ,parser->load("")) String filename; NEW_TMP_FILE(filename) // just create the file ofstream of; of.open(filename.c_str()); of << "just text" << std::endl; of.close(); parser->load(filename); TEST_EQUAL(parser->getElements().empty(), false) } END_SECTION START_SECTION((virtual ContainerType& getElements())) { TEST_EQUAL(parser->getElements().size(), 2) TEST_REAL_SIMILAR(parser->getElements()["A"], 71.03711) TEST_REAL_SIMILAR(parser->getElements()["R"], 156.10111) } END_SECTION START_SECTION((virtual void parse(InputSource &is))) { // already tested by load NOT_TESTABLE } END_SECTION delete parser; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/EDTAFile_test.cpp
.cpp
3,656
136
// 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/EDTAFile.h> /////////////////////////// #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/KERNEL/ConsensusMap.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> using namespace OpenMS; using namespace std; START_TEST(EDTAFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// EDTAFile* ptr = nullptr; EDTAFile* null_ptr = nullptr; START_SECTION(EDTAFile()) { ptr = new EDTAFile(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(virtual ~EDTAFile()) { delete ptr; } END_SECTION START_SECTION(void load(const String &filename, ConsensusMap &consensus_map)) { EDTAFile f; ConsensusMap fm; f.load(OPENMS_GET_TEST_DATA_PATH("EDTAFile_test_1.edta"), fm); TEST_EQUAL(fm.size(),2) ABORT_IF(fm.size()!=2) TEST_EQUAL(fm[0].getRT(), 321) TEST_EQUAL(fm[0].getMZ(), 405.233) TEST_EQUAL(fm[0].getIntensity(), 24543534) TEST_EQUAL(fm[0].getCharge(), 2) TEST_EQUAL(String(fm[0].getMetaValue("mymeta")), String("lala")) TEST_EQUAL(fm[1].getRT(), 322) TEST_EQUAL(fm[1].getMZ(), 406.207) TEST_EQUAL(fm[1].getIntensity(), 4343344) TEST_EQUAL(fm[1].getCharge(), 3) TEST_EQUAL(String(fm[1].getMetaValue("mymeta")), String("blubb")) f.load(OPENMS_GET_TEST_DATA_PATH("EDTAFile_test_3.edta"), fm); TEST_EQUAL(fm.size(),3) TEST_EXCEPTION(Exception::ParseError, f.load(OPENMS_GET_TEST_DATA_PATH("EDTAFile_test_2.edta"), fm)); TEST_EXCEPTION(Exception::FileNotFound, f.load(OPENMS_GET_TEST_DATA_PATH("EDTAFile_test_3_doesnotexist.edta"), fm)); } END_SECTION START_SECTION((void store(const String& filename, const ConsensusMap& map) const)) { EDTAFile f; ConsensusMap cm; f.load(OPENMS_GET_TEST_DATA_PATH("EDTAFile_test_4.edta"), cm); String outfile; NEW_TMP_FILE(outfile) f.store(outfile, cm); ConsensusMap cm2; f.load(outfile, cm2); TEST_EQUAL(cm.size(),cm2.size()) ABORT_IF(cm.size()!=cm2.size()) for (Size i=0; i< cm.size(); ++i) { TEST_REAL_SIMILAR(cm[i].getRT(), cm2[i].getRT()) TEST_REAL_SIMILAR(cm[i].getMZ(), cm2[i].getMZ()) TEST_REAL_SIMILAR(cm[i].getIntensity(), cm2[i].getIntensity()) TEST_EQUAL(cm[i].getCharge(), cm2[i].getCharge()) TEST_EQUAL(cm[i].getFeatures().size(), cm2[i].getFeatures().size()) // cannot test for metavalues, since they are not written to EDTA (yet) } } END_SECTION START_SECTION((void store(const String& filename, const FeatureMap& map) const)) { FeatureMap fm; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("EDTAFile_test_out_1.featureXML"), fm); EDTAFile f; String outfile; NEW_TMP_FILE(outfile) f.store(outfile, fm); ConsensusMap cm; f.load(outfile, cm); TEST_EQUAL(fm.size(), cm.size()); ABORT_IF(fm.size() != cm.size()); for (Size i=0; i< fm.size(); ++i) { TEST_REAL_SIMILAR(fm[i].getRT(), cm[i].getRT()) TEST_REAL_SIMILAR(fm[i].getMZ(), cm[i].getMZ()) TEST_REAL_SIMILAR(fm[i].getIntensity(), cm[i].getIntensity()) } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CubicSpline2d_test.cpp
.cpp
4,693
148
// 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/MATH/MISC/CubicSpline2d.h> using namespace OpenMS; START_TEST(CubicSpline2d, "$Id$") std::vector<double> mz; mz.push_back(486.784); mz.push_back(486.787); mz.push_back(486.790); mz.push_back(486.793); mz.push_back(486.795); mz.push_back(486.797); mz.push_back(486.800); mz.push_back(486.802); mz.push_back(486.805); mz.push_back(486.808); mz.push_back(486.811); std::vector<double> intensity; intensity.push_back(0.0); intensity.push_back(154683.17); intensity.push_back(620386.5); intensity.push_back(1701390.12); intensity.push_back(2848879.25); intensity.push_back(3564045.5); intensity.push_back(2744585.7); intensity.push_back(1605583.0); intensity.push_back(1518984.0); intensity.push_back(1591352.21); intensity.push_back(1691345.1); double x_min = -0.5; double x_max = 1.5; Size n = 10; std::vector<double> x; std::vector<double> y; for (Size i=0; i<(n+1); ++i) { x.push_back(x_min + (double)i/10*(x_max-x_min)); y.push_back(sin(x_min + (double)i/10*(x_max-x_min))); } std::map<double,double> mz_intensity; for (Size i=0; i<mz.size(); ++i) { mz_intensity.insert(std::pair<double,double>(mz[i], intensity[i])); } std::map<double,double> x_y; for (Size i=0; i<x.size(); ++i) { x_y.insert(std::pair<double,double>(x[i], y[i])); } CubicSpline2d sp1(mz, intensity); CubicSpline2d sp2(mz_intensity); CubicSpline2d sp5(x, y); CubicSpline2d sp6(x_y); CubicSpline2d* nullPointer = nullptr; START_SECTION(CubicSpline2d(const std::vector<double>& x, const std::vector<double>& y)) CubicSpline2d* sp3 = new CubicSpline2d(mz, intensity); TEST_NOT_EQUAL(sp3, nullPointer) delete sp3; END_SECTION START_SECTION(CubicSpline2d(const std::map<double, double>& m)) CubicSpline2d* sp4 = new CubicSpline2d(mz_intensity); TEST_NOT_EQUAL(sp4, nullPointer) delete sp4; END_SECTION START_SECTION(double eval(double x)) // near border of spline range TEST_REAL_SIMILAR(sp1.eval(486.785), 35173.1841778984); TEST_REAL_SIMILAR(sp2.eval(486.785), 35173.1841778984); // inside spline range TEST_REAL_SIMILAR(sp1.eval(486.794), 2271426.93316241); TEST_REAL_SIMILAR(sp2.eval(486.794), 2271426.93316241); // at the input nodes TEST_REAL_SIMILAR(sp1.eval(486.784), 0.0); TEST_REAL_SIMILAR(sp1.eval(486.790), 620386.5); TEST_REAL_SIMILAR(sp2.eval(486.808), 1591352.21); TEST_REAL_SIMILAR(sp2.eval(486.811), 1691345.1); // test sine at nodes for (Size i=0; i<(n+1); ++i) { TEST_REAL_SIMILAR(sp5.eval(x[i]), y[i]); TEST_REAL_SIMILAR(sp6.eval(x[i]), y[i]); } // test sine between nodes // The cubic spline is a third order approximation of the (co)sines. TOLERANCE_RELATIVE(1.005); for (Size i=0; i<(n+6); ++i) { double xx = x_min + (double)i/(n+5)*(x_max-x_min); TEST_REAL_SIMILAR(sp5.eval(xx), sin(xx)); TEST_REAL_SIMILAR(sp6.eval(xx), sin(xx)); } END_SECTION START_SECTION(double derivatives(double x, unsigned order)) // near border of spline range TEST_REAL_SIMILAR(sp1.derivatives(486.785,1), 39270152.2996247) TEST_REAL_SIMILAR(sp1.derivatives(486.785,2), 12290904368.2736); TEST_REAL_SIMILAR(sp2.derivatives(486.785,1), 39270152.2996247); TEST_REAL_SIMILAR(sp2.derivatives(486.785,2), 12290904368.2736); // inside spline range TEST_REAL_SIMILAR(sp1.derivatives(486.794,1), 594825947.154264); TEST_REAL_SIMILAR(sp1.derivatives(486.794,2), 7415503644.8958); TEST_REAL_SIMILAR(sp2.derivatives(486.794,1), 594825947.154264); TEST_REAL_SIMILAR(sp2.derivatives(486.794,2), 7415503644.8958); // test cosine at nodes // No tests near boundaries, since deviation from cos(x) large and expected. TOLERANCE_RELATIVE(1.01); for (Size i=2; i<n-1; ++i) { TEST_REAL_SIMILAR(sp5.derivatives(x[i],1), cos(x[i])); TEST_REAL_SIMILAR(sp6.derivatives(x[i],1), cos(x[i])); } // test cosine between nodes for (Size i=2; i<(n+4); ++i) { double xx = x_min + (double)i/(n+5)*(x_max-x_min); TEST_REAL_SIMILAR(sp5.derivatives(xx,1), cos(xx)); TEST_REAL_SIMILAR(sp6.derivatives(xx,1), cos(xx)); } // test boundary conditions y"=0 TEST_REAL_SIMILAR(sp5.derivatives(x[0],2), 0); TEST_REAL_SIMILAR(sp6.derivatives(x[0],2), 0); TEST_REAL_SIMILAR(sp5.derivatives(x[n],2), 0); TEST_REAL_SIMILAR(sp6.derivatives(x[n],2), 0); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/InspectInfile_test.cpp
.cpp
13,832
369
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Martin Langwisch $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/InspectInfile.h> #include <iostream> #include <vector> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(InspectInfile, "$Id$") ///////////////////////////////////////////////////////////// InspectInfile* ptr = nullptr; InspectInfile* nullPointer = nullptr; START_SECTION(InspectInfile()) ptr = new InspectInfile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~InspectInfile()) delete ptr; END_SECTION START_SECTION((InspectInfile& operator=(const InspectInfile &inspect_infile))) InspectInfile inspect_infile1; inspect_infile1.setSpectra("dummy"); InspectInfile inspect_infile2 = inspect_infile1; InspectInfile inspect_infile3; inspect_infile3.setSpectra("dummy"); inspect_infile1 = InspectInfile(); TEST_EQUAL(( inspect_infile2 == inspect_infile3 ), true) InspectInfile inspect_infile4; TEST_EQUAL(( inspect_infile1 == inspect_infile4 ), true) END_SECTION START_SECTION((InspectInfile(const InspectInfile &inspect_infile))) InspectInfile inspect_infile1; inspect_infile1.setSpectra("dummy"); InspectInfile inspect_infile2(inspect_infile1); InspectInfile inspect_infile3; inspect_infile3.setSpectra("dummy"); inspect_infile1 = InspectInfile(); TEST_EQUAL(( inspect_infile2 == inspect_infile3 ), true) InspectInfile inspect_infile4; TEST_EQUAL(( inspect_infile1 == inspect_infile4 ), true) END_SECTION START_SECTION((bool operator==(const InspectInfile &inspect_infile) const)) InspectInfile inspect_infile1; inspect_infile1.setSpectra("dummy"); InspectInfile inspect_infile2; inspect_infile2.setSpectra("dummy"); TEST_EQUAL(( inspect_infile1 == inspect_infile2 ), true) END_SECTION InspectInfile file; START_SECTION(void setSpectra(const String& spectra)) file.setSpectra("dummy4712"); TEST_STRING_EQUAL(file.getSpectra(), "dummy4712") END_SECTION START_SECTION((const String& getSpectra() const)) TEST_STRING_EQUAL(file.getSpectra(), "dummy4712") END_SECTION START_SECTION(void setDb(const String& db)) file.setDb("dummy4711"); TEST_STRING_EQUAL(file.getDb(), "dummy4711"); END_SECTION START_SECTION((const String& getDb() const)) TEST_STRING_EQUAL(file.getDb(), "dummy4711"); END_SECTION START_SECTION(void setEnzyme(const String& enzyme)) file.setEnzyme("Trypsin"); TEST_STRING_EQUAL(file.getEnzyme(), "Trypsin") END_SECTION START_SECTION((const String& getEnzyme() const)) TEST_STRING_EQUAL(file.getEnzyme(), "Trypsin") END_SECTION START_SECTION(void handlePTMs(const String& modification_line, const String& modifications_filename, const bool monoisotopic)) // test exceptions String modification_line = "Phosphorylation"; TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.handlePTMs(modification_line, "a", true), "the file 'a' could not be found") // TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotReadable, file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Inspect_unreadable_unwriteable.txt"), true), "the file `data/Inspect_unreadable_unwriteable.txt' is not readable for the current user") modification_line = "2H20,KRLNH,fix"; TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Inspect_PTMs.xml"), true), "There's something wrong with this modification. Aborting! in: 2H20,KRLNH,fix") modification_line = "10.3+"; TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Inspect_PTMs.xml"), true), "No residues for modification given. Aborting! in: 10.3+") modification_line = "10.3+,KRLNH,stat,PTM_0"; TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Inspect_PTMs.xml"), true), "There's something wrong with the type of this modification. Aborting! in: 10.3+,KRLNH,stat,PTM_0") modification_line = "Phosphorylation:Phosphorylation"; TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Inspect_PTMs.xml"), true), "There's already a modification with this name. Aborting! in: Phosphorylation") // test the actual program modification_line = "10.3+,KRLNH,fix:+16,C:16-,cterm:-16,nterm"; // "10.3+,KRLNH,fix:Phosphorylation:+16,C:HCNO,nterm,Carbamylation:H2C,CHKNQRILDEST,opt,Methylation:16-,cterm:-16,nterm"; // average masses file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Inspect_PTMs.xml"), false); map< String, vector< String > > modifications; modifications["PTM_0"] = vector< String >(3); modifications["PTM_0"][0] = "KRLNH"; modifications["PTM_0"][1] = "10.3"; modifications["PTM_0"][2] = "FIX"; // modifications["Phosphorylation"] = vector< String >(3); // modifications["Phosphorylation"][0] = "STYDHCR"; // modifications["Phosphorylation"][1] = "79.97990"; // modifications["Phosphorylation"][2] = "OPT"; modifications["PTM_1"] = vector< String >(3); modifications["PTM_1"][0] = "C"; modifications["PTM_1"][1] = "16"; modifications["PTM_1"][2] = "OPT"; // modifications["Carbamylation"] = vector< String >(3); // modifications["Carbamylation"][0] = "NTERM"; // modifications["Carbamylation"][1] = "43.02474"; // modifications["Carbamylation"][2] = "OPT"; // modifications["Methylation"] = vector< String >(3); // modifications["Methylation"][0] = "CHKNQRILDEST"; // modifications["Methylation"][1] = "14.02658"; // modifications["Methylation"][2] = "OPT"; // modifications["PTM_5"] = vector< String >(3); // modifications["PTM_5"][0] = "CTERM"; // modifications["PTM_5"][1] = "-16"; // modifications["PTM_5"][2] = "OPT"; // modifications["PTM_6"] = vector< String >(3); // modifications["PTM_6"][0] = "NTERM"; // modifications["PTM_6"][1] = "-16"; // modifications["PTM_6"][2] = "OPT"; modifications["PTM_2"] = vector< String >(3); modifications["PTM_2"][0] = "CTERM"; modifications["PTM_2"][1] = "-16"; modifications["PTM_2"][2] = "OPT"; modifications["PTM_3"] = vector< String >(3); modifications["PTM_3"][0] = "NTERM"; modifications["PTM_3"][1] = "-16"; modifications["PTM_3"][2] = "OPT"; map< String, vector< String > >::const_iterator result_mod_i = file.getModifications().begin(); TEST_EQUAL(file.getModifications().size(), modifications.size()) if ( file.getModifications().size() == modifications.size() ) { for ( map< String, vector< String > >::const_iterator mod_i = modifications.begin(); mod_i != modifications.end(); ++mod_i, ++result_mod_i ) { TEST_STRING_EQUAL(result_mod_i->first, mod_i->first) TEST_EQUAL(result_mod_i->second.size(), 3) TEST_EQUAL(result_mod_i->second.size(), mod_i->second.size()) if ( result_mod_i->second.size() == mod_i->second.size() ) { TEST_STRING_EQUAL(result_mod_i->second[0], mod_i->second[0]) TEST_STRING_EQUAL(result_mod_i->second[1], mod_i->second[1]) TEST_STRING_EQUAL(result_mod_i->second[2], mod_i->second[2]) } } } // monoisotopic masses file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Inspect_PTMs.xml"), true); // modifications["Phosphorylation"][1] = "79.96635"; // modifications["Carbamylation"][1] = "43.00582"; // modifications["Methylation"][1] = "14.01565"; result_mod_i = file.getModifications().begin(); TEST_EQUAL(file.getModifications().size(), modifications.size()) if ( file.getModifications().size() == modifications.size() ) { for ( map< String, vector< String > >::const_iterator mod_i = modifications.begin(); mod_i != modifications.end(); ++mod_i, ++result_mod_i ) { TEST_STRING_EQUAL(result_mod_i->first, mod_i->first) TEST_EQUAL(result_mod_i->second.size(), 3) TEST_EQUAL(result_mod_i->second.size(), mod_i->second.size()) if ( result_mod_i->second.size() == mod_i->second.size() ) { TEST_STRING_EQUAL(result_mod_i->second[0], mod_i->second[0]) TEST_STRING_EQUAL(result_mod_i->second[2], mod_i->second[2]) } } } END_SECTION START_SECTION((const Map< String, std::vector< String > >& getModifications() const)) String modification_line = "10.3+,KRLNH,fix:+16,C:16-,cterm:-16,nterm"; // "10.3+,KRLNH,fix:Phosphorylation:+16,C:HCNO,nterm,Carbamylation:H2C,CHKNQRILDEST,opt,Methylation:16-,cterm:-16,nterm"; // average masses file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Inspect_PTMs.xml"), false); map< String, vector< String > > modifications; modifications["PTM_0"] = vector< String >(3); modifications["PTM_0"][0] = "KRLNH"; modifications["PTM_0"][1] = "10.3"; modifications["PTM_0"][2] = "FIX"; // modifications["Phosphorylation"] = vector< String >(3); // modifications["Phosphorylation"][0] = "STYDHCR"; // modifications["Phosphorylation"][1] = "79.97990"; // modifications["Phosphorylation"][2] = "OPT"; modifications["PTM_1"] = vector< String >(3); modifications["PTM_1"][0] = "C"; modifications["PTM_1"][1] = "16"; modifications["PTM_1"][2] = "OPT"; // modifications["Carbamylation"] = vector< String >(3); // modifications["Carbamylation"][0] = "NTERM"; // modifications["Carbamylation"][1] = "43.02474"; // modifications["Carbamylation"][2] = "OPT"; // modifications["Methylation"] = vector< String >(3); // modifications["Methylation"][0] = "CHKNQRILDEST"; // modifications["Methylation"][1] = "14.02658"; // modifications["Methylation"][2] = "OPT"; // modifications["PTM_5"] = vector< String >(3); // modifications["PTM_5"][0] = "CTERM"; // modifications["PTM_5"][1] = "-16"; // modifications["PTM_5"][2] = "OPT"; // modifications["PTM_6"] = vector< String >(3); // modifications["PTM_6"][0] = "NTERM"; // modifications["PTM_6"][1] = "-16"; // modifications["PTM_6"][2] = "OPT"; modifications["PTM_2"] = vector< String >(3); modifications["PTM_2"][0] = "CTERM"; modifications["PTM_2"][1] = "-16"; modifications["PTM_2"][2] = "OPT"; modifications["PTM_3"] = vector< String >(3); modifications["PTM_3"][0] = "NTERM"; modifications["PTM_3"][1] = "-16"; modifications["PTM_3"][2] = "OPT"; map< String, vector< String > >::const_iterator result_mod_i = file.getModifications().begin(); TEST_EQUAL(file.getModifications().size(), modifications.size()) if ( file.getModifications().size() == modifications.size() ) { for ( map< String, vector< String > >::const_iterator mod_i = modifications.begin(); mod_i != modifications.end(); ++mod_i, ++result_mod_i ) { TEST_STRING_EQUAL(result_mod_i->first, mod_i->first) TEST_EQUAL(result_mod_i->second.size(), 3) TEST_EQUAL(result_mod_i->second.size(), mod_i->second.size()) if ( result_mod_i->second.size() == mod_i->second.size() ) { TEST_STRING_EQUAL(result_mod_i->second[0], mod_i->second[0]) TEST_STRING_EQUAL(result_mod_i->second[1], mod_i->second[1]) TEST_STRING_EQUAL(result_mod_i->second[2], mod_i->second[2]) } } } END_SECTION START_SECTION(void setModificationsPerPeptide(Int modifications_per_peptide)) file.setModificationsPerPeptide(2); TEST_EQUAL(file.getModificationsPerPeptide(), 2) END_SECTION START_SECTION((Int getModificationsPerPeptide() const)) TEST_EQUAL(file.getModificationsPerPeptide(), 2) END_SECTION START_SECTION(void setBlind(UInt blind)) file.setBlind(1); TEST_EQUAL(file.getBlind(), 1) END_SECTION START_SECTION((UInt getBlind() const)) TEST_EQUAL(file.getBlind(), 1) END_SECTION START_SECTION(void setMaxPTMsize(float maxptmsize)) file.setMaxPTMsize(250); TEST_EQUAL(file.getMaxPTMsize(), 250) END_SECTION START_SECTION((float getMaxPTMsize() const)) TEST_EQUAL(file.getMaxPTMsize(), 250) END_SECTION START_SECTION(void setPrecursorMassTolerance(float precursor_mass_tolerance)) file.setPrecursorMassTolerance(1.3f); TEST_REAL_SIMILAR(file.getPrecursorMassTolerance(), 1.3f) END_SECTION START_SECTION((float getPrecursorMassTolerance() const)) TEST_REAL_SIMILAR(file.getPrecursorMassTolerance(), 1.3f) END_SECTION START_SECTION(void setPeakMassTolerance(float peak_mass_tolerance)) file.setPeakMassTolerance(0.3f); TEST_REAL_SIMILAR(file.getPeakMassTolerance(), 0.3f) END_SECTION START_SECTION((float getPeakMassTolerance() const)) TEST_REAL_SIMILAR(file.getPeakMassTolerance(), 0.3f) END_SECTION START_SECTION(void setMulticharge(UInt multicharge)) file.setMulticharge(1); TEST_EQUAL(file.getMulticharge(), 1) END_SECTION START_SECTION((UInt getMulticharge() const)) TEST_EQUAL(file.getMulticharge(), 1) END_SECTION START_SECTION(void setInstrument(const String& instrument)) file.setInstrument("ESI-ION-TRAP"); TEST_STRING_EQUAL(file.getInstrument(), "ESI-ION-TRAP") END_SECTION START_SECTION((const String& getInstrument() const)) TEST_STRING_EQUAL(file.getInstrument(), "ESI-ION-TRAP") END_SECTION START_SECTION(void setTagCount(Int TagCount)) file.setTagCount(1); TEST_EQUAL(file.getTagCount(), 1) END_SECTION START_SECTION((Int getTagCount() const)) TEST_EQUAL(file.getTagCount(), 1) END_SECTION START_SECTION(void store(const String& filename)) String filename; NEW_TMP_FILE(filename) // TEST_EXCEPTION_WITH_MESSAGE(Exception::UnableToCreateFile, file.store(OPENMS_GET_TEST_DATA_PATH("Inspect_unreadable_unwriteable.txt")), "the file `data/Inspect_unreadable_unwriteable.txt' could not be created") file.store(filename); TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("InspectInfile_test_template1.txt")) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ChromatogramSettings_test.cpp
.cpp
15,253
520
// 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/METADATA/ChromatogramSettings.h> /////////////////////////// #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; START_TEST(ChromatogramSettings, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ChromatogramSettings* ptr = nullptr; ChromatogramSettings* nullPointer = nullptr; START_SECTION(ChromatogramSettings()) { ptr = new ChromatogramSettings(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~ChromatogramSettings()) { delete ptr; } END_SECTION START_SECTION((ChromatogramSettings(const ChromatogramSettings &source))) { ChromatogramSettings tmp; tmp.getAcquisitionInfo().setMethodOfCombination("test"); tmp.getInstrumentSettings().getScanWindows().resize(1); tmp.getPrecursor().setMZ(0.11); tmp.getProduct().setMZ(0.12); tmp.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); tmp.setComment("bla"); tmp.setNativeID("nid"); tmp.getDataProcessing().resize(1); tmp.setMetaValue("bla","bluff"); ChromatogramSettings tmp2; tmp2 = tmp; TEST_EQUAL(tmp2.getComment(), "bla"); TEST_EQUAL(tmp2.getChromatogramType(), ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); TEST_REAL_SIMILAR(tmp2.getPrecursor().getMZ(), 0.11); TEST_REAL_SIMILAR(tmp2.getProduct().getMZ(), 0.12); TEST_EQUAL(tmp2.getInstrumentSettings()==InstrumentSettings(), false); TEST_EQUAL(tmp2.getAcquisitionInfo()==AcquisitionInfo(), false); TEST_EQUAL(tmp2.getAcquisitionInfo().empty(), true); TEST_STRING_EQUAL(tmp2.getNativeID(),"nid"); TEST_EQUAL(tmp2.getDataProcessing().size(),1); TEST_STRING_EQUAL(tmp2.getMetaValue("bla"),"bluff"); tmp2 = ChromatogramSettings(); TEST_EQUAL(tmp2.getComment(), ""); TEST_EQUAL(tmp2.getChromatogramType(), ChromatogramSettings::ChromatogramType::MASS_CHROMATOGRAM); TEST_REAL_SIMILAR(tmp2.getPrecursor().getMZ(), 0.0); TEST_REAL_SIMILAR(tmp2.getProduct().getMZ(), 0.0); TEST_EQUAL(tmp2.getInstrumentSettings()==InstrumentSettings(), true); TEST_EQUAL(tmp2.getAcquisitionInfo().empty(), true); TEST_STRING_EQUAL(tmp2.getNativeID(),""); TEST_EQUAL(tmp2.getDataProcessing().size(),0); TEST_EQUAL(tmp2.metaValueExists("bla"),false); } END_SECTION START_SECTION((ChromatogramSettings& operator=(const ChromatogramSettings &source))) { ChromatogramSettings tmp; tmp.setMetaValue("bla","bluff"); tmp.getAcquisitionInfo().setMethodOfCombination("test"); tmp.getInstrumentSettings().getScanWindows().resize(1); tmp.getPrecursor().setMZ(0.13); tmp.getProduct().setMZ(0.14); tmp.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); tmp.setComment("bla"); tmp.setNativeID("nid"); tmp.getDataProcessing().resize(1); ChromatogramSettings tmp2(tmp); TEST_EQUAL(tmp2.getComment(), "bla"); TEST_EQUAL(tmp2.getChromatogramType(), ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); TEST_REAL_SIMILAR(tmp2.getPrecursor().getMZ(), 0.13); TEST_REAL_SIMILAR(tmp2.getProduct().getMZ(), 0.14); TEST_EQUAL(tmp2.getInstrumentSettings()==InstrumentSettings(), false); TEST_EQUAL(tmp2.getAcquisitionInfo()==AcquisitionInfo(), false); TEST_EQUAL(tmp2.getAcquisitionInfo().empty(), true); TEST_STRING_EQUAL(tmp2.getNativeID(),"nid"); TEST_EQUAL(tmp2.getDataProcessing().size(),1); TEST_EQUAL(tmp2.getMetaValue("bla")=="bluff",true); } END_SECTION START_SECTION((bool operator==(const ChromatogramSettings &rhs) const )) { ChromatogramSettings edit, empty; TEST_TRUE(edit == empty); edit.getAcquisitionInfo().setMethodOfCombination("test"); TEST_EQUAL(edit==empty, false); edit = empty; edit.setNativeID("nid"); TEST_EQUAL(edit==empty, false); edit = empty; edit.getInstrumentSettings().getScanWindows().resize(1); TEST_EQUAL(edit==empty, false); edit = empty; edit.setComment("comment"); TEST_EQUAL(edit == empty, false) edit = empty; edit.getPrecursor().setMZ(0.15); TEST_EQUAL(edit==empty, false); edit = empty; edit.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); TEST_EQUAL(edit==empty, false); edit = empty; edit.setComment("bla"); TEST_EQUAL(edit==empty, false); edit = empty; edit.getPrecursor().setMZ(0.16); TEST_EQUAL(edit==empty, false); edit = empty; edit.getProduct().setMZ(0.17); TEST_EQUAL(edit==empty, false); edit = empty; edit.getDataProcessing().resize(1); TEST_EQUAL(edit==empty, false); edit = empty; edit.setMetaValue("bla","bluff"); TEST_EQUAL(edit==empty, false); } END_SECTION START_SECTION((bool operator!=(const ChromatogramSettings &rhs) const )) { ChromatogramSettings edit, empty; TEST_EQUAL(edit!=empty, false); edit.getAcquisitionInfo().setMethodOfCombination("test"); TEST_FALSE(edit == empty); edit = empty; edit.setNativeID("nid"); TEST_FALSE(edit == empty) edit = empty; edit.getInstrumentSettings().getScanWindows().resize(1); TEST_FALSE(edit == empty); edit = empty; edit.setComment("comment"); TEST_FALSE(edit == empty) edit = empty; edit.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); TEST_FALSE(edit == empty); edit = empty; edit.setComment("bla"); TEST_FALSE(edit == empty) edit = empty; Precursor prec; prec.setMZ(1.3); edit.setPrecursor(prec); TEST_FALSE(edit == empty) edit = empty; Product prod; prod.setMZ(1.5); edit.setProduct(prod); TEST_FALSE(edit == empty) edit = empty; edit.getDataProcessing().resize(1); TEST_FALSE(edit == empty) edit = empty; edit.setMetaValue("bla","bluff"); TEST_FALSE(edit == empty) } END_SECTION START_SECTION((const String& getNativeID() const )) { ChromatogramSettings tmp; TEST_STRING_EQUAL(tmp.getNativeID(),"") } END_SECTION START_SECTION((void setNativeID(const String &native_id))) { ChromatogramSettings tmp; tmp.setNativeID("nid"); TEST_STRING_EQUAL(tmp.getNativeID(),"nid") } END_SECTION START_SECTION((const String& getComment() const )) { ChromatogramSettings tmp; TEST_STRING_EQUAL(tmp.getComment(), "") } END_SECTION START_SECTION((void setComment(const String &comment))) { ChromatogramSettings tmp; tmp.setComment("name"); TEST_STRING_EQUAL(tmp.getComment(), "name") } END_SECTION START_SECTION((const InstrumentSettings& getInstrumentSettings() const )) { ChromatogramSettings tmp; TEST_EQUAL(tmp.getInstrumentSettings()==InstrumentSettings(), true); } END_SECTION START_SECTION((InstrumentSettings& getInstrumentSettings())) { ChromatogramSettings tmp; tmp.getInstrumentSettings().getScanWindows().resize(1); TEST_EQUAL(tmp.getInstrumentSettings()==InstrumentSettings(), false); } END_SECTION START_SECTION((void setInstrumentSettings(const InstrumentSettings &instrument_settings))) { ChromatogramSettings tmp; InstrumentSettings is; is.getScanWindows().resize(1); tmp.setInstrumentSettings(is); TEST_EQUAL(tmp.getInstrumentSettings()==InstrumentSettings(), false); } END_SECTION START_SECTION((const AcquisitionInfo& getAcquisitionInfo() const )) { ChromatogramSettings tmp; tmp.getAcquisitionInfo().setMethodOfCombination("test"); TEST_EQUAL(tmp.getAcquisitionInfo()==AcquisitionInfo(), false); TEST_EQUAL(tmp.getAcquisitionInfo().empty(), true); } END_SECTION START_SECTION((AcquisitionInfo& getAcquisitionInfo())) { ChromatogramSettings tmp; TEST_EQUAL(tmp.getAcquisitionInfo().empty(), true); } END_SECTION START_SECTION((void setAcquisitionInfo(const AcquisitionInfo &acquisition_info))) { ChromatogramSettings tmp; AcquisitionInfo ai; ai.setMethodOfCombination("test"); tmp.setAcquisitionInfo(ai); TEST_EQUAL(tmp.getAcquisitionInfo()==AcquisitionInfo(), false); TEST_EQUAL(tmp.getAcquisitionInfo().empty(), true); } END_SECTION START_SECTION((const SourceFile& getSourceFile() const )) { ChromatogramSettings tmp; TEST_EQUAL(tmp.getInstrumentSettings()==InstrumentSettings(), true); } END_SECTION START_SECTION((SourceFile& getSourceFile())) { ChromatogramSettings tmp; TEST_EQUAL(tmp.getSourceFile()==SourceFile(), true); } END_SECTION START_SECTION((void setSourceFile(const SourceFile &source_file))) { ChromatogramSettings tmp; SourceFile sf; sf.setNameOfFile("test"); tmp.setSourceFile(sf); TEST_EQUAL(tmp.getSourceFile()==SourceFile(), false); } END_SECTION START_SECTION((const Precursor& getPrecursor() const )) { ChromatogramSettings tmp; TEST_EQUAL(tmp.getPrecursor() == Precursor(), true) } END_SECTION START_SECTION((Precursor& getPrecursor())) { ChromatogramSettings tmp; tmp.getPrecursor().setMZ(0.3); TEST_EQUAL(tmp.getPrecursor() == Precursor(), false) TEST_REAL_SIMILAR(tmp.getPrecursor().getMZ(), 0.3) } END_SECTION START_SECTION((void setPrecursor(const Precursor &precursor))) { ChromatogramSettings tmp; Precursor prec; prec.setMZ(0.4); tmp.setPrecursor(prec); TEST_EQUAL(tmp.getPrecursor() == Precursor(), false) TEST_REAL_SIMILAR(tmp.getPrecursor().getMZ(), 0.4) } END_SECTION START_SECTION((const Product& getProduct() const )) { ChromatogramSettings tmp; TEST_EQUAL(tmp.getProduct() == Product(), true) } END_SECTION START_SECTION((Product& getProduct())) { ChromatogramSettings tmp; tmp.getProduct().setMZ(0.3); TEST_EQUAL(tmp.getProduct() == Product(), false) TEST_REAL_SIMILAR(tmp.getProduct().getMZ(), 0.3) } END_SECTION START_SECTION((void setProduct(const Product &product))) { ChromatogramSettings tmp; Product prod; prod.setMZ(0.4); tmp.setProduct(prod); TEST_EQUAL(tmp.getProduct() == Product(), false) TEST_REAL_SIMILAR(tmp.getProduct().getMZ(), 0.4) } END_SECTION START_SECTION((const std::vector<DataProcessing>& getDataProcessing() const )) { ChromatogramSettings tmp; TEST_EQUAL(tmp.getDataProcessing().size(),0); } END_SECTION START_SECTION((std::vector<DataProcessing>& getDataProcessing())) { ChromatogramSettings tmp; DataProcessingPtr dp = std::shared_ptr<DataProcessing>(new DataProcessing); tmp.getDataProcessing().push_back(dp); TEST_EQUAL(tmp.getDataProcessing().size(),1); } END_SECTION START_SECTION((void setDataProcessing(const std::vector< DataProcessing > &data_processing))) { ChromatogramSettings tmp; std::vector<DataProcessingPtr > dummy; dummy.resize(1); tmp.setDataProcessing(dummy); TEST_EQUAL(tmp.getDataProcessing().size(),1); } END_SECTION START_SECTION((ChromatogramType getChromatogramType() const )) { ChromatogramSettings tmp; TEST_EQUAL(tmp.getChromatogramType(), ChromatogramSettings::ChromatogramType::MASS_CHROMATOGRAM) } END_SECTION START_SECTION((void setChromatogramType(ChromatogramType type))) { ChromatogramSettings tmp; tmp.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); TEST_EQUAL(tmp.getChromatogramType(), ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM) } END_SECTION START_SECTION([EXTRA](ENUMs)) { // extra stuff tested here: TEST_EQUAL(static_cast<size_t>(ChromatogramSettings::ChromatogramType::SIZE_OF_CHROMATOGRAM_TYPE)+1, sizeof( ChromatogramSettings::ChromatogramNames ) / sizeof( char* )) TEST_EQUAL(String(ChromatogramSettings::ChromatogramNames[static_cast<size_t>(ChromatogramSettings::ChromatogramType::MASS_CHROMATOGRAM)]), String("mass chromatogram")) TEST_EQUAL(String(ChromatogramSettings::ChromatogramNames[static_cast<size_t>(ChromatogramSettings::ChromatogramType::EMISSION_CHROMATOGRAM)]), String("emission chromatogram")) TEST_EQUAL(String(ChromatogramSettings::ChromatogramNames[static_cast<size_t>(ChromatogramSettings::ChromatogramType::SIZE_OF_CHROMATOGRAM_TYPE)]), String("unknown chromatogram")) // should be the last entry } END_SECTION START_SECTION([EXTRA] std::hash<ChromatogramSettings>) { std::hash<ChromatogramSettings> hasher; // Test that equal objects have equal hashes ChromatogramSettings cs1, cs2; TEST_EQUAL(cs1 == cs2, true) TEST_EQUAL(hasher(cs1), hasher(cs2)) // Test with populated objects cs1.setNativeID("native_id_1"); cs1.setComment("test comment"); cs1.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); cs1.getPrecursor().setMZ(500.5); cs1.getProduct().setMZ(200.2); cs1.getAcquisitionInfo().setMethodOfCombination("sum"); cs1.getInstrumentSettings().getScanWindows().resize(1); cs1.getInstrumentSettings().getScanWindows()[0].begin = 100.0; cs1.getInstrumentSettings().getScanWindows()[0].end = 1000.0; cs2.setNativeID("native_id_1"); cs2.setComment("test comment"); cs2.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); cs2.getPrecursor().setMZ(500.5); cs2.getProduct().setMZ(200.2); cs2.getAcquisitionInfo().setMethodOfCombination("sum"); cs2.getInstrumentSettings().getScanWindows().resize(1); cs2.getInstrumentSettings().getScanWindows()[0].begin = 100.0; cs2.getInstrumentSettings().getScanWindows()[0].end = 1000.0; TEST_EQUAL(cs1 == cs2, true) TEST_EQUAL(hasher(cs1), hasher(cs2)) // Test that different objects produce different hashes (not guaranteed but highly likely) ChromatogramSettings cs3; cs3.setNativeID("different_id"); TEST_EQUAL(cs1 == cs3, false) TEST_NOT_EQUAL(hasher(cs1), hasher(cs3)) // Test use in unordered_set { std::unordered_set<ChromatogramSettings> set; ChromatogramSettings s1, s2, s3; s1.setNativeID("id1"); s2.setNativeID("id2"); s3.setNativeID("id1"); // same as s1 set.insert(s1); set.insert(s2); TEST_EQUAL(set.size(), 2) // s3 is equal to s1, so size should stay 2 set.insert(s3); TEST_EQUAL(set.size(), 2) TEST_EQUAL(set.count(s1), 1) TEST_EQUAL(set.count(s2), 1) TEST_EQUAL(set.count(s3), 1) // s3 == s1 } // Test use in unordered_map { std::unordered_map<ChromatogramSettings, int> map; ChromatogramSettings k1, k2, k3; k1.setNativeID("key1"); k2.setNativeID("key2"); k3.setNativeID("key1"); // same as k1 map[k1] = 1; map[k2] = 2; TEST_EQUAL(map.size(), 2) TEST_EQUAL(map[k1], 1) TEST_EQUAL(map[k2], 2) TEST_EQUAL(map[k3], 1) // k3 == k1 map[k3] = 3; // should update k1's value TEST_EQUAL(map[k1], 3) } // Test hash consistency (same object hashed multiple times) size_t hash1 = hasher(cs1); size_t hash2 = hasher(cs1); TEST_EQUAL(hash1, hash2) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IndentedStream_test.cpp
.cpp
3,827
128
// 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/IndentedStream.h> /////////////////////////// #include <OpenMS/CONCEPT/Colorizer.h> #include <sstream> using namespace OpenMS; using namespace std; const int TEST_CONSOLE_WIDTH = 9; namespace OpenMS { struct ConsoleWidthTest { ConsoleWidthTest() { auto& t = ConsoleUtils::getInstance(); // make sure the singleton is initialized const_cast<ConsoleUtils&>(t).console_width_ = TEST_CONSOLE_WIDTH; } }; ConsoleWidthTest instance; // set console width! } // namespace OpenMS START_TEST(IndentedStream, "$Id$") // test this first, because all the other tests rely on it START_SECTION([EXTRA] int getConsoleWidth() const) { auto& t = ConsoleUtils::getInstance(); TEST_EQUAL(t.getConsoleWidth(), TEST_CONSOLE_WIDTH) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(IndentedStream(std::ostream& stream, const UInt indentation, const UInt max_lines)) { NOT_TESTABLE // tested below } END_SECTION START_SECTION(IndentedStream& operator<<(Colorizer& colorizer)) { { // inline color stringstream ss; // will contain ANSI color codes... but they are not counted as characters on the current line IndentedStream is(ss, 3, 10); is << "12" << red("red") << "6789ab"; TEST_EQUAL(ss.str(), "12\033[91mred\033[39m6789\n ab") // the first line has more than #TEST_CONSOLE_WIDTH chars, but the ANSI codes do not count } { // color until revoked stringstream ss; IndentedStream is(ss, 3, 10); is << "12" << red() << "red" << red.undo() << "6789ab"; TEST_EQUAL(ss.str(), "12\033[91mred\033[39m6789\n ab") // the first line has more than #TEST_CONSOLE_WIDTH chars, but the ANSI codes do not count } } END_SECTION START_SECTION(IndentedStream& operator<<(IndentedStream& self)) { NOT_TESTABLE // tested below } END_SECTION const String x20(TEST_CONSOLE_WIDTH * 2 + 1, 'x'); // test string (2 full lines plus one 'x') const String xC(TEST_CONSOLE_WIDTH, 'x'); // full console width of 'x' START_SECTION((template<typename T> IndentedStream & operator<<(const T& data))) { stringstream ss; int indent = 3; String s_indent(indent, ' '); IndentedStream is(ss, indent, 10); is << 3 << " " << '\n' << 'c'; TEST_EQUAL(ss.str(), "3 \n" + s_indent + "c") } END_SECTION START_SECTION(IndentedStream& operator<<(StreamManipulator manip)) { stringstream ss; IndentedStream is(ss, 3, 10); is << "xx" << std::endl << 'y'; TEST_EQUAL(ss.str(), "xx\ny") } END_SECTION START_SECTION(IndentedStream& indent(const UInt new_indent)) { stringstream ss; int indent = 3; int indent_new = 5; String s_indent(indent, ' '); String s_indent_new(indent_new, ' '); IndentedStream is(ss, indent, 10); is << xC // a full line << 'y' // indented 'y' << is.indent(indent_new) // 'announce' that we want a new indentation for the next line << xC; // a full line which does not fit and triggers a linebreak TEST_EQUAL(ss.str(), xC + "\n" + s_indent + "y" + (xC.data() + indent + 1) + "\n" // +1 to skip one 'x' + s_indent_new + xC.suffix(indent + 1)) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/LevMarqFitter1D_test.cpp
.cpp
2,321
112
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FEATUREFINDER/InterpolationModel.h> #include <OpenMS/FEATUREFINDER/LevMarqFitter1D.h> #include <OpenMS/FEATUREFINDER/Fitter1D.h> /////////////////////////// using namespace OpenMS; using namespace std; /////////////////////////// class TestModel : public LevMarqFitter1D { public: TestModel() : LevMarqFitter1D() { setName("TestModel"); check_defaults_ = false; defaultsToParam_(); } TestModel(const TestModel& source) : LevMarqFitter1D(source) { updateMembers_(); } ~TestModel() override { } virtual TestModel& operator = (const TestModel& source) { if (&source == this) return *this; LevMarqFitter1D::operator = (source); updateMembers_(); return *this; } void updateMembers_() override { LevMarqFitter1D::updateMembers_(); } QualityType fit1d(const RawDataArrayType& /*range*/, std::unique_ptr<InterpolationModel>& /*model*/) override { // double center = 0.0; // center = model->getCenter(); return 1.0; } void optimize_() { } }; ///////////////////////////////////////////////////////////// START_TEST(LevMarqFitter1D, "$Id$") /////////////////////////// ///////////////////////////////////////////////////////////// TestModel* ptr = nullptr; TestModel* nullPointer = nullptr; START_SECTION((LevMarqFitter1D())) ptr = new TestModel(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((LevMarqFitter1D(const LevMarqFitter1D &source))) TestModel tm1; TestModel tm2(tm1); END_SECTION START_SECTION((virtual ~LevMarqFitter1D())) delete ptr; END_SECTION START_SECTION((virtual LevMarqFitter1D& operator=(const LevMarqFitter1D &source))) TestModel tm1; TestModel tm2; tm2 = tm1; END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MascotXMLFile_test.cpp
.cpp
15,936
309
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Nico Pfeifer, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/CONCEPT/FuzzyStringComparator.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/FORMAT/MascotXMLFile.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/METADATA/ContactPerson.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <vector> /////////////////////////// START_TEST(MascotXMLFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; MascotXMLFile xml_file; MascotXMLFile* ptr; ProteinIdentification protein_identification; PeptideIdentificationList peptide_identifications; PeptideIdentificationList peptide_identifications2; DateTime date; PeptideHit peptide_hit; vector<String> references; date.set("2006-03-09 11:31:52"); MascotXMLFile* nullPointer = nullptr; START_SECTION((MascotXMLFile())) ptr = new MascotXMLFile(); TEST_NOT_EQUAL(ptr, nullPointer) delete ptr; END_SECTION START_SECTION((static void initializeLookup(SpectrumMetaDataLookup& lookup, PeakMap& experiment, const String& scan_regex = ""))) { PeakMap exp; exp.getSpectra().resize(1); SpectrumMetaDataLookup lookup; xml_file.initializeLookup(lookup, exp); TEST_EQUAL(lookup.empty(), false); } END_SECTION START_SECTION((void load(const String& filename, ProteinIdentification& protein_identification, PeptideIdentificationList& id_data, SpectrumMetaDataLookup& lookup))) { SpectrumMetaDataLookup lookup; xml_file.load(OPENMS_GET_TEST_DATA_PATH("MascotXMLFile_test_1.mascotXML"), protein_identification, peptide_identifications, lookup); { ProteinIdentification::SearchParameters search_parameters = protein_identification.getSearchParameters(); TEST_EQUAL(search_parameters.missed_cleavages, 1); TEST_EQUAL(search_parameters.taxonomy, ". . Eukaryota (eucaryotes)"); TEST_EQUAL(search_parameters.mass_type, ProteinIdentification::PeakMassType::AVERAGE); TEST_EQUAL(search_parameters.db, "MSDB_chordata"); TEST_EQUAL(search_parameters.db_version, "MSDB_chordata_20070910.fasta"); TEST_EQUAL(search_parameters.fragment_mass_tolerance, 0.2); TEST_EQUAL(search_parameters.precursor_mass_tolerance, 1.4); TEST_EQUAL(search_parameters.fragment_mass_tolerance_ppm, false); TEST_EQUAL(search_parameters.precursor_mass_tolerance_ppm, false); TEST_EQUAL(search_parameters.charges, "1+, 2+ and 3+"); TEST_EQUAL(search_parameters.fixed_modifications.size(), 4); TEST_EQUAL(search_parameters.fixed_modifications[0], "Carboxymethyl (C)"); TEST_EQUAL(search_parameters.fixed_modifications[1], "Deamidated (N)"); TEST_EQUAL(search_parameters.fixed_modifications[2], "Deamidated (Q)"); TEST_EQUAL(search_parameters.fixed_modifications[3], "Guanidinyl (K)"); TEST_EQUAL(search_parameters.variable_modifications.size(), 3); TEST_EQUAL(search_parameters.variable_modifications[0], "Acetyl (Protein N-term)"); TEST_EQUAL(search_parameters.variable_modifications[1], "Biotin (K)"); TEST_EQUAL(search_parameters.variable_modifications[2], "Carbamyl (K)"); TEST_EQUAL(peptide_identifications.size(), 3); TOLERANCE_ABSOLUTE(0.0001); TEST_REAL_SIMILAR(peptide_identifications[0].getMZ(), 789.83); TEST_REAL_SIMILAR(peptide_identifications[1].getMZ(), 135.29); TEST_REAL_SIMILAR(peptide_identifications[2].getMZ(), 982.58); TOLERANCE_ABSOLUTE(0.00001); TEST_EQUAL(protein_identification.getHits().size(), 2); TEST_EQUAL(protein_identification.getHits()[0].getAccession(), "AAN17824"); TEST_EQUAL(protein_identification.getHits()[1].getAccession(), "GN1736"); TEST_REAL_SIMILAR(protein_identification.getHits()[0].getScore(), 619); TEST_REAL_SIMILAR(protein_identification.getHits()[1].getScore(), 293); TEST_EQUAL(protein_identification.getScoreType(), "Mascot"); TEST_EQUAL(protein_identification.getDateTime().get(), "2006-03-09 11:31:52"); TEST_REAL_SIMILAR(peptide_identifications[0].getSignificanceThreshold(), 31.8621); TEST_EQUAL(peptide_identifications[0].getHits().size(), 2); peptide_hit = peptide_identifications[0].getHits()[0]; set<String> ref_set = peptide_hit.extractProteinAccessionsSet(); vector<String> references(ref_set.begin(), ref_set.end()); TEST_EQUAL(references.size(), 2); TEST_EQUAL(references[0], "AAN17824"); TEST_EQUAL(references[1], "GN1736"); peptide_hit = peptide_identifications[0].getHits()[1]; ref_set = peptide_hit.extractProteinAccessionsSet(); references = vector<String>(ref_set.begin(), ref_set.end()); TEST_EQUAL(references.size(), 1); TEST_EQUAL(references[0], "AAN17824"); peptide_hit = peptide_identifications[1].getHits()[0]; ref_set = peptide_hit.extractProteinAccessionsSet(); references = vector<String>(ref_set.begin(), ref_set.end()); TEST_EQUAL(references.size(), 1); TEST_EQUAL(references[0], "GN1736"); TEST_EQUAL(peptide_identifications[1].getHits().size(), 1); TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[0].getScore(), 33.85); TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[1].getScore(), 33.12); TEST_REAL_SIMILAR(peptide_identifications[1].getHits()[0].getScore(), 43.9); TEST_EQUAL(peptide_identifications[0].getScoreType(), "Mascot"); TEST_EQUAL(peptide_identifications[1].getScoreType(), "Mascot"); TEST_EQUAL(protein_identification.getDateTime() == date, true); TEST_EQUAL(peptide_identifications[0].getHits()[0].getSequence(), AASequence::fromString("LHASGITVTEIPVTATN(MOD:00565)FK(MOD:00445)")); TEST_EQUAL(peptide_identifications[0].getHits()[1].getSequence(), AASequence::fromString("MRSLGYVAVISAVATDTDK(MOD:00445)")); TEST_EQUAL(peptide_identifications[1].getHits()[0].getSequence(), AASequence::fromString("HSK(MOD:00445)LSAK(MOD:00445)")); String identifier = protein_identification.getIdentifier(); TEST_EQUAL(!identifier.empty(), true); for (Size i = 0; i < peptide_identifications.size(); ++i) { TEST_EQUAL(identifier, peptide_identifications[i].getIdentifier()) } } /// for new MascotXML 2.1 as used by Mascot Server 2.3 xml_file.load(OPENMS_GET_TEST_DATA_PATH("MascotXMLFile_test_2.mascotXML"), protein_identification, peptide_identifications, lookup); { ProteinIdentification::SearchParameters search_parameters = protein_identification.getSearchParameters(); TEST_EQUAL(search_parameters.missed_cleavages, 7); TEST_EQUAL(search_parameters.taxonomy, "All entries"); TEST_EQUAL(search_parameters.mass_type, ProteinIdentification::PeakMassType::MONOISOTOPIC); TEST_EQUAL(search_parameters.db, "IPI_human"); TEST_EQUAL(search_parameters.db_version, "ipi.HUMAN.v3.61.fasta"); TEST_EQUAL(search_parameters.fragment_mass_tolerance, 0.3); TEST_EQUAL(search_parameters.precursor_mass_tolerance, 3); TEST_EQUAL(search_parameters.fragment_mass_tolerance_ppm, false); TEST_EQUAL(search_parameters.precursor_mass_tolerance_ppm, false); TEST_EQUAL(search_parameters.charges, ""); TEST_EQUAL(search_parameters.fixed_modifications.size(), 1); TEST_EQUAL(search_parameters.fixed_modifications[0], "Carbamidomethyl (C)"); TEST_EQUAL(search_parameters.variable_modifications.size(), 3); TEST_EQUAL(search_parameters.variable_modifications[0], "Oxidation (M)"); TEST_EQUAL(search_parameters.variable_modifications[1], "Acetyl (N-term)"); TEST_EQUAL(search_parameters.variable_modifications[2], "Phospho (Y)"); // not necessarily equal to numQueries as some hits might not be contained, e.g. peptide's might start with <peptide rank="10"...> so 9 peptides are missing // thus empty peptides are removed (see MascotXMLFile.cpp::load() ) after the handler() call TEST_EQUAL(peptide_identifications.size(), 1112); TOLERANCE_ABSOLUTE(0.0001); TEST_REAL_SIMILAR(peptide_identifications[0].getMZ(), 304.6967); TEST_REAL_SIMILAR(peptide_identifications[1].getMZ(), 314.1815); TEST_REAL_SIMILAR(peptide_identifications[1111].getMZ(), 583.7948); TOLERANCE_ABSOLUTE(0.00001); TEST_EQUAL(protein_identification.getHits().size(), 66); TEST_EQUAL(protein_identification.getHits()[0].getAccession(), "IPI00745872"); TEST_EQUAL(protein_identification.getHits()[1].getAccession(), "IPI00908876"); TEST_REAL_SIMILAR(protein_identification.getHits()[0].getScore(), 122); TEST_REAL_SIMILAR(protein_identification.getHits()[1].getScore(), 122); TEST_EQUAL(protein_identification.getScoreType(), "Mascot"); TEST_EQUAL(protein_identification.getDateTime().get(), "2011-06-24 19:34:54"); TEST_REAL_SIMILAR(peptide_identifications[0].getSignificanceThreshold(), 5); TEST_EQUAL(peptide_identifications[0].getHits().size(), 1); peptide_hit = peptide_identifications[0].getHits()[0]; vector<PeptideEvidence> pes = peptide_hit.getPeptideEvidences(); TEST_EQUAL(pes.size(), 0); pes = peptide_identifications[34].getHits()[0].getPeptideEvidences(); set<String> accessions = peptide_identifications[34].getHits()[0].extractProteinAccessionsSet(); references = vector<String>(accessions.begin(), accessions.end()); // corresponds to <peptide query="35" ...> ABORT_IF(references.size() != 5); TEST_EQUAL(references[0], "IPI00022434"); TEST_EQUAL(references[1], "IPI00384697"); TEST_EQUAL(references[2], "IPI00745872"); TEST_EQUAL(references[3], "IPI00878517"); TEST_EQUAL(references[4], "IPI00908876"); TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[0].getScore(), 5.34); TEST_REAL_SIMILAR(peptide_identifications[49].getHits()[0].getScore(), 14.83); TEST_REAL_SIMILAR(peptide_identifications[49].getHits()[1].getScore(), 17.5); TEST_EQUAL(peptide_identifications[0].getScoreType(), "Mascot"); TEST_EQUAL(peptide_identifications[1].getScoreType(), "Mascot"); TEST_EQUAL(protein_identification.getDateTime().get() == "2011-06-24 19:34:54", true); TEST_EQUAL(peptide_identifications[0].getHits()[0].getSequence(), AASequence::fromString("VVFIK")); TEST_EQUAL(peptide_identifications[49].getHits()[0].getSequence(), AASequence::fromString("LASYLDK")); TEST_EQUAL(peptide_identifications[49].getHits()[1].getSequence(), AASequence::fromString("(Acetyl)AAFESDK")); //for (int i=520;i<540;++i) std::cerr << "i: " << i << " " << peptide_identifications[i].getHits()[0].getSequence() << "\n"; TEST_EQUAL(peptide_identifications[522].getHits()[0].getSequence(), AASequence::fromString("(Acetyl)GALM(Oxidation)NEIQAAK")); TEST_EQUAL(peptide_identifications[67].getHits()[0].getSequence(), AASequence::fromString("SHY(Phospho)GGSR")); String identifier = protein_identification.getIdentifier(); TEST_EQUAL(!identifier.empty(), true); for (Size i = 0; i < peptide_identifications.size(); ++i) { TEST_EQUAL(identifier, peptide_identifications[i].getIdentifier()) } } xml_file.load(OPENMS_GET_TEST_DATA_PATH("MascotXMLFile_test_3.mascotXML"), protein_identification, peptide_identifications, lookup); { std::vector<ProteinIdentification> pids; pids.push_back(protein_identification); String filename; NEW_TMP_FILE(filename) IdXMLFile().store(filename, pids, peptide_identifications); FuzzyStringComparator fuzzy; fuzzy.setWhitelist(ListUtils::create<String>("<?xml-stylesheet")); fuzzy.setAcceptableAbsolute(0.0001); bool result = fuzzy.compareFiles(filename, OPENMS_GET_TEST_DATA_PATH("MascotXMLFile_test_out_3.idXML")); TEST_EQUAL(result, true); } } END_SECTION START_SECTION((void load(const String& filename, ProteinIdentification& protein_identification, PeptideIdentificationList& id_data, std::map<String, std::vector<AASequence> >& peptides, SpectrumMetaDataLookup& lookup))) std::map<String, vector<AASequence> > modified_peptides; AASequence aa_sequence_1; AASequence aa_sequence_2; AASequence aa_sequence_3; vector<AASequence> temp; aa_sequence_1 = AASequence::fromString("LHASGITVTEIPVTATNFK"); aa_sequence_1.setModification(16, "Deamidated"); aa_sequence_2 = AASequence::fromString("MRSLGYVAVISAVATDTDK"); aa_sequence_2.setModification(2, "Phospho"); aa_sequence_3 = AASequence::fromString("HSKLSAK"); aa_sequence_3.setModification(4, "Phospho"); temp.push_back(aa_sequence_1); temp.push_back(aa_sequence_2); modified_peptides.insert(make_pair("789.83", temp)); temp.clear(); temp.push_back(aa_sequence_3); modified_peptides.insert(make_pair("135.29", temp)); SpectrumMetaDataLookup lookup; xml_file.load(OPENMS_GET_TEST_DATA_PATH("MascotXMLFile_test_1.mascotXML"), protein_identification, peptide_identifications, modified_peptides, lookup); TEST_EQUAL(peptide_identifications.size(), 3) TOLERANCE_ABSOLUTE(0.0001) TEST_REAL_SIMILAR(peptide_identifications[0].getMZ(), 789.83) TEST_REAL_SIMILAR(peptide_identifications[1].getMZ(), 135.29) TEST_REAL_SIMILAR(peptide_identifications[2].getMZ(), 982.58) TOLERANCE_ABSOLUTE(0.00001) TEST_EQUAL(protein_identification.getHits().size(), 2) TEST_EQUAL(protein_identification.getHits()[0].getAccession(), "AAN17824") TEST_EQUAL(protein_identification.getHits()[1].getAccession(), "GN1736") TEST_REAL_SIMILAR(protein_identification.getHits()[0].getScore(), 619) TEST_REAL_SIMILAR(protein_identification.getHits()[1].getScore(), 293) TEST_EQUAL(protein_identification.getScoreType(), "Mascot") TEST_EQUAL(protein_identification.getDateTime().get(), "2006-03-09 11:31:52") TEST_REAL_SIMILAR(peptide_identifications[0].getSignificanceThreshold(), 31.8621) TEST_EQUAL(peptide_identifications[0].getHits().size(), 2) peptide_hit = peptide_identifications[0].getHits()[0]; set<String> accessions = peptide_hit.extractProteinAccessionsSet(); references = vector<String>(accessions.begin(), accessions.end()); TEST_EQUAL(references.size(), 2) TEST_EQUAL(references[0], "AAN17824") TEST_EQUAL(references[1], "GN1736") peptide_hit = peptide_identifications[0].getHits()[1]; accessions = peptide_hit.extractProteinAccessionsSet(); references = vector<String>(accessions.begin(), accessions.end()); TEST_EQUAL(references.size(), 1) TEST_EQUAL(references[0], "AAN17824") peptide_hit = peptide_identifications[1].getHits()[0]; accessions = peptide_hit.extractProteinAccessionsSet(); references = vector<String>(accessions.begin(), accessions.end()); TEST_EQUAL(references.size(), 1) TEST_EQUAL(references[0], "GN1736") TEST_EQUAL(peptide_identifications[1].getHits().size(), 1) TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[0].getScore(), 33.85) TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[1].getScore(), 33.12) TEST_REAL_SIMILAR(peptide_identifications[1].getHits()[0].getScore(), 43.9) TEST_EQUAL(peptide_identifications[0].getScoreType(), "Mascot") TEST_EQUAL(peptide_identifications[1].getScoreType(), "Mascot") TEST_EQUAL(protein_identification.getDateTime() == date, true) TEST_EQUAL(peptide_identifications[0].getHits()[0].getSequence(), aa_sequence_1) TEST_EQUAL(peptide_identifications[0].getHits()[1].getSequence(), aa_sequence_2) TEST_EQUAL(peptide_identifications[1].getHits()[0].getSequence(), aa_sequence_3) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MSDataAggregatingConsumer_test.cpp
.cpp
7,114
230
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/DATAACCESS/MSDataAggregatingConsumer.h> /////////////////////////// #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/FORMAT/DATAACCESS/MSDataStoringConsumer.h> START_TEST(MSDataAggregatingConsumer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; MSDataAggregatingConsumer* agg_consumer_ptr = nullptr; MSDataAggregatingConsumer* agg_consumer_nullPointer = nullptr; START_SECTION((MSDataAggregatingConsumer())) agg_consumer_ptr = new MSDataAggregatingConsumer(agg_consumer_nullPointer); // don't do that ... TEST_NOT_EQUAL(agg_consumer_ptr, agg_consumer_nullPointer) END_SECTION START_SECTION((~MSDataAggregatingConsumer())) delete agg_consumer_ptr; END_SECTION START_SECTION((void consumeSpectrum(SpectrumType & s))) { // no adding up { MSDataStoringConsumer * storage = new MSDataStoringConsumer(); MSDataAggregatingConsumer * agg_consumer = new MSDataAggregatingConsumer(storage); MSSpectrum s; s.setName("spec1"); s.setRT(5); agg_consumer->consumeSpectrum(s); s.setName("spec2"); s.setRT(15); agg_consumer->consumeSpectrum(s); s.setName("spec3"); s.setRT(25); agg_consumer->consumeSpectrum(s); // note how we can / have to destroy the aggregate consumer to ensure it // flushes the data. The storage object will still be around. delete agg_consumer; TEST_EQUAL(storage->getData().getNrSpectra(), 3) TEST_EQUAL(storage->getData().getNrChromatograms(), 0) TEST_EQUAL(storage->getData().getSpectra()[0].getName(), "spec1") TEST_EQUAL(storage->getData().getSpectra()[1].getName(), "spec2") TEST_EQUAL(storage->getData().getSpectra()[2].getName(), "spec3") delete storage; } // adding empty spectra { MSDataStoringConsumer * storage = new MSDataStoringConsumer(); MSDataAggregatingConsumer * agg_consumer = new MSDataAggregatingConsumer(storage); MSSpectrum s; s.setName("spec1"); s.setComment("comm1"); s.setRT(5); agg_consumer->consumeSpectrum(s); s.setName("spec2"); s.setComment("comm2"); s.setRT(5); agg_consumer->consumeSpectrum(s); s.setName("spec3"); s.setComment("comm3"); s.setRT(25); agg_consumer->consumeSpectrum(s); s.setName("spec4"); s.setComment("comm4"); s.setRT(25); agg_consumer->consumeSpectrum(s); s.setName("spec5"); s.setComment("comm5"); s.setRT(35); agg_consumer->consumeSpectrum(s); // note how we can / have to destroy the aggregate consumer to ensure it // flushes the data. The storage object will still be around. delete agg_consumer; TEST_EQUAL(storage->getData().getNrSpectra(), 3) TEST_EQUAL(storage->getData().getNrChromatograms(), 0) TEST_EQUAL(storage->getData().getSpectra()[0].getName(), "spec1") TEST_EQUAL(storage->getData().getSpectra()[1].getName(), "spec3") TEST_EQUAL(storage->getData().getSpectra()[2].getName(), "spec5") TEST_EQUAL(storage->getData().getSpectra()[0].getComment(), "comm1") TEST_EQUAL(storage->getData().getSpectra()[1].getComment(), "comm3") TEST_EQUAL(storage->getData().getSpectra()[2].getComment(), "comm5") delete storage; } // adding full spectra { MSDataStoringConsumer * storage = new MSDataStoringConsumer(); MSDataAggregatingConsumer * agg_consumer = new MSDataAggregatingConsumer(storage); MSSpectrum s; s.setName("spec1"); s.setComment("comm1"); s.setRT(5); s.push_back(Peak1D(5, 7)); s.push_back(Peak1D(10, 20)); s.push_back(Peak1D(15, 30)); agg_consumer->consumeSpectrum(s); s.clear(true); s.setName("spec2"); s.setComment("comm2"); s.setRT(5); s.push_back(Peak1D(5, 10)); s.push_back(Peak1D(10, 100)); s.push_back(Peak1D(15, 200)); agg_consumer->consumeSpectrum(s); s.clear(true); s.setName("spec3"); s.setComment("comm3"); s.setRT(25); agg_consumer->consumeSpectrum(s); s.clear(true); s.setName("spec4"); s.setComment("comm4"); s.setRT(25); agg_consumer->consumeSpectrum(s); s.clear(true); s.setName("spec5"); s.setComment("comm5"); s.setRT(35); agg_consumer->consumeSpectrum(s); s.clear(true); // note how we can / have to destroy the aggregate consumer to ensure it // flushes the data. The storage object will still be around. delete agg_consumer; TEST_EQUAL(storage->getData().getNrSpectra(), 3) TEST_EQUAL(storage->getData().getNrChromatograms(), 0) TEST_EQUAL(storage->getData().getSpectra()[0].getName(), "spec1") TEST_EQUAL(storage->getData().getSpectra()[1].getName(), "spec3") TEST_EQUAL(storage->getData().getSpectra()[2].getName(), "spec5") TEST_EQUAL(storage->getData().getSpectra()[0].getComment(), "comm1") TEST_EQUAL(storage->getData().getSpectra()[1].getComment(), "comm3") TEST_EQUAL(storage->getData().getSpectra()[2].getComment(), "comm5") MSSpectrum snew = storage->getData().getSpectra()[0]; TEST_EQUAL(snew.size(), 3) TEST_REAL_SIMILAR(snew[0].getMZ(), 5) TEST_REAL_SIMILAR(snew[0].getIntensity(), 17) TEST_REAL_SIMILAR(snew[1].getMZ(), 10) TEST_REAL_SIMILAR(snew[1].getIntensity(), 120) TEST_REAL_SIMILAR(snew[2].getMZ(), 15) TEST_REAL_SIMILAR(snew[2].getIntensity(), 230) delete storage; } } END_SECTION START_SECTION((void consumeChromatogram(ChromatogramType & c))) { MSDataStoringConsumer * storage = new MSDataStoringConsumer(); MSDataAggregatingConsumer * agg_consumer = new MSDataAggregatingConsumer(storage); MSChromatogram c; c.setNativeID("testid"); agg_consumer->consumeChromatogram(c); delete agg_consumer; TEST_EQUAL(storage->getData().getNrSpectra(), 0) TEST_EQUAL(storage->getData().getNrChromatograms(), 1) TEST_EQUAL(storage->getData().getChromatograms()[0].getNativeID(), "testid") delete storage; } END_SECTION START_SECTION((void setExpectedSize(Size, Size))) NOT_TESTABLE // tested above END_SECTION START_SECTION((void setExperimentalSettings(const ExperimentalSettings&))) { /* MSDataTransformingConsumer * transforming_consumer = new MSDataTransformingConsumer(); transforming_consumer->setExpectedSize(2,0); ExperimentalSettings s; transforming_consumer->setExperimentalSettings( s ); TEST_NOT_EQUAL(transforming_consumer, transforming_consumer_nullPointer) delete transforming_consumer; */ } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ZhangSimilarityScore_test.cpp
.cpp
2,891
102
// 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/ZhangSimilarityScore.h> #include <OpenMS/FORMAT/DTAFile.h> #include <OpenMS/PROCESSING/SCALING/Normalizer.h> /////////////////////////// START_TEST(ZhangSimilarityScore, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; ZhangSimilarityScore* ptr = nullptr; ZhangSimilarityScore* nullPointer = nullptr; START_SECTION(ZhangSimilarityScore()) ptr = new ZhangSimilarityScore(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~ZhangSimilarityScore()) delete ptr; END_SECTION ptr = new ZhangSimilarityScore(); START_SECTION(ZhangSimilarityScore(const ZhangSimilarityScore& source)) ZhangSimilarityScore copy(*ptr); TEST_EQUAL(copy.getName(), ptr->getName()); TEST_EQUAL(copy.getParameters(), ptr->getParameters()); END_SECTION START_SECTION(ZhangSimilarityScore& operator = (const ZhangSimilarityScore& source)) ZhangSimilarityScore 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) PeakSpectrum s1; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); Normalizer normalizer; Param p(normalizer.getParameters()); p.setValue("method", "to_one"); normalizer.setParameters(p); normalizer.filterSpectrum(s1); double score = (*ptr)(s1); TEST_REAL_SIMILAR(score, 1.82682); END_SECTION START_SECTION(double operator () (const PeakSpectrum& spec1, const PeakSpectrum& spec2) const) PeakSpectrum s1, s2; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s2); Normalizer normalizer; Param p(normalizer.getParameters()); p.setValue("method", "to_one"); normalizer.setParameters(p); normalizer.filterSpectrum(s1); normalizer.filterSpectrum(s2); TOLERANCE_ABSOLUTE(0.01) double score = (*ptr)(s1, s2); TEST_REAL_SIMILAR(score, 1.82682) s2.resize(100); score = (*ptr)(s1, s2); normalizer.filterSpectrum(s2); TEST_REAL_SIMILAR(score, 0.328749) END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/OpenSwathMRMFeatureAccessOpenMS_test.cpp
.cpp
4,460
169
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: George Rosenberger, Hannes Roest, Witold Wolski $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <boost/assign/std/vector.hpp> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/MRMFeatureAccessOpenMS.h> /////////////////////////// #include <OpenMS/ANALYSIS/MRM/ReactionMonitoringTransition.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <OpenMS/KERNEL/MSExperiment.h> using namespace OpenMS; using namespace std; START_TEST(MRMFeatureAccessOpenMS, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// //FeatureOpenMS { FeatureOpenMS* ptr = nullptr; FeatureOpenMS* nullPointer = nullptr; START_SECTION(FeatureOpenMS()) { Feature f; ptr = new FeatureOpenMS(f); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~FeatureOpenMS()) { delete ptr; } END_SECTION } //MRMFeatureOpenMS { MRMFeatureOpenMS* ptr = nullptr; MRMFeatureOpenMS* nullPointer = nullptr; START_SECTION(MRMFeatureOpenMS()) { MRMFeature f; ptr = new MRMFeatureOpenMS(f); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~MRMFeatureOpenMS()) { delete ptr; } END_SECTION } //TransitionGroupOpenMS { TransitionGroupOpenMS <MSChromatogram, ReactionMonitoringTransition>* ptr = nullptr; TransitionGroupOpenMS <MSChromatogram, ReactionMonitoringTransition>* nullPointer = nullptr; START_SECTION(TransitionGroupOpenMS()) { MRMTransitionGroup <MSChromatogram, ReactionMonitoringTransition> trgroup; ptr = new TransitionGroupOpenMS < MSChromatogram, ReactionMonitoringTransition> (trgroup); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~TransitionGroupOpenMS()) { delete ptr; } END_SECTION } //SignalToNoiseOpenMS { SignalToNoiseOpenMS<MSSpectrum>* ptr = nullptr; SignalToNoiseOpenMS<MSSpectrum>* nullPointer = nullptr; START_SECTION(SignalToNoiseOpenMS()) { OpenMS::MSSpectrum chromat; ptr = new SignalToNoiseOpenMS<MSSpectrum>(chromat, 1.0, 3.0, true); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~SignalToNoiseOpenMS()) { delete ptr; } END_SECTION START_SECTION(double getValueAtRT(double RT)) { static const double arr1[] = { 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590 }; std::vector<double> mz (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); static const double arr2[] = { 5.4332, 5.6189, 4.3025, 4.5705, 5.4538, 9.7202, 8.805, 8.5391, 6.6257, 5.809, 6.5518, 7.9273, 5.3875, 9.826, 5.139, 5.8588, 0.7806, 4.2054, 9.9171, 4.0198, 1.1462, 5.1042, 7.8318, 4.8553, 6.691, 4.2377, 7.2344, 4.0124, 3.8565, 6.2867, 1.0817, 8.2412, 5.0589, 7.0478, 5.9388, 1.2747, 2.4228, 4.909, 6.856, 1.9665 }; std::vector<double> intensity (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); MSSpectrum s; for (Size i = 0; i < mz.size(); i++) { Peak1D p; p.setMZ(mz[i]); p.setIntensity(intensity[i]); s.push_back(p); } SignalToNoiseOpenMS<MSSpectrum> ff(s, 200, 50, true); double value200 = 0.987854524; double value210 = 1.02162; double value220 = 0.782272686; double value590 = 0.35754546252164; // test values between the mz values TEST_REAL_SIMILAR ( ff.getValueAtRT(201), value200 ) TEST_REAL_SIMILAR ( ff.getValueAtRT(211), value210 ) TEST_REAL_SIMILAR ( ff.getValueAtRT(221), value220 ) // test values exactly on the mz values TEST_REAL_SIMILAR ( ff.getValueAtRT(200), value200 ) TEST_REAL_SIMILAR ( ff.getValueAtRT(210), value210 ) // test values outside the range TEST_REAL_SIMILAR ( ff.getValueAtRT(100), value200 ) TEST_REAL_SIMILAR ( ff.getValueAtRT(588), value590 ) TEST_REAL_SIMILAR ( ff.getValueAtRT(590), value590 ) TEST_REAL_SIMILAR ( ff.getValueAtRT(700), value590 ) } END_SECTION } ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MaxLikeliFitter1D_test.cpp
.cpp
2,648
118
// 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/MaxLikeliFitter1D.h> /////////////////////////// /////////////////////////// using namespace OpenMS; using namespace std; class TestModel : public MaxLikeliFitter1D { public: TestModel() : MaxLikeliFitter1D() { setName("TestModel"); check_defaults_ = false; defaultsToParam_(); } TestModel(const TestModel& source) : MaxLikeliFitter1D(source) { updateMembers_(); } ~TestModel() override { } virtual TestModel& operator = (const TestModel& source) { if (&source == this) return *this; MaxLikeliFitter1D::operator = (source); updateMembers_(); return *this; } void updateMembers_() override { MaxLikeliFitter1D::updateMembers_(); } QualityType fit1d(const RawDataArrayType& /*range*/, std::unique_ptr<InterpolationModel>& /*model*/) override { // double center = 0.0; // center = model->getCenter(); return 1.0; } QualityType fitOffset_(InterpolationModel* /* model */, const RawDataArrayType& /*set*/ , const CoordinateType /* stdev1 */, const CoordinateType /* stdev2 */, const CoordinateType /* offset_step */) { // double center = 0.0; // center = model->getCenter(); // double st_dev_1 = 0.0; // st_dev_1 = stdev1; // double st_dev_2 = 0.0; // st_dev_2 = stdev2; // double offset = 0.0; // offset = offset_step; return 1.0; } }; ///////////////////////////////////////////////////////////// START_TEST(MaxLikeliFitter1D, "$Id$") ///////////////////////////////////////////////////////////// TestModel* ptr = nullptr; TestModel* nullPointer = nullptr; START_SECTION(MaxLikeliFitter1D()) { ptr = new TestModel(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((MaxLikeliFitter1D(const MaxLikeliFitter1D &source))) TestModel tm1; TestModel tm2(tm1); END_SECTION START_SECTION((virtual ~MaxLikeliFitter1D())) delete ptr; END_SECTION START_SECTION((virtual MaxLikeliFitter1D& operator=(const MaxLikeliFitter1D &source))) TestModel tm1; TestModel tm2; tm2 = tm1; END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FAIMSHelper_test.cpp
.cpp
2,990
111
// 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/IONMOBILITY/FAIMSHelper.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/IONMOBILITY/IMTypes.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(FAIMSHelper, "$Id$") ///////////////////////////////////////////////////////////// FAIMSHelper* e_ptr = nullptr; FAIMSHelper* e_nullPointer = nullptr; START_SECTION((FAIMSHelper())) e_ptr = new FAIMSHelper; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION((~FAIMSHelper())) delete e_ptr; END_SECTION e_ptr = new FAIMSHelper(); START_SECTION((std::set<double> getCompensationVoltages(PeakMap& exp))) delete e_ptr; e_ptr = new FAIMSHelper(); MzMLFile IM_file; PeakMap exp; IM_file.load(OPENMS_GET_TEST_DATA_PATH("IM_FAIMS_test.mzML"), exp); TEST_EQUAL(exp.getSpectra().size(), 19) std::set<double> CVs = e_ptr->getCompensationVoltages(exp); TEST_EQUAL(CVs.size(), 3) TEST_EQUAL(CVs.find(-65.0) == CVs.end(), 0) TEST_EQUAL(CVs.find(-55.0) == CVs.end(), 0) TEST_EQUAL(CVs.find(-45.0) == CVs.end(), 0) END_SECTION START_SECTION((std::set<double> getCompensationVoltages() detects FAIMS beyond first spectrum and ignores sentinel)) { PeakMap exp2; // spectrum without FAIMS (first) MSSpectrum s0; s0.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); s0.setDriftTime(12.3); // FAIMS spectrum with valid CV MSSpectrum s1; s1.setDriftTimeUnit(DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE); s1.setDriftTime(-50.0); // FAIMS spectrum with sentinel (should be ignored) MSSpectrum s2; s2.setDriftTimeUnit(DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE); s2.setDriftTime(IMTypes::DRIFTTIME_NOT_SET); exp2.addSpectrum(s0); exp2.addSpectrum(s1); exp2.addSpectrum(s2); const std::set<double> cvs2 = FAIMSHelper::getCompensationVoltages(exp2); TEST_EQUAL(cvs2.size(), 1) TEST_TRUE(cvs2.find(-50.0) != cvs2.end()) } END_SECTION START_SECTION((std::set<double> getCompensationVoltages() returns empty for non-FAIMS)) { PeakMap exp3; MSSpectrum a; a.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); a.setDriftTime(1.0); MSSpectrum b; b.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); b.setDriftTime(2.0); exp3.addSpectrum(a); exp3.addSpectrum(b); const std::set<double> cvs3 = FAIMSHelper::getCompensationVoltages(exp3); TEST_EQUAL(cvs3.empty(), true) } END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MapAlignmentEvaluationAlgorithm_test.cpp
.cpp
3,110
102
// 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/MapAlignmentEvaluationAlgorithm.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentEvaluationAlgorithmPrecision.h> #include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentEvaluationAlgorithmRecall.h> #include <OpenMS/KERNEL/Feature.h> using namespace OpenMS; using namespace std; namespace OpenMS { class MAEA : public MapAlignmentEvaluationAlgorithm { public: void evaluate(const ConsensusMap&, const ConsensusMap&, const double&, const double&, const Peak2D::IntensityType&, const bool use_charge, double& real) override { bool x = use_charge; x=!x; real = 1.5; } }; } START_TEST(MapAlignmentEvaluation, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MAEA* ptr = nullptr; MAEA* nullPointer = nullptr; START_SECTION((MapAlignmentEvaluationAlgorithm())) ptr = new MAEA(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~MapAlignmentEvaluationAlgorithm())) delete ptr; END_SECTION START_SECTION((virtual void evaluate(const ConsensusMap &conensus_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)=0)) MAEA maea; ConsensusMap map1; ConsensusMap map2; double rt_dev, mz_dev; Peak2D::IntensityType int_dev; double real; maea.evaluate(map1, map2, rt_dev, mz_dev, int_dev, false, real); TEST_EQUAL(real, 1.5) END_SECTION START_SECTION((bool isSameHandle(const FeatureHandle &lhs, const FeatureHandle &rhs, const double &rt_dev, const double &mz_dev, const Peak2D::IntensityType &int_dev, const bool use_charge))) { Feature tmp_feature; tmp_feature.setRT(100); tmp_feature.setMZ(555); tmp_feature.setIntensity(200.0f); tmp_feature.setCharge(3); tmp_feature.setUniqueId(1); Feature tmp_feature2; tmp_feature2.setRT(101); tmp_feature2.setMZ(556); tmp_feature2.setIntensity(1199.0f); tmp_feature2.setCharge(4); tmp_feature2.setUniqueId(2); FeatureHandle a(0,tmp_feature); FeatureHandle b(0,tmp_feature2); MAEA maea; TEST_EQUAL(maea.isSameHandle(a, b, 2, 1.5, 1000, false), true); TEST_EQUAL(maea.isSameHandle(a, b, 2, 1.5, 1000, true), false); tmp_feature2.setCharge(3); // now charge is equal FeatureHandle b2(0,tmp_feature2); TEST_EQUAL(maea.isSameHandle(a, b2, 2, 1.5, 1000, false), true); TEST_EQUAL(maea.isSameHandle(a, b2, 2, 1.5, 1000, true), true); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ClusterAnalyzer_test.cpp
.cpp
10,479
340
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer$ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ML/CLUSTERING/ClusterAnalyzer.h> #include <OpenMS/DATASTRUCTURES/DistanceMatrix.h> #include <vector> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ClusterAnalyzer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ClusterAnalyzer* ptr = nullptr; ClusterAnalyzer* nullPointer = nullptr; START_SECTION(ClusterAnalyzer()) { ptr = new ClusterAnalyzer(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~ClusterAnalyzer()) { delete ptr; } END_SECTION START_SECTION((ClusterAnalyzer(const ClusterAnalyzer &source))) { NOT_TESTABLE } END_SECTION ptr = new ClusterAnalyzer(); START_SECTION((std::vector< float > averageSilhouetteWidth(const std::vector< BinaryTreeNode > &tree, const DistanceMatrix< float > &original))) { DistanceMatrix<float> matrix(6,666); matrix.setValue(1,0,0.5f); matrix.setValue(2,0,0.8f); matrix.setValue(2,1,0.3f); matrix.setValue(3,0,0.6f); matrix.setValue(3,1,0.8f); matrix.setValue(3,2,0.8f); matrix.setValue(4,0,0.8f); matrix.setValue(4,1,0.8f); matrix.setValue(4,2,0.8f); matrix.setValue(4,3,0.4f); matrix.setValue(5,0,0.7f); matrix.setValue(5,1,0.8f); matrix.setValue(5,2,0.8f); matrix.setValue(5,3,0.8f); matrix.setValue(5,4,0.8f); vector<float> asw(5); asw[0]=0.170833f; asw[1]=0.309722f; asw[2]=0.306412f; asw[3]=0.125744f; asw[4]=0; vector< BinaryTreeNode > tree; tree.push_back(BinaryTreeNode(1,2,0.3f)); tree.push_back(BinaryTreeNode(3,4,0.4f)); tree.push_back(BinaryTreeNode(0,1,0.5f)); tree.push_back(BinaryTreeNode(0,3,0.6f)); tree.push_back(BinaryTreeNode(0,5,0.7f)); vector<float> result = ptr->averageSilhouetteWidth(tree, matrix); TEST_EQUAL(result.size(), asw.size()); for (Size i = 0; i < result.size(); ++i) { TOLERANCE_ABSOLUTE(0.001); TEST_REAL_SIMILAR(result[i], asw[i]); } } END_SECTION START_SECTION((std::vector< float > dunnIndices(const std::vector<BinaryTreeNode>& tree, const DistanceMatrix<float>& original, const bool tree_from_singlelinkage = false))) { DistanceMatrix<float> matrix(6,666); matrix.setValue(1,0,0.5f); matrix.setValue(2,0,0.8f); matrix.setValue(2,1,0.3f); matrix.setValue(3,0,0.6f); matrix.setValue(3,1,0.8f); matrix.setValue(3,2,0.8f); matrix.setValue(4,0,0.8f); matrix.setValue(4,1,0.8f); matrix.setValue(4,2,0.8f); matrix.setValue(4,3,0.4f); matrix.setValue(5,0,0.7f); matrix.setValue(5,1,0.8f); matrix.setValue(5,2,0.8f); matrix.setValue(5,3,0.8f); matrix.setValue(5,4,0.8f); vector< BinaryTreeNode > tree; tree.push_back(BinaryTreeNode(1,2,0.3f)); tree.push_back(BinaryTreeNode(3,4,0.4f)); tree.push_back(BinaryTreeNode(0,1,0.5f)); tree.push_back(BinaryTreeNode(0,3,0.6f)); tree.push_back(BinaryTreeNode(0,5,0.7f)); vector<float> di(5); di[0]=0.4f/0.3f; di[1]=0.5f/0.4f; di[2]=0.6f/0.8f; di[3]=0.7f/0.8f; di[4]=0.0f; vector<float> result = ptr->dunnIndices(tree, matrix); TEST_EQUAL(result.size(), di.size()); for (Size i = 0; i < result.size(); ++i) { TOLERANCE_ABSOLUTE(0.001); TEST_REAL_SIMILAR(result[i], di[i]); } result = ptr->dunnIndices(tree, matrix, true); TEST_EQUAL(result.size(), di.size()); for (Size i = 0; i < result.size(); ++i) { TOLERANCE_ABSOLUTE(0.001); TEST_REAL_SIMILAR(result[i], di[i]); } } END_SECTION START_SECTION((std::vector< float > cohesion(const std::vector< std::vector<Size> >& clusters, const DistanceMatrix<float>& original))) { DistanceMatrix<float> matrix(6,666); matrix.setValue(1,0,0.5f); matrix.setValue(2,0,0.8f); matrix.setValue(2,1,0.3f); matrix.setValue(3,0,0.6f); matrix.setValue(3,1,0.8f); matrix.setValue(3,2,0.8f); matrix.setValue(4,0,0.8f); matrix.setValue(4,1,0.8f); matrix.setValue(4,2,0.8f); matrix.setValue(4,3,0.4f); matrix.setValue(5,0,0.7f); matrix.setValue(5,1,0.8f); matrix.setValue(5,2,0.8f); matrix.setValue(5,3,0.8f); matrix.setValue(5,4,0.8f); Size a[] = {0,1,2,3,4,5}; vector< vector<Size> > clusters; clusters.push_back(vector<Size>(a,a+3)); clusters.push_back(vector<Size>(a+3,a+5)); clusters.push_back(vector<Size>(a+5,a+6)); vector<float> cohesions; cohesions.push_back(0.533f); cohesions.push_back(0.4f); cohesions.push_back(0.7f); vector<float> result = ptr->cohesion(clusters, matrix); TEST_EQUAL(cohesions.size(), result.size()); for (Size i = 0; i < cohesions.size(); ++i) { TOLERANCE_ABSOLUTE(0.001); TEST_REAL_SIMILAR(cohesions[i], result[i]); } clusters.clear(); clusters.push_back(vector<Size>(a,a+4)); clusters.push_back(vector<Size>(a+4,a+5)); clusters.push_back(vector<Size>(a+5,a+6)); cohesions.clear(); cohesions.push_back(0.633f); cohesions.push_back(0.7f); cohesions.push_back(0.7f); result = ptr->cohesion(clusters, matrix); TEST_EQUAL(cohesions.size(), result.size()); for (Size i = 0; i < cohesions.size(); ++i) { TOLERANCE_ABSOLUTE(0.001); TEST_REAL_SIMILAR(cohesions[i], result[i]); } } END_SECTION START_SECTION((float averagePopulationAberration(Size cluster_quantity, std::vector<BinaryTreeNode>& tree))) { vector< BinaryTreeNode > tree; tree.push_back(BinaryTreeNode(1,2,0.3f)); tree.push_back(BinaryTreeNode(3,4,0.4f)); tree.push_back(BinaryTreeNode(0,1,0.5f)); tree.push_back(BinaryTreeNode(0,3,0.6f)); tree.push_back(BinaryTreeNode(0,5,0.7f)); float result = ptr->averagePopulationAberration(3, tree); TEST_REAL_SIMILAR(2.0/3.0, result); } END_SECTION START_SECTION((void cut(const Size cluster_quantity, const std::vector<BinaryTreeNode>& tree, std::vector<std::vector<Size> >& clusters))) { Size a[] = {0,1,2,3,4,5}; vector< vector<Size> > clusters; vector< vector<Size> > result; result.push_back(vector<Size>(a,a+3)); result.push_back(vector<Size>(a+3,a+5)); result.push_back(vector<Size>(a+5,a+6)); vector< BinaryTreeNode > tree; tree.push_back(BinaryTreeNode(1,2,0.3f)); tree.push_back(BinaryTreeNode(3,4,0.4f)); tree.push_back(BinaryTreeNode(0,1,0.5f)); tree.push_back(BinaryTreeNode(0,3,0.6f)); tree.push_back(BinaryTreeNode(0,5,0.7f)); ptr->cut(3, tree, clusters); TEST_EQUAL(clusters.size(), result.size()); for (Size i = 0; i < clusters.size(); ++i) { TEST_EQUAL(clusters[i].size(), result[i].size()); for (Size j = 0; j < clusters[i].size(); ++j) { TEST_EQUAL(clusters[i][j], result[i][j]); } } Size b[] = {0,1,5,8,10,12,2,3,9,11,4,6,7}; result.clear(); result.push_back(vector<Size>(b,b+1)); result.push_back(vector<Size>(b+1,b+6)); result.push_back(vector<Size>(b+6,b+10)); result.push_back(vector<Size>(b+10,b+13)); std::vector< BinaryTreeNode > trunk; trunk.push_back(BinaryTreeNode(4,6,0.1f)); trunk.push_back(BinaryTreeNode(2,3,0.11f)); trunk.push_back(BinaryTreeNode(5,8,0.111f)); trunk.push_back(BinaryTreeNode(4,7,0.2f)); trunk.push_back(BinaryTreeNode(2,9,0.22f)); trunk.push_back(BinaryTreeNode(1,10,0.222f)); trunk.push_back(BinaryTreeNode(2,11,0.3f)); trunk.push_back(BinaryTreeNode(1,5,0.33f)); trunk.push_back(BinaryTreeNode(1,12,0.333f)); trunk.push_back(BinaryTreeNode(0,1,-1.0f)); trunk.push_back(BinaryTreeNode(0,2,-1.0f)); trunk.push_back(BinaryTreeNode(0,4,-1.0f)); clusters.clear(); ptr->cut(4, trunk, clusters); TEST_EQUAL(clusters.size(), result.size()); for (Size i = 0; i < clusters.size(); ++i) { TEST_EQUAL(clusters[i].size(), result[i].size()); for (Size j = 0; j < clusters[i].size(); ++j) { TEST_EQUAL(clusters[i][j], result[i][j]); } } } END_SECTION START_SECTION((void cut(const Size cluster_quantity, const std::vector<BinaryTreeNode>& tree, std::vector< std::vector<BinaryTreeNode> >& subtrees))) { std::vector< std::vector< BinaryTreeNode > > c_ts(4),ts; std::vector< BinaryTreeNode > trunk; trunk.push_back(BinaryTreeNode(4,6,0.1f)); trunk.push_back(BinaryTreeNode(2,3,0.11f)); trunk.push_back(BinaryTreeNode(5,8,0.111f)); trunk.push_back(BinaryTreeNode(4,7,0.2f)); trunk.push_back(BinaryTreeNode(2,9,0.22f)); trunk.push_back(BinaryTreeNode(1,10,0.222f)); trunk.push_back(BinaryTreeNode(2,11,0.3f)); trunk.push_back(BinaryTreeNode(1,5,0.33f)); trunk.push_back(BinaryTreeNode(1,12,0.333f)); trunk.push_back(BinaryTreeNode(0,1,-1.0f)); trunk.push_back(BinaryTreeNode(0,2,-1.0f)); trunk.push_back(BinaryTreeNode(0,4,-1.0f)); //~ c_ts[0].push_back(BinaryTreeNode(0,1,-1.0f)); //~ c_ts[0].push_back(BinaryTreeNode(0,2,-1.0f)); //~ c_ts[0].push_back(BinaryTreeNode(0,4,-1.0f)); c_ts[1].push_back(BinaryTreeNode(5,8,0.111f)); c_ts[1].push_back(BinaryTreeNode(1,10,0.222f)); c_ts[1].push_back(BinaryTreeNode(1,5,0.33f)); c_ts[1].push_back(BinaryTreeNode(1,12,0.333f)); c_ts[2].push_back(BinaryTreeNode(2,3,0.11f)); c_ts[2].push_back(BinaryTreeNode(2,9,0.22f)); c_ts[2].push_back(BinaryTreeNode(2,11,0.3f)); c_ts[3].push_back(BinaryTreeNode(4,6,0.1f)); c_ts[3].push_back(BinaryTreeNode(4,7,0.2f)); ptr->cut(4, trunk, ts); TEST_EQUAL(ts.size(), c_ts.size()); for (Size i = 0; i < c_ts.size() && i < ts.size(); ++i) { TEST_EQUAL(ts[i].size(), c_ts[i].size()); for (Size j = 0; j < ts[i].size() && j < c_ts[i].size(); ++j) { TEST_EQUAL(ts[i][j].right_child, c_ts[i][j].right_child); TEST_EQUAL(ts[i][j].left_child, c_ts[i][j].left_child); TEST_EQUAL(ts[i][j].distance, c_ts[i][j].distance); } } } END_SECTION START_SECTION((String newickTree(const std::vector<BinaryTreeNode>& tree, const bool include_distance = false))) { vector< BinaryTreeNode > tree; tree.push_back(BinaryTreeNode(1,2,0.3f)); tree.push_back(BinaryTreeNode(3,4,0.4f)); tree.push_back(BinaryTreeNode(0,1,0.5f)); tree.push_back(BinaryTreeNode(0,3,0.6f)); tree.push_back(BinaryTreeNode(0,5,0.7f)); String result = ptr->newickTree(tree); TEST_EQUAL(result,"( ( ( 0 , ( 1 , 2 ) ) , ( 3 , 4 ) ) , 5 )"); result = ptr->newickTree(tree,true); TEST_EQUAL(result,"( ( ( 0:0.5 , ( 1:0.3 , 2:0.3 ):0.5 ):0.6 , ( 3:0.4 , 4:0.4 ):0.6 ):0.7 , 5:0.7 )"); } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SplinePackage_test.cpp
.cpp
2,253
85
// 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/PROCESSING/MISC/SplinePackage.h> using namespace OpenMS; START_TEST(SplinePackage, "$Id$") std::vector<double> mz; mz.push_back(413.8); mz.push_back(413.9); mz.push_back(414.0); mz.push_back(414.1); mz.push_back(414.2); std::vector<double> intensity; intensity.push_back(0.0); intensity.push_back(100.2); intensity.push_back(20.3); intensity.push_back(2000.4); intensity.push_back(4.3); std::vector<double> mz1; mz1.push_back(413.9); std::vector<double> intensity1; intensity1.push_back(100.2); std::vector<double> mz2; mz2.push_back(413.8); mz2.push_back(413.9); std::vector<double> intensity2; intensity2.push_back(0.0); intensity2.push_back(100.2); SplinePackage sp1(mz, intensity); SplinePackage* nullPointer = nullptr; START_SECTION(SplinePackage(std::vector<double> mz, std::vector<double> intensity)) SplinePackage* sp2 = new SplinePackage(mz, intensity); TEST_NOT_EQUAL(sp2, nullPointer) delete sp2; END_SECTION START_SECTION(getPosMin()) TEST_EQUAL(sp1.getPosMin(), 413.8); END_SECTION START_SECTION(getPosMax()) TEST_EQUAL(sp1.getPosMax(), 414.2); END_SECTION START_SECTION(getPosStepWidth()) TEST_REAL_SIMILAR(sp1.getPosStepWidth(), 0.1); END_SECTION START_SECTION(isInPackage(double mz)) TEST_EQUAL(sp1.isInPackage(414.05), true); END_SECTION START_SECTION(eval(double mz)) TEST_REAL_SIMILAR(sp1.eval(414.05), 1134.08593750018); END_SECTION START_SECTION(SplinePackage(std::vector<double> mz, std::vector<double> intensity)) TEST_EXCEPTION(Exception::IllegalArgument, SplinePackage(mz1, intensity1)); END_SECTION START_SECTION(SplinePackage(std::vector<double> mz, std::vector<double> intensity)) SplinePackage* sp4 = new SplinePackage(mz2, intensity2); TEST_NOT_EQUAL(sp4, nullPointer); TEST_REAL_SIMILAR((*sp4).eval(413.85), 50.1); delete sp4; END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GaussFitter_test.cpp
.cpp
3,899
159
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Andreas Bertsch, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/MATH/STATISTICS/GaussFitter.h> /////////////////////////// using namespace OpenMS; using namespace Math; using namespace std; START_TEST(GaussFitter, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// GaussFitter* ptr = nullptr; GaussFitter* nullPointer = nullptr; START_SECTION(GaussFitter()) { ptr = new GaussFitter(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((virtual ~GaussFitter())) { delete ptr; NOT_TESTABLE } END_SECTION double mz[] = { 240.1000470172, 240.1002675493, 240.1004880817, 240.1007086145, 240.1009291475, 240.1011496808, 240.1013702145}; double ints[] = { 61134.39453125, 111288.5390625, 163761.46875, 165861.4375, 162133.46875, 120060.5234375, 71102.1328125, }; // initial guesses double max_peak_int = 168324; double max_peak_mz = 240.10051; double sigma = 0.000375375; Math::GaussFitter::GaussFitResult gfi(max_peak_int, max_peak_mz, sigma); START_SECTION((GaussFitResult fit(std::vector< DPosition< 2 > >& points) const)) { DPosition<2> pos; pos.setX(0.0); pos.setY(0.01); vector<DPosition<2> > points; points.push_back(pos); pos.setX(0.05); pos.setY(0.2); points.push_back(pos); pos.setX(0.16); pos.setY(0.63); points.push_back(pos); pos.setX(0.28); pos.setY(0.99); points.push_back(pos); pos.setX(0.66); pos.setY(0.03); points.push_back(pos); pos.setX(0.50); pos.setY(0.36); points.push_back(pos); ptr = new GaussFitter; GaussFitter::GaussFitResult result = ptr->fit(points); //TOLERANCE_ABSOLUTE(0.1) TEST_REAL_SIMILAR(result.A, 1.01898275662372) TEST_REAL_SIMILAR(result.x0, 0.300612870901173) TEST_REAL_SIMILAR(result.sigma, 0.136316330927453) //////////////////////////////////////// // second case which results in a negative sigma internally (requires using fabs()) //////////////////////////////////////// std::vector< DPosition< 2 > > gp; for (Size iii = 0; iii < 7; ++iii) { DPosition< 2 > d(mz[iii], ints[iii]); gp.push_back(d); } Math::GaussFitter gf; gf.setInitialParameters(gfi); Math::GaussFitter::GaussFitResult gfr = gf.fit(gp); /* x0: 240.10051 --> 240.1007246725147 sigma: 0.000375375 --> 0.00046642320683761701 A: 168324 --> 175011.8930067491 */ TEST_REAL_SIMILAR(gfr.A, 175011.893006749) TEST_REAL_SIMILAR(gfr.x0, 240.1007246725147) TEST_REAL_SIMILAR(gfr.sigma, 0.00046642320683761701) delete ptr; } END_SECTION START_SECTION((void setInitialParameters(const GaussFitResult& result))) { GaussFitter f1; GaussFitter::GaussFitResult result (-1,-1,-1); f1.setInitialParameters(result); NOT_TESTABLE //implicitly tested in fit method } END_SECTION START_SECTION((static std::vector<double> eval(const std::vector<double>& evaluation_points, const GaussFitResult& model))) GaussFitter f1; std::vector<double> rnd = Math::GaussFitter::eval(std::vector<double>(&mz[0], &mz[0] + 7), gfi); double int_fitted[] = { 78670.515322697669, 136633.77791868619, 168037.29915800504, 146337.00743127937, 90240.802825824489, 39405.008909696895, 12184.248044493703 }; for (Size i=0; i < rnd.size(); ++i) { TEST_REAL_SIMILAR(int_fitted[i], rnd[i]) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConsensusIDAlgorithmPEPIons_test.cpp
.cpp
1,312
50
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hendrik Weisser $ // $Authors: Marc Sturm, Andreas Bertsch, Sven Nahnsen, Hendrik Weisser $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmPEPIons.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(ConsensusIDAlgorithmPEPIons, "$Id$") ///////////////////////////////////////////////////////////// ConsensusIDAlgorithm* ptr = nullptr; ConsensusIDAlgorithm* null_pointer = nullptr; START_SECTION(ConsensusIDAlgorithmPEPIons()) { ptr = new ConsensusIDAlgorithmPEPIons(); TEST_NOT_EQUAL(ptr, null_pointer); } END_SECTION START_SECTION(~ConsensusIDAlgorithmPEPIons()) { delete(ptr); } END_SECTION START_SECTION(void apply(PeptideIdentificationList& ids)) { NOT_TESTABLE // tested by ConsensusID TOPP tool tests } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Bzip2InputStream_test.cpp
.cpp
2,997
86
// 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/Bzip2InputStream.h> using namespace OpenMS; /////////////////////////// START_TEST(Bzip2InputStream, "$Id$") xercesc::XMLPlatformUtils::Initialize(); Bzip2InputStream* ptr = nullptr; Bzip2InputStream* nullPointer = nullptr; START_SECTION(Bzip2InputStream(const char* const file_name)) TEST_EXCEPTION(Exception::FileNotFound, Bzip2InputStream bzip2(OPENMS_GET_TEST_DATA_PATH("ThisFileDoesNotExist"))) ptr = new Bzip2InputStream(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2")); TEST_NOT_EQUAL(ptr, nullPointer) TEST_EQUAL(ptr->getIsOpen(),true) END_SECTION START_SECTION((~Bzip2InputStream())) delete ptr; END_SECTION START_SECTION(Bzip2InputStream(const String& file_name)) TEST_EXCEPTION(Exception::FileNotFound, Bzip2InputStream bzip2(OPENMS_GET_TEST_DATA_PATH("ThisFileDoesNotExist"))) String filename = OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2"); ptr = new Bzip2InputStream(filename); TEST_NOT_EQUAL(ptr, nullPointer) TEST_EQUAL(ptr->getIsOpen(),true) delete ptr; END_SECTION START_SECTION(virtual XMLSize_t readBytes(XMLByte *const to_fill, const XMLSize_t max_to_read)) Bzip2InputStream bzip(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2")); char buffer[31]; buffer[30] = buffer[29] = '\0'; XMLByte* xml_buffer = reinterpret_cast<XMLByte* >(buffer); TEST_EQUAL(bzip.getIsOpen(),true) TEST_EQUAL(bzip.readBytes(xml_buffer,(XMLSize_t)10),10) TEST_EQUAL(bzip.readBytes(&xml_buffer[10],(XMLSize_t)10),10) TEST_EQUAL(bzip.readBytes(&xml_buffer[20],(XMLSize_t)9),9) TEST_EQUAL(String(buffer), String("Was decompression successful?")) TEST_EQUAL(bzip.getIsOpen(),true) TEST_EQUAL(bzip.readBytes(&xml_buffer[30],(XMLSize_t)10),1) TEST_EQUAL(bzip.getIsOpen(),false) END_SECTION START_SECTION(XMLFilePos curPos() const) Bzip2InputStream bzip(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2")); TEST_EQUAL(bzip.curPos(), 0) char buffer[31]; buffer[30] = buffer[29] = '\0'; XMLByte* xml_buffer = reinterpret_cast<XMLByte* >(buffer); bzip.readBytes(xml_buffer,(XMLSize_t)10); TEST_EQUAL(bzip.curPos(),10) END_SECTION START_SECTION(bool getIsOpen() const) //test above NOT_TESTABLE END_SECTION START_SECTION(virtual const XMLCh* getContentType() const) Bzip2InputStream bzip2(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2")); XMLCh* xmlch_nullPointer = nullptr; TEST_EQUAL(bzip2.getContentType(),xmlch_nullPointer) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/StringUtils_test.cpp
.cpp
16,946
514
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg, Chris Bielow $ // $Authors: Marc Sturm, Stephan Aiche, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/StringUtils.h> #include <OpenMS/DATASTRUCTURES/StringUtilsSimple.h> /////////////////////////// using namespace OpenMS; using namespace std; using namespace StringUtils; START_TEST(StringUtils, "$Id$") string whitespaces = "\t\r\n "; ///< all whitespaces we need to test START_SECTION(inline const char* skipWhitespace(const char* p, const char* p_end)) { // postfix with 16x, to enable SIMD on the prefix #define x16 "xxxxxxxxxxxxxxxx" #define s16 " " for (const char whitespace : whitespaces) { String at1 = "0 2 3456789101112" x16; at1.substitute(' ', whitespace); TEST_EQUAL(skipWhitespace(at1), 0); TEST_EQUAL(skipWhitespace(std::string_view(at1.data() + 1)), 1); TEST_EQUAL(skipWhitespace(std::string_view(at1.data() + 2)), 0); TEST_EQUAL(skipWhitespace(std::string_view(at1.data() + 3)), 2); String at2 = s16 s16 "1" x16; at2.substitute(' ', whitespace); TEST_EQUAL(skipWhitespace(std::string_view(at2.data())), 32); TEST_EQUAL(skipWhitespace(std::string_view(at2.data() + 2)), 30); String at1_noSSE = "0 2 34"; at1_noSSE.substitute(' ', whitespace); TEST_EQUAL(skipWhitespace(std::string_view(at1_noSSE.data())), 0); TEST_EQUAL(skipWhitespace(std::string_view(at1_noSSE.data() + 1)), 1); TEST_EQUAL(skipWhitespace(std::string_view(at1_noSSE.data() + 2)), 0); TEST_EQUAL(skipWhitespace(std::string_view(at1_noSSE.data() + 3)), 2); } } END_SECTION START_SECTION(inline const char* skipNonWhitespace(const char* p, const char* p_end)) { // postfix with 16x, to enable SIMD on the prefix #define x16 "xxxxxxxxxxxxxxxx" #define s16 " " for (const char whitespace : whitespaces) { String at1 = "0 2 3456789101112" x16; at1.substitute(' ', whitespace); TEST_EQUAL(skipNonWhitespace(at1), 1); TEST_EQUAL(skipNonWhitespace(std::string_view(at1.data() + 1)), 0); TEST_EQUAL(skipNonWhitespace(std::string_view(at1.data() + 2)), 1); TEST_EQUAL(skipNonWhitespace(std::string_view(at1.data() + 3)), 0); TEST_EQUAL(skipNonWhitespace(std::string_view(at1.data() + 5)), 13 + 16); String at2 = x16 x16 " " x16; at2.substitute(' ', whitespace); TEST_EQUAL(skipNonWhitespace(std::string_view(at2.data())), 32); TEST_EQUAL(skipNonWhitespace(std::string_view(at2.data() + 31)), 1); TEST_EQUAL(skipNonWhitespace(std::string_view(at2.data() + 33)), 16); String at1_noSSE = "0 2 34"; at1_noSSE.substitute(' ', whitespace); TEST_EQUAL(skipNonWhitespace(std::string_view(at1_noSSE.data())), 1); TEST_EQUAL(skipNonWhitespace(std::string_view(at1_noSSE.data() + 1)), 0); TEST_EQUAL(skipNonWhitespace(std::string_view(at1_noSSE.data() + 2)), 1); TEST_EQUAL(skipNonWhitespace(std::string_view(at1_noSSE.data() + 3)), 0); TEST_EQUAL(skipNonWhitespace(std::string_view(at1_noSSE.data() + 5)), 2); } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// StringUtilsHelper* ptr = nullptr; StringUtilsHelper* null_ptr = nullptr; START_SECTION(StringUtilsHelper()) { ptr = new StringUtilsHelper(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~StringUtilsHelper()) { delete ptr; } END_SECTION START_SECTION((static String numberLength(double d, UInt n))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String number(double d, UInt n))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& fillLeft(String &this_s, char c, UInt size))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& fillRight(String &this_s, char c, UInt size))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static bool hasPrefix(const String &this_s, const String &string))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static bool hasSuffix(const String &this_s, const String &string))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static bool hasSubstring(const String &this_s, const String &string))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static bool has(const String &this_s, Byte byte))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String prefix(const String &this_s, size_t length))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String suffix(const String &this_s, size_t length))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String prefix(const String &this_s, Int length))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String suffix(const String &this_s, Int length))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String prefix(const String &this_s, char delim))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String suffix(const String &this_s, char delim))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String substr(const String &this_s, size_t pos, size_t n))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String chop(const String &this_s, Size n))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& trim(String &this_s))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& quote(String &this_s, char q, String::QuotingMethod method))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& unquote(String &this_s, char q, String::QuotingMethod method))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& simplify(String &this_s))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String random(UInt length))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& reverse(String &this_s))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static bool split(const String &this_s, const char splitter, std::vector< String > &substrings, bool quote_protect))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static bool split(const String &this_s, const String &splitter, std::vector< String > &substrings))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static bool split_quoted(const String &this_s, const String &splitter, std::vector< String > &substrings, char q, String::QuotingMethod method))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static QString toQString(const String &this_s))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static Int32 toInt32(const String &this_s))) { // easy case TEST_EQUAL(StringUtils::toInt32("2147483647"), 2147483647) // with spaces (allowed) TEST_EQUAL(StringUtils::toInt32(" 2147483647"), 2147483647) TEST_EQUAL(StringUtils::toInt32("2147483647 "), 2147483647) TEST_EQUAL(StringUtils::toInt32(" 2147483647 "), 2147483647) // TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt32("2147483648")) // +1 too large TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt32("-2147483649")) // -1 too small // with trailing chars (unexplained) --> error (because it means the input was not split correctly beforehand)!!! TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt32("1234 moreText")) // 'moreText' is not explained... TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt32(" 1234 911.0")) // '911.0' is not explained... // incorrect type TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt32(" abc ")) TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt32(" 123.45 ")) } END_SECTION START_SECTION((static Int64 toInt64(const String &this_s))) { // easy case TEST_EQUAL(StringUtils::toInt64("9223372036854775807"), 9223372036854775807) // with spaces (allowed) TEST_EQUAL(StringUtils::toInt64(" 9223372036854775807"), 9223372036854775807) TEST_EQUAL(StringUtils::toInt64("9223372036854775807 "), 9223372036854775807) TEST_EQUAL(StringUtils::toInt64(" 9223372036854775807 "), 9223372036854775807) // TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt64("9223372036854775808")) // +1 too large TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt64("-9223372036854775809")) // -1 too small // with trailing chars (unexplained) --> error (because it means the input was not split correctly beforehand)!!! TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt64("1234 moreText")) // 'moreText' is not explained... TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt64(" 1234 911.0")) // '911.0' is not explained... // incorrect type TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt64(" abc ")) TEST_EXCEPTION(Exception::ConversionError, StringUtils::toInt64(" 123.45 ")) } END_SECTION START_SECTION((static float toFloat(const String &this_s))) { // easy case TEST_REAL_SIMILAR(StringUtils::toFloat("1234.45"), 1234.45) // with spaces (allowed) TEST_REAL_SIMILAR(StringUtils::toFloat(" 1234.45"), 1234.45) TEST_REAL_SIMILAR(StringUtils::toFloat("1234.45 "), 1234.45) TEST_REAL_SIMILAR(StringUtils::toFloat(" 1234.45 "), 1234.45) // with trailing chars (unexplained) --> error (because it means the input was not split correctly beforehand)!!! TEST_EXCEPTION(Exception::ConversionError, StringUtils::toFloat("1234.45 moreText")) // 'moreText' is not explained... TEST_EXCEPTION(Exception::ConversionError, StringUtils::toFloat(" 1234.45 911.0")) // '911.0' is not explained... // incorrect type TEST_EXCEPTION(Exception::ConversionError, StringUtils::toFloat(" abc ")) } END_SECTION START_SECTION((static double toDouble(const String &this_s))) { // easy case TEST_REAL_SIMILAR(StringUtils::toDouble("1234.45"), 1234.45) // with spaces (allowed) TEST_REAL_SIMILAR(StringUtils::toDouble(" 1234.45"), 1234.45) TEST_REAL_SIMILAR(StringUtils::toDouble("1234.45 "), 1234.45) TEST_REAL_SIMILAR(StringUtils::toDouble(" 1234.45 "), 1234.45) // with trailing chars (unexplained) --> error (because it means the input was not split correctly beforehand)!!! TEST_EXCEPTION(Exception::ConversionError, StringUtils::toDouble("1234.45 moreText")) // 'moreText' is not explained... TEST_EXCEPTION(Exception::ConversionError, StringUtils::toDouble(" 1234.45 911.0")) // '911.0' is not explained... // incorrect type TEST_EXCEPTION(Exception::ConversionError, StringUtils::toDouble(" abc ")) } END_SECTION START_SECTION((template <typename IteratorT> static bool extractDouble(IteratorT& begin, const IteratorT& end, double& target))) { double d; { std::string ss("12345.45 "); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractDouble(it, ss.end(), d), true); TEST_REAL_SIMILAR(d, 12345.45) TEST_EQUAL((int)std::distance(ss.begin(), it), 8); // was the iterator advanced? } { std::string ss("+1234.45!"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractDouble(it, ss.end(), d), true); TEST_REAL_SIMILAR(d, 1234.45) TEST_EQUAL((int)std::distance(ss.begin(), it), 8); // was the iterator advanced? } { d = 0; std::string ss(" -123.45"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractDouble(it, ss.end(), d), false); TEST_REAL_SIMILAR(d, 0) TEST_EQUAL((int)std::distance(ss.begin(), it), 0); // was the iterator advanced? } { std::string ss("15.0e6"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractDouble(it, ss.end(), d), true); TEST_REAL_SIMILAR(d, 15.0e6) TEST_EQUAL((int)std::distance(ss.begin(), it), 6); // was the iterator advanced? } { // try two doubles in a single stream (should stop after the first) std::string ss("-5.0 9.1"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractDouble(it, ss.end(), d), true); TEST_REAL_SIMILAR(d, -5.0) TEST_EQUAL((int)std::distance(ss.begin(), it), 4); // was the iterator advanced? auto it2 = ss.begin() + 5; TEST_EQUAL(StringUtils::extractDouble(it2, ss.end(), d), true); TEST_REAL_SIMILAR(d, 9.1) TEST_EQUAL((int)std::distance(ss.begin(), it2), 8); // was the iterator advanced? } { // explicitly test X.FeY vs XeY since some compilers implementation of the native operator>> stop reading at 'e' if no '.F' was seen std::string ss("15.0e6 x"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractDouble(it, ss.end(), d), true); TEST_REAL_SIMILAR(d, 15.0e6) TEST_EQUAL((int)std::distance(ss.begin(), it), 6); // was the iterator advanced? } { std::string ss("16e6!"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractDouble(it, ss.end(), d), true); TEST_REAL_SIMILAR(d, 16e+06) TEST_EQUAL((int)std::distance(ss.begin(), it), 4); // was the iterator advanced? } { std::string ss("!noNumber"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractDouble(it, ss.end(), d), false); TEST_EQUAL((int)std::distance(ss.begin(), it), 0); // was the iterator advanced? } } END_SECTION START_SECTION((template <typename IteratorT> static bool extractInt(IteratorT& begin, const IteratorT& end, int& target))) { int i; { std::string ss("12345 "); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractInt(it, ss.end(), i), true); TEST_EQUAL(i, 12345) TEST_EQUAL((int)std::distance(ss.begin(), it), 5); // was the iterator advanced? } { std::string ss("+1234!"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractInt(it, ss.end(), i), true); TEST_EQUAL(i, 1234) TEST_EQUAL((int)std::distance(ss.begin(), it), 5); // was the iterator advanced? } { i = 0; std::string ss(" -123"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractInt(it, ss.end(), i), false); TEST_EQUAL(i, 0) TEST_EQUAL((int)std::distance(ss.begin(), it), 0); // was the iterator advanced? } { std::string ss("y15++"); auto it = ss.begin() + 1; TEST_EQUAL(StringUtils::extractInt(it, ss.end(), i), true); TEST_EQUAL(i, 15) TEST_EQUAL((int)std::distance(ss.begin(), it), 3); // was the iterator advanced? } { // try two ints in a single stream (should stop after the first) std::string ss("-5 9"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractInt(it, ss.end(), i), true); TEST_EQUAL(i, -5) TEST_EQUAL((int)std::distance(ss.begin(), it), 2); // was the iterator advanced? auto it2 = ss.begin() + 3; TEST_EQUAL(StringUtils::extractInt(it2, ss.end(), i), true); TEST_EQUAL(i, 9) TEST_EQUAL((int)std::distance(ss.begin(), it2), 4); // was the iterator advanced? } { std::string ss("!noNumber"); auto it = ss.begin(); TEST_EQUAL(StringUtils::extractInt(it, ss.end(), i), false); TEST_EQUAL((int)std::distance(ss.begin(), it), 0); // was the iterator advanced? } } END_SECTION START_SECTION((static String& toUpper(String &this_s))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& firstToUpper(String &this_s))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& toLower(String &this_s))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& substitute(String &this_s, char from, char to))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& substitute(String &this_s, const String &from, const String &to))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& remove(String &this_s, char what))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& ensureLastChar(String &this_s, char end))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION START_SECTION((static String& removeWhitespaces(String &this_s))) { NOT_TESTABLE // tested in String_test.cpp } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/LabeledPairFinder_test.cpp
.cpp
4,493
156
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/LabeledPairFinder.h> /////////////////////////// #include <OpenMS/KERNEL/ConversionHelper.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> using namespace OpenMS; using namespace std; START_TEST(LabeledPairFinder, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// LabeledPairFinder* ptr = nullptr; LabeledPairFinder* nullPointer = nullptr; START_SECTION((LabeledPairFinder())) ptr = new LabeledPairFinder(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~LabeledPairFinder())) delete ptr; END_SECTION FeatureMap features; features.resize(10); //start features[0].setRT(1.0f); features[0].setMZ(1.0f); features[0].setCharge(1); features[0].setOverallQuality(1); features[0].setIntensity(4.0f); //best features[1].setRT(1.5f); features[1].setMZ(5.0f); features[1].setCharge(1); features[1].setOverallQuality(1); features[1].setIntensity(2.0f); //inside (down, up, left, right) features[2].setRT(1.0f); features[2].setMZ(5.0f); features[2].setCharge(1); features[2].setOverallQuality(1); features[3].setRT(3.0f); features[3].setMZ(5.0f); features[3].setCharge(1); features[3].setOverallQuality(1); features[4].setRT(1.5f); features[4].setMZ(4.8f); features[4].setCharge(1); features[4].setOverallQuality(1); features[5].setRT(1.5f); features[5].setMZ(5.2f); features[5].setCharge(1); features[5].setOverallQuality(1); //outside (down, up, left, right) features[6].setRT(0.0f); features[6].setMZ(5.0f); features[6].setCharge(1); features[6].setOverallQuality(1); features[7].setRT(4.0f); features[7].setMZ(5.0f); features[7].setCharge(1); features[7].setOverallQuality(1); features[8].setRT(1.5f); features[8].setMZ(4.0f); features[8].setCharge(1); features[8].setOverallQuality(1); features[9].setRT(1.5f); features[9].setMZ(6.0f); features[9].setCharge(1); features[9].setOverallQuality(1); START_SECTION((virtual void run(const std::vector<ConsensusMap>& input_maps, ConsensusMap& result_map))) LabeledPairFinder pm; Param p; p.setValue("rt_estimate","false"); p.setValue("rt_pair_dist",0.4); p.setValue("rt_dev_low",1.0); p.setValue("rt_dev_high",2.0); p.setValue("mz_pair_dists",ListUtils::create<double>(4.0)); p.setValue("mz_dev",0.6); pm.setParameters(p); ConsensusMap output; TEST_EXCEPTION(Exception::IllegalArgument,pm.run(vector<ConsensusMap>(),output)); vector<ConsensusMap> input(1); MapConversion::convert(5,features,input[0]); output.getColumnHeaders()[5].label = "light"; output.getColumnHeaders()[5].filename = "filename"; output.getColumnHeaders()[8] = output.getColumnHeaders()[5]; output.getColumnHeaders()[8].label = "heavy"; pm.run(input,output); TEST_EQUAL(output.size(),1); ABORT_IF(output.size()!=1) TEST_REAL_SIMILAR(output[0].begin()->getMZ(),1.0f); TEST_REAL_SIMILAR(output[0].begin()->getRT(),1.0f); TEST_REAL_SIMILAR(output[0].rbegin()->getMZ(),5.0f); TEST_REAL_SIMILAR(output[0].rbegin()->getRT(),1.5f); TEST_REAL_SIMILAR(output[0].getQuality(),0.959346); TEST_EQUAL(output[0].getCharge(),1); //test automated RT parameter estimation LabeledPairFinder pm2; Param p2; p2.setValue("rt_estimate","true"); p2.setValue("mz_pair_dists", ListUtils::create<double>(4.0)); p2.setValue("mz_dev",0.2); pm2.setParameters(p2); FeatureMap features2; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("LabeledPairFinder.featureXML"),features2); ConsensusMap output2; vector<ConsensusMap> input2(1); MapConversion::convert(5,features2,input2[0]); output2.getColumnHeaders()[5].label = "light"; output2.getColumnHeaders()[5].filename = "filename"; output2.getColumnHeaders()[8] = output.getColumnHeaders()[5]; output2.getColumnHeaders()[8].label = "heavy"; pm2.run(input2,output2); TEST_EQUAL(output2.size(),250); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Weights_test.cpp
.cpp
8,234
305
// 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/IMSAlphabet.h> #include <OpenMS/CHEMISTRY/ResidueDB.h> #include <OpenMS/CHEMISTRY/Residue.h> #include <set> /////////////////////////// #include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/Weights.h> /////////////////////////// using namespace OpenMS; using namespace ims; using namespace std; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_TEST(Weights, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Weights* ptr = nullptr; Weights* null_ptr = nullptr; Weights::alphabet_masses_type masses; masses.push_back(71.0456); masses.push_back(180.0312); masses.push_back(1.0186); masses.push_back(4284.36894); masses.push_back(255.0); START_SECTION(Weights()) { ptr = new Weights(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~Weights()) { delete ptr; } END_SECTION START_SECTION((Weights(const alphabet_masses_type &masses, alphabet_mass_type prec))) { Weights::alphabet_mass_type precision = 0.01; ptr = new Weights(masses, precision); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION((Weights(const Weights &other))) { Weights copy(*ptr); TEST_NOT_EQUAL(&copy, null_ptr) // test equality of copy and ptr ABORT_IF(ptr->size()!=copy.size()) for(Size i = 0 ; i < ptr->size() ; ++i) { TEST_EQUAL(ptr->getAlphabetMass(i), copy.getAlphabetMass(i)) TEST_EQUAL(ptr->getWeight(i), copy.getWeight(i)) TEST_EQUAL((*ptr)[i], copy[i]) } } END_SECTION START_SECTION((Weights& operator=(const Weights &weights_))) { Weights copy; copy = *ptr; TEST_NOT_EQUAL(&copy, null_ptr) // test equality of copy and ptr ABORT_IF(ptr->size()!=copy.size()) for(Size i = 0 ; i < ptr->size() ; ++i) { TEST_EQUAL(ptr->getAlphabetMass(i), copy.getAlphabetMass(i)) TEST_EQUAL(ptr->getWeight(i), copy.getWeight(i)) TEST_EQUAL((*ptr)[i], copy[i]) } } END_SECTION START_SECTION((size_type size() const )) { TEST_EQUAL(ptr->size(), 5) Weights w; TEST_EQUAL(w.size(),0) } END_SECTION START_SECTION((weight_type getWeight(size_type i) const )) { TEST_EQUAL(ptr->getWeight(0), 7105) TEST_EQUAL(ptr->getWeight(1), 18003) TEST_EQUAL(ptr->getWeight(2), 102) TEST_EQUAL(ptr->getWeight(3), 428437); TEST_EQUAL(ptr->getWeight(4), 25500) } END_SECTION START_SECTION((void setPrecision(alphabet_mass_type precision_))) { ptr->setPrecision(0.1); TEST_EQUAL(ptr->getWeight(0), 710) TEST_EQUAL(ptr->getWeight(1), 1800) TEST_EQUAL(ptr->getWeight(2), 10) TEST_EQUAL(ptr->getWeight(3), 42844) TEST_EQUAL(ptr->getWeight(4), 2550) ptr->setPrecision(1); TEST_EQUAL(ptr->getWeight(0), 71) TEST_EQUAL(ptr->getWeight(1), 180) TEST_EQUAL(ptr->getWeight(2), 1) TEST_EQUAL(ptr->getWeight(3), 4284) TEST_EQUAL(ptr->getWeight(4), 255) ptr->setPrecision(0.0001); TEST_EQUAL(ptr->getWeight(0), 710456) TEST_EQUAL(ptr->getWeight(1), 1800312) TEST_EQUAL(ptr->getWeight(2), 10186) TEST_EQUAL(ptr->getWeight(3), 42843689) TEST_EQUAL(ptr->getWeight(4), 2550000) ptr->setPrecision(0.01); TEST_EQUAL(ptr->getWeight(0), 7105) TEST_EQUAL(ptr->getWeight(1), 18003) TEST_EQUAL(ptr->getWeight(2), 102) TEST_EQUAL(ptr->getWeight(3), 428437) TEST_EQUAL(ptr->getWeight(4), 25500) } END_SECTION START_SECTION((alphabet_mass_type getPrecision() const )) { TEST_EQUAL(ptr->getPrecision(), 0.01) ptr->setPrecision(0.00025); TEST_EQUAL(ptr->getPrecision(), 0.00025) ptr->setPrecision(0.01); TEST_EQUAL(ptr->getPrecision(), 0.01) } END_SECTION START_SECTION((weight_type operator[](size_type i) const )) { TEST_EQUAL((*ptr)[0], 7105) TEST_EQUAL((*ptr)[1], 18003) TEST_EQUAL((*ptr)[2], 102) TEST_EQUAL((*ptr)[3], 428437) TEST_EQUAL((*ptr)[4], 25500) } END_SECTION START_SECTION((weight_type back() const )) { TEST_EQUAL((*ptr)[4], 25500); TEST_EQUAL(ptr->back(), 25500); } END_SECTION START_SECTION((alphabet_mass_type getAlphabetMass(size_type i) const )) { // compare with the masses it was created from ABORT_IF(ptr->size() != masses.size()) for(Size i = 0 ; i < ptr->size() ; ++i) { TEST_EQUAL(ptr->getAlphabetMass(i), masses[i]) } } END_SECTION START_SECTION((alphabet_mass_type getParentMass(const std::vector< unsigned int > &decomposition) const )) { vector<unsigned int> base_decomposition(5,0); for(Size i = 0 ; i < ptr->size() ; ++i) { vector<unsigned int> decomposition(base_decomposition); decomposition[i] = 1; TEST_REAL_SIMILAR(ptr->getParentMass(decomposition), masses[i]) decomposition[i] = 2; TEST_REAL_SIMILAR(ptr->getParentMass(decomposition), 2*masses[i]) } vector<unsigned int> wrong_decomposition(3,0); TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidParameter, ptr->getParentMass(wrong_decomposition),"The passed decomposition has the wrong size. Expected 5 but got 3.") } END_SECTION START_SECTION((void swap(size_type index1, size_type index2))) { Weights copy_to_swap(*ptr); copy_to_swap.swap(0,1); TEST_EQUAL(ptr->getAlphabetMass(0), copy_to_swap.getAlphabetMass(1)) TEST_EQUAL(ptr->getAlphabetMass(1), copy_to_swap.getAlphabetMass(0)) TEST_EQUAL(ptr->getWeight(0), copy_to_swap.getWeight(1)) TEST_EQUAL(ptr->getWeight(1), copy_to_swap.getWeight(0)) copy_to_swap.swap(1,3); TEST_EQUAL(ptr->getAlphabetMass(0), copy_to_swap.getAlphabetMass(3)) TEST_EQUAL(ptr->getAlphabetMass(3), copy_to_swap.getAlphabetMass(1)) TEST_EQUAL(ptr->getWeight(0), copy_to_swap.getWeight(3)) TEST_EQUAL(ptr->getWeight(3), copy_to_swap.getWeight(1)) } END_SECTION START_SECTION((bool divideByGCD())) { // we use the example from the documentation here to demonstrate that // it works // For example, given alphabet weights 3.0, 5.0, 8.0 with precision 0.1, the // integer weights would be 30, 50, 80. After calling this method, the new // weights are 3, 5, 8 with precision 1.0 (since the gcd of 30, 50, and 80 // is 10). Weights::alphabet_masses_type masses_local; masses_local.push_back(3.0); masses_local.push_back(5.0); masses_local.push_back(8.0); Weights weights_to_test_gcd(masses_local, 0.1); TEST_EQUAL(weights_to_test_gcd.divideByGCD(), true) TEST_EQUAL(weights_to_test_gcd[0],3) TEST_EQUAL(weights_to_test_gcd[1],5) TEST_EQUAL(weights_to_test_gcd[2],8) TEST_EQUAL(weights_to_test_gcd.getPrecision(), 1.0) // calling it again should not change anything TEST_EQUAL(weights_to_test_gcd.divideByGCD(), false) Weights::alphabet_masses_type prime_masses; prime_masses.push_back(1.13); prime_masses.push_back(1.67); prime_masses.push_back(2.41); Weights prime_weights(prime_masses, 0.01); // we cannot find a GCD here TEST_EQUAL(prime_weights.divideByGCD(), false) Weights::alphabet_masses_type not_enough_masses; not_enough_masses.push_back(40); Weights not_enough_entries_weights(not_enough_masses,0.01); // we cannot divide by GCD if we only have 1 entry TEST_EQUAL(not_enough_entries_weights.divideByGCD(), false) } END_SECTION START_SECTION((alphabet_mass_type getMinRoundingError() const )) { TEST_REAL_SIMILAR(ptr->getMinRoundingError(), -6.6655113114361e-06) // for 255.0 -> 25500 ptr->setPrecision(10); TEST_REAL_SIMILAR(ptr->getMinRoundingError(), -1.0) // for 1.0186 -> 0 ptr->setPrecision(0.01); } END_SECTION START_SECTION((alphabet_mass_type getMaxRoundingError() const )) { TEST_REAL_SIMILAR(ptr->getMaxRoundingError(), 0.00137443549970554) ptr->setPrecision(10); TEST_REAL_SIMILAR(ptr->getMaxRoundingError(), 0.0196078431372549) } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ControlledVocabulary_test.cpp
.cpp
11,178
285
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Authors: Marc Sturm, Andreas Bertsch, Mathias Walzer$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/ControlledVocabulary.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/DATASTRUCTURES/ListUtilsIO.h> #include <OpenMS/SYSTEM/File.h> #include <map> /////////////////////////// START_TEST(ControlledVocabulary, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; ControlledVocabulary* ptr = nullptr; ControlledVocabulary* nullPointer = nullptr; START_SECTION((ControlledVocabulary())) ptr = new ControlledVocabulary(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~ControlledVocabulary())) delete ptr; END_SECTION START_SECTION(const String& name() const) TEST_EQUAL(ControlledVocabulary().name(),"") END_SECTION ControlledVocabulary cv; START_SECTION(void loadFromOBO(const String &name, const String &filename)) cv.loadFromOBO("bla",OPENMS_GET_TEST_DATA_PATH("ControlledVocabulary.obo")); TEST_EQUAL(cv.name(),"bla") END_SECTION START_SECTION(bool exists(const String& id) const) TEST_EQUAL(cv.exists("OpenMS:1"),true) TEST_EQUAL(cv.exists("OpenMS:2"),true) TEST_EQUAL(cv.exists("OpenMS:3"),true) TEST_EQUAL(cv.exists("OpenMS:4"),true) TEST_EQUAL(cv.exists("OpenMS:5"),true) TEST_EQUAL(cv.exists("OpenMS:6"),true) TEST_EQUAL(cv.exists("OpenMS:7"),false) END_SECTION START_SECTION(const CVTerm& getTerm(const String& id) const) const ControlledVocabulary::CVTerm* term=nullptr; //Auto term = &(cv.getTerm("OpenMS:1")); TEST_EQUAL(term->id,"OpenMS:1") TEST_EQUAL(term->name,"Auto") TEST_EQUAL(term->description,"Auto desc") TEST_EQUAL(term->obsolete,false) TEST_EQUAL(term->parents.size(),0) TEST_EQUAL(term->unparsed.size(),0) TEST_EQUAL(term->synonyms.size(),2) TEST_STRING_EQUAL(term->synonyms[0],"Kutsche") TEST_STRING_EQUAL(term->synonyms[1],"Karre") //Ford term = &(cv.getTerm("OpenMS:2")); TEST_EQUAL(term->id,"OpenMS:2") TEST_EQUAL(term->name,"Ford") TEST_EQUAL(term->obsolete,false) TEST_EQUAL(term->parents.size(),1) TEST_EQUAL(*term->parents.begin(),"OpenMS:1") TEST_EQUAL(term->unparsed.size(),0) TEST_EQUAL(term->synonyms.size(),0) //Mercedes term = &(cv.getTerm("OpenMS:3")); TEST_EQUAL(term->id,"OpenMS:3") TEST_EQUAL(term->name,"Mercedes") TEST_EQUAL(term->obsolete,false) TEST_EQUAL(term->parents.size(),1) TEST_EQUAL(*term->parents.begin(),"OpenMS:1") TEST_STRING_EQUAL(term->synonyms[0],"Zedes") //A-Klasse term = &(cv.getTerm("OpenMS:4")); TEST_EQUAL(term->id,"OpenMS:4") TEST_EQUAL(term->name,"A-Klasse") TEST_EQUAL(term->description,"A-Klasse desc") TEST_EQUAL(term->obsolete,false) TEST_EQUAL(term->parents.size(),1) TEST_EQUAL(*term->parents.begin(),"OpenMS:3") TEST_EQUAL(term->unparsed.size(),3) TEST_EQUAL(term->unparsed[0],"xref: unparsed line 1") TEST_EQUAL(term->unparsed[1],"xref: unparsed line 2") TEST_EQUAL(term->unparsed[2],"xref: unparsed line 3") TEST_EQUAL(term->synonyms.size(),0) //Mustang term = &(cv.getTerm("OpenMS:5")); TEST_EQUAL(term->id,"OpenMS:5") TEST_EQUAL(term->name,"Mustang") TEST_EQUAL(term->obsolete,false) TEST_EQUAL(term->parents.size(),1) TEST_EQUAL(*term->parents.begin(),"OpenMS:2") TEST_EQUAL(term->unparsed.size(),0) TEST_EQUAL(term->synonyms.size(),0) //Ka term = &(cv.getTerm("OpenMS:6")); TEST_EQUAL(term->id,"OpenMS:6") TEST_EQUAL(term->name,"Ka") TEST_EQUAL(term->description,"Ka desc") TEST_EQUAL(term->obsolete,true) TEST_EQUAL(term->parents.size(),1) TEST_EQUAL(*term->parents.begin(),"OpenMS:2") TEST_EQUAL(term->unparsed.size(),0) TEST_EQUAL(term->synonyms.size(),0) TEST_EXCEPTION(Exception::InvalidValue, cv.getTerm("OpenMS:7")) END_SECTION START_SECTION(bool isChildOf(const String& child, const String& parent) const) TEST_EQUAL(cv.isChildOf("OpenMS:6","OpenMS:2"),true) TEST_EQUAL(cv.isChildOf("OpenMS:5","OpenMS:2"),true) TEST_EQUAL(cv.isChildOf("OpenMS:2","OpenMS:1"),true) TEST_EQUAL(cv.isChildOf("OpenMS:3","OpenMS:1"),true) TEST_EQUAL(cv.isChildOf("OpenMS:4","OpenMS:3"),true) TEST_EQUAL(cv.isChildOf("OpenMS:1","OpenMS:6"),false) TEST_EQUAL(cv.isChildOf("OpenMS:4","OpenMS:6"),false) TEST_EQUAL(cv.isChildOf("OpenMS:2","OpenMS:6"),false) TEST_EQUAL(cv.isChildOf("OpenMS:2","OpenMS:3"),false) TEST_EXCEPTION(Exception::InvalidValue, cv.isChildOf("OpenMS:7","OpenMS:3")) END_SECTION START_SECTION((const Map<String, CVTerm>& getTerms() const)) const auto& terms = cv.getTerms(); TEST_EQUAL(terms.size(), 6) TEST_EQUAL(terms.find("OpenMS:1") != terms.end(), true) TEST_EQUAL(terms.find("OpenMS:2") != terms.end(), true) TEST_EQUAL(terms.find("OpenMS:3") != terms.end(), true) TEST_EQUAL(terms.find("OpenMS:4") != terms.end(), true) TEST_EQUAL(terms.find("OpenMS:5") != terms.end(), true) TEST_EQUAL(terms.find("OpenMS:6") != terms.end(), true) TEST_EQUAL(terms.find("OpenMS:7") != terms.end(), false) END_SECTION START_SECTION((void getAllChildTerms(std::set<String>& terms, const String& parent) const)) set<String> terms; cv.getAllChildTerms(terms, "OpenMS:2"); TEST_EQUAL(terms.size(), 2) TEST_EQUAL(terms.find("OpenMS:2") == terms.end(), true) TEST_EQUAL(terms.find("OpenMS:5") == terms.end(), false) END_SECTION ControlledVocabulary::CVTerm * cvterm = nullptr; ControlledVocabulary::CVTerm * cvtermNullPointer = nullptr; START_SECTION(([ControlledVocabulary::CVTerm] CVTerm())) { cvterm = new ControlledVocabulary::CVTerm(); TEST_NOT_EQUAL(cvterm, cvtermNullPointer) delete cvterm; } END_SECTION START_SECTION(([ControlledVocabulary::CVTerm] static String getXRefTypeName(XRefType type))) { TEST_STRING_EQUAL(ControlledVocabulary::CVTerm::getXRefTypeName(ControlledVocabulary::CVTerm::XRefType::XSD_STRING), "xsd:string") TEST_STRING_EQUAL(ControlledVocabulary::CVTerm::getXRefTypeName(ControlledVocabulary::CVTerm::XRefType::XSD_INTEGER), "xsd:integer") TEST_STRING_EQUAL(ControlledVocabulary::CVTerm::getXRefTypeName(ControlledVocabulary::CVTerm::XRefType::XSD_DECIMAL), "xsd:decimal") TEST_STRING_EQUAL(ControlledVocabulary::CVTerm::getXRefTypeName(ControlledVocabulary::CVTerm::XRefType::XSD_NEGATIVE_INTEGER), "xsd:negativeInteger") TEST_STRING_EQUAL(ControlledVocabulary::CVTerm::getXRefTypeName(ControlledVocabulary::CVTerm::XRefType::XSD_POSITIVE_INTEGER), "xsd:positiveInteger") TEST_STRING_EQUAL(ControlledVocabulary::CVTerm::getXRefTypeName(ControlledVocabulary::CVTerm::XRefType::XSD_NON_NEGATIVE_INTEGER), "xsd:nonNegativeInteger") TEST_STRING_EQUAL(ControlledVocabulary::CVTerm::getXRefTypeName(ControlledVocabulary::CVTerm::XRefType::XSD_NON_POSITIVE_INTEGER), "xsd:nonPositiveInteger") TEST_STRING_EQUAL(ControlledVocabulary::CVTerm::getXRefTypeName(ControlledVocabulary::CVTerm::XRefType::XSD_BOOLEAN), "xsd:boolean") TEST_STRING_EQUAL(ControlledVocabulary::CVTerm::getXRefTypeName(ControlledVocabulary::CVTerm::XRefType::XSD_DATE), "xsd:date") TEST_STRING_EQUAL(ControlledVocabulary::CVTerm::getXRefTypeName(ControlledVocabulary::CVTerm::XRefType::XSD_ANYURI), "xsd:anyURI") } END_SECTION START_SECTION(([ControlledVocabulary::CVTerm] bool ControlledVocabulary::CVTerm::isHigherBetterScore(ControlledVocabulary::CVTerm term))) { ControlledVocabulary cv; cv.loadFromOBO("PSI-MS", File::find("/CV/psi-ms.obo")); TEST_EQUAL(ControlledVocabulary::CVTerm::isHigherBetterScore(cv.getTerm("MS:1001331")),true) TEST_EQUAL(ControlledVocabulary::CVTerm::isHigherBetterScore(cv.getTerm("MS:1002265")),false) TEST_EQUAL(ControlledVocabulary::CVTerm::isHigherBetterScore(cv.getTerm("MS:1002467")),true) } END_SECTION START_SECTION(([ControlledVocabulary::CVTerm] String ControlledVocabulary::CVTerm::toXMLString(const OpenMS::String& ref, const String& value) const)) { ControlledVocabulary cv; cv.loadFromOBO("PSI-MS", File::find("/CV/psi-ms.obo")); String ref = R"(<cvParam accession="MS:1001331" cvRef="PSI-MS" name="X\!Tandem:hyperscore" value="12.5"/>)"; TEST_STRING_EQUAL(cv.getTerm("MS:1001331").toXMLString("PSI-MS", String("12.5")),ref) } END_SECTION START_SECTION(([ControlledVocabulary::CVTerm] String ControlledVocabulary::CVTerm::toXMLString(const OpenMS::String& ref, const OpenMS::DataValue& value) const)) { ControlledVocabulary cv; cv.loadFromOBO("PSI-MS", File::find("/CV/psi-ms.obo")); String ref = R"(<cvParam accession="MS:1001331" cvRef="PSI-MS" name="X\!Tandem:hyperscore" value="12.5"/>)"; OpenMS::DataValue val = 12.5; TEST_STRING_EQUAL(cv.getTerm("MS:1001331").toXMLString("PSI-MS",val),ref) } END_SECTION START_SECTION(([ControlledVocabulary::CVTerm] CVTerm(const CVTerm &rhs))) { ControlledVocabulary::CVTerm a; a.name = "test_cvterm"; a.id = "test_id"; a.parents.insert("test_parent"); a.children.insert("test_children"); a.obsolete = true; a.description = "test_description"; a.synonyms = ListUtils::create<String>("test,synonyms"); a.unparsed = ListUtils::create<String>("test,unparsed"); a.xref_type = ControlledVocabulary::CVTerm::XRefType::XSD_DECIMAL; a.xref_binary = ListUtils::create<String>("test,xref_binary"); a.units.insert("units"); ControlledVocabulary::CVTerm b(a); TEST_STRING_EQUAL(b.name,a.name) TEST_STRING_EQUAL(b.id,a.id) TEST_EQUAL(b.parents == a.parents, true) TEST_EQUAL(b.children == a.children, true) TEST_EQUAL(b.obsolete, a.obsolete) TEST_STRING_EQUAL(b.description,a.description) TEST_EQUAL(b.synonyms, a.synonyms) TEST_EQUAL(b.unparsed, a.unparsed) TEST_EQUAL(b.xref_type == a.xref_type, true) TEST_EQUAL(b.xref_binary, a.xref_binary) TEST_EQUAL(b.units == a.units, true) } END_SECTION START_SECTION(([ControlledVocabulary::CVTerm] CVTerm& operator=(const CVTerm &rhs))) { ControlledVocabulary::CVTerm a,b; a.name = "test_cvterm"; a.id = "test_id"; a.parents.insert("test_parent"); a.children.insert("test_children"); a.obsolete = true; a.description = "test_description"; a.synonyms = ListUtils::create<String>("test,synonyms"); a.unparsed = ListUtils::create<String>("test,unparsed"); a.xref_type = ControlledVocabulary::CVTerm::XRefType::XSD_DECIMAL; a.xref_binary = ListUtils::create<String>("test,xref_binary"); a.units.insert("units"); b = a; TEST_STRING_EQUAL(b.name,a.name) TEST_STRING_EQUAL(b.id,a.id) TEST_EQUAL(b.parents == a.parents, true) TEST_EQUAL(b.children == a.children, true) TEST_EQUAL(b.obsolete, a.obsolete) TEST_STRING_EQUAL(b.description,a.description) TEST_EQUAL(b.synonyms, a.synonyms) TEST_EQUAL(b.unparsed, a.unparsed) TEST_EQUAL(b.xref_type == a.xref_type, true) TEST_EQUAL(b.xref_binary, a.xref_binary) TEST_EQUAL(b.units == a.units, true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ItraqEightPlexQuantitationMethod_test.cpp
.cpp
5,995
193
// 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/ItraqEightPlexQuantitationMethod.h> #include <OpenMS/ANALYSIS/QUANTITATION/ItraqConstants.h> /////////////////////////// // #include <OpenMS/DATASTRUCTURES/Matrix.h> using namespace OpenMS; using namespace std; START_TEST(ItraqEightPlexQuantitationMethod, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ItraqEightPlexQuantitationMethod* ptr = nullptr; ItraqEightPlexQuantitationMethod* null_ptr = nullptr; START_SECTION(ItraqEightPlexQuantitationMethod()) { ptr = new ItraqEightPlexQuantitationMethod(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~ItraqEightPlexQuantitationMethod()) { delete ptr; } END_SECTION START_SECTION((const String& getMethodName() const )) { ItraqEightPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getMethodName(), "itraq8plex") } END_SECTION START_SECTION((const IsobaricChannelList& getChannelInformation() const )) { ItraqEightPlexQuantitationMethod quant_meth; IsobaricQuantitationMethod::IsobaricChannelList channel_list = quant_meth.getChannelInformation(); TEST_EQUAL(channel_list.size(), 8) ABORT_IF(channel_list.size() != 8) // 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, "") // check masses&co TEST_EQUAL(channel_list[0].name, 113) TEST_EQUAL(channel_list[0].id, 0) TEST_EQUAL(channel_list[0].center, 113.1078) TEST_EQUAL(channel_list[1].name, 114) TEST_EQUAL(channel_list[1].id, 1) TEST_EQUAL(channel_list[1].center, 114.1112) TEST_EQUAL(channel_list[2].name, 115) TEST_EQUAL(channel_list[2].id, 2) TEST_EQUAL(channel_list[2].center, 115.1082) TEST_EQUAL(channel_list[3].name, 116) TEST_EQUAL(channel_list[3].id, 3) TEST_EQUAL(channel_list[3].center, 116.1116) TEST_EQUAL(channel_list[4].name, 117) TEST_EQUAL(channel_list[4].id, 4) TEST_EQUAL(channel_list[4].center, 117.1149) TEST_EQUAL(channel_list[5].name, 118) TEST_EQUAL(channel_list[5].id, 5) TEST_EQUAL(channel_list[5].center, 118.1120) TEST_EQUAL(channel_list[6].name, 119) TEST_EQUAL(channel_list[6].id, 6) TEST_EQUAL(channel_list[6].center, 119.1153) TEST_EQUAL(channel_list[7].name, 121) TEST_EQUAL(channel_list[7].id, 7) TEST_EQUAL(channel_list[7].center, 121.1220) } END_SECTION START_SECTION((Size getNumberOfChannels() const )) { ItraqEightPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getNumberOfChannels(), 8) } END_SECTION START_SECTION((virtual Matrix<double> getIsotopeCorrectionMatrix() const )) { ItraqEightPlexQuantitationMethod quant_meth; // we only check the default matrix here Matrix<double> m = quant_meth.getIsotopeCorrectionMatrix(); TEST_EQUAL(m.rows(), 8) TEST_EQUAL(m.cols(), 8) ABORT_IF(m.rows() != 8) ABORT_IF(m.cols() != 8) double real_m[8][8] = { { 0.9289, 0.0094, 0, 0, 0, 0, 0, 0 }, { 0.0689, 0.93, 0.0188, 0, 0, 0, 0, 0 }, { 0.0022, 0.059, 0.9312, 0.0282, 0.0006, 0, 0, 0 }, { 0, 0.0016, 0.049, 0.9321, 0.0377, 0.0009, 0, 0 }, { 0, 0, 0.001, 0.039, 0.9318, 0.0471, 0.0014, 0 }, { 0, 0, 0, 0.0007, 0.0299, 0.9332, 0.0566, 0 }, { 0, 0, 0, 0, 0, 0.0188, 0.9333, 0.0027 }, { 0, 0, 0, 0, 0, 0, 0, 0.9211 } }; for(Size i = 0; i < m.rows(); ++i) { for(Size j = 0; j < m.cols(); ++j) { TEST_REAL_SIMILAR(m(i,j), real_m[i][j]) } } } END_SECTION START_SECTION((Size getReferenceChannel() const )) { ItraqEightPlexQuantitationMethod quant_meth; TEST_EQUAL(quant_meth.getReferenceChannel(), 0) Param p; p.setValue("reference_channel",115); quant_meth.setParameters(p); TEST_EQUAL(quant_meth.getReferenceChannel(), 2) p.setValue("reference_channel",121); quant_meth.setParameters(p); TEST_EQUAL(quant_meth.getReferenceChannel(), 7) } END_SECTION START_SECTION((ItraqEightPlexQuantitationMethod(const ItraqEightPlexQuantitationMethod &other))) { ItraqEightPlexQuantitationMethod qm; Param p = qm.getParameters(); p.setValue("channel_114_description", "new_description"); p.setValue("reference_channel", 116); qm.setParameters(p); ItraqEightPlexQuantitationMethod 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((ItraqEightPlexQuantitationMethod& operator=(const ItraqEightPlexQuantitationMethod &rhs))) { ItraqEightPlexQuantitationMethod qm; Param p = qm.getParameters(); p.setValue("channel_114_description", "new_description"); p.setValue("reference_channel", 116); qm.setParameters(p); ItraqEightPlexQuantitationMethod 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/FeatureGroupingAlgorithmKD_test.cpp
.cpp
1,462
47
// 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(FeatureGroupingAlgorithmKD, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FeatureGroupingAlgorithmKD* ptr = nullptr; FeatureGroupingAlgorithmKD* nullPointer = nullptr; START_SECTION((FeatureGroupingAlgorithmKD())) ptr = new FeatureGroupingAlgorithmKD(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~FeatureGroupingAlgorithmKD())) delete ptr; END_SECTION START_SECTION((virtual void group(const std::vector<FeatureMap>& maps, ConsensusMap& out))) // This is tested in the tool NOT_TESTABLE; END_SECTION START_SECTION((virtual void group(const std::vector<ConsensusMap>& maps, ConsensusMap& out))) // This is tested in the tool NOT_TESTABLE; END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TheoreticalSpectrumGenerator_test.cpp
.cpp
33,276
904
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg, Eugen Netz $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <iostream> #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/CONCEPT/Constants.h> /////////////////////////// START_TEST(TheoreticalSpectrumGenerator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; TheoreticalSpectrumGenerator* ptr = nullptr; TheoreticalSpectrumGenerator* nullPointer = nullptr; START_SECTION(TheoreticalSpectrumGenerator()) ptr = new TheoreticalSpectrumGenerator(); TEST_NOT_EQUAL(ptr, nullPointer) delete ptr; END_SECTION START_SECTION(TheoreticalSpectrumGenerator(const TheoreticalSpectrumGenerator& source)) ptr = new TheoreticalSpectrumGenerator(); TheoreticalSpectrumGenerator copy(*ptr); TEST_EQUAL(copy.getParameters(), ptr->getParameters()) END_SECTION START_SECTION(~TheoreticalSpectrumGenerator()) delete ptr; END_SECTION ptr = new TheoreticalSpectrumGenerator(); AASequence peptide = AASequence::fromString("IFSQVGK"); START_SECTION(TheoreticalSpectrumGenerator& operator = (const TheoreticalSpectrumGenerator& tsg)) TheoreticalSpectrumGenerator copy; copy = *ptr; TEST_EQUAL(copy.getParameters(), ptr->getParameters()) END_SECTION START_SECTION(void getSpectrum(PeakSpectrum& spec, const AASequence& peptide, Int min_charge = 1, Int max_charge = 1)) PeakSpectrum spec; ptr->getSpectrum(spec, peptide, 1, 1); TEST_EQUAL(spec.size(), 11) TOLERANCE_ABSOLUTE(0.001) /** From http://db.systemsbiology.net:8080/proteomicsToolkit/FragIonServlet.html Fragment Ion Table, monoisotopic masses Seq # A B C X Y Z # (+1) I 1 86.09647 114.09139 131.11793 - 778.44581 761.42036 7 F 2 233.16488 261.15980 278.18635 691.34101 665.36174 648.33629 6 S 3 320.19691 348.19183 365.21838 544.27260 518.29333 501.26788 5 Q 4 448.25549 476.25040 493.27695 457.24057 431.26130 414.23585 4 V 5 547.32390 575.31882 592.34537 329.18199 303.20273 286.17727 3 G 6 604.34537 632.34028 649.36683 230.11358 204.13431 187.10886 2 K 7 732.44033 760.43524 - 173.09211 147.11285 130.08740 1 **/ double result[] = {/*114.091,*/ 147.113, 204.135, 261.16, 303.203, 348.192, 431.262, 476.251, 518.294, 575.319, 632.341, 665.362}; std::vector<double> result_x = { 691.34101, 544.27260, 457.24057, 329.18199, 230.11358, 173.09211 }; std::vector<double> result_x_losses = { 691.34101 - 17.026549095700005, 691.34101 - 18.01056506379996, 691.34101, 544.27260 - 17.026549095700005, 544.27260 - 18.01056506379996, 544.27260, 457.24057 - 17.026549095700005, 457.24057, 329.18199 - 17.026549095700005, 329.18199, 230.11358 - 17.026549095700005, 230.11358, 173.09211 - 17.026549095700005, 173.09211 }; std::sort(result_x.begin(), result_x.end()); std::sort(result_x_losses.begin(), result_x_losses.end()); for (Size i = 0; i != spec.size(); ++i) { TEST_REAL_SIMILAR(spec[i].getPosition()[0], result[i]) } TEST_EQUAL(spec.getMSLevel(), 2); TEST_EQUAL(spec.getType(), MSSpectrum::SpectrumSettings::SpectrumType::CENTROID); TEST_REAL_SIMILAR(peptide.getMZ(2, Residue::Full), spec.getPrecursors()[0].getMZ()); spec.clear(true); ptr->getSpectrum(spec, peptide, 1, 2); TEST_EQUAL(spec.size(), 22) TEST_REAL_SIMILAR(peptide.getMZ(3, Residue::Full), spec.getPrecursors()[0].getMZ()); spec.clear(true); Param param(ptr->getParameters()); param.setValue("add_first_prefix_ion", "true"); ptr->setParameters(param); ptr->getSpectrum(spec, peptide, 1, 1); TEST_EQUAL(spec.size(), 12) double result2[] = {114.091, 147.113, 204.135, 261.16, 303.203, 348.192, 431.262, 476.251, 518.294, 575.319, 632.341, 665.362}; for (Size i = 0; i != spec.size(); ++i) { TEST_REAL_SIMILAR(spec[i].getPosition()[0], result2[i]) } AASequence new_peptide = AASequence::fromString("DFPLANGER"); /** From http://db.systemsbiology.net:8080/proteomicsToolkit/FragIonServlet.html Seq # A B C X Y Z # (+1) D 1 88.03990 116.03481 133.06136 - 1018.49583 1001.46928 9 F 2 235.10831 263.10323 280.12978 929.44815 903.46888 886.44233 8 P 3 332.16108 360.15599 377.18254 782.37973 756.40047 739.37392 7 I 4 445.24514 473.24005 490.26660 685.32697 659.34771 642.32116 6 A 5 516.28225 544.27717 561.30372 572.24291 546.26364 529.23709 5 N 6 630.32518 658.32009 675.34664 501.20579 475.22653 458.19998 4 G 7 687.34664 715.34156 732.36811 387.16287 361.18360 344.15705 3 E 8 816.38924 844.38415 861.41070 330.14140 304.16214 287.13559 2 R 9 972.49035 1000.48526 - 201.09881 175.11955 158.09300 1 **/ double result_all[52-1] = { 88.03990, 235.10831, 332.16108, 445.24514, 516.28225, 630.32518, 687.34664, 816.38924, /*972.49035, because TSG does not do A-ions of the full peptide*/ 116.03481, 263.10323, 360.15599, 473.24005, 544.27717, 658.32009, 715.34156, 844.38415, 1000.48526, 133.06136, 280.12978, 377.18254, 490.26660, 561.30372, 675.34664, 732.36811, 861.41070, 929.44815, 782.37973, 685.32697, 572.24291, 501.20579, 387.16287, 330.14140, 201.09881, 1018.49583, 903.46888, 756.40047, 659.34771, 546.26364, 475.22653, 361.18360, 304.16214, 175.11955, 1001.46928, 886.44233, 739.37392, 642.32116, 529.23709, 458.19998, 344.15705, 287.13559, 158.09300 }; std::sort(result_all,result_all+52-1); spec.clear(true); std::vector<double> result_bx = { 116.03481, 263.10323, 360.15599, 473.24005, 544.27717, 658.32009, 715.34156, 844.38415, 1000.48526, 929.44815, 782.37973, 685.32697, 572.24291, 501.20579, 387.16287, 330.14140, 201.09881, }; std::sort(result_bx.begin(),result_bx.end()); param.setValue("add_first_prefix_ion", "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_precursor_peaks", "true"); ptr->setParameters(param); ptr->getSpectrum(spec, new_peptide, 1, 1); TEST_EQUAL(spec.size(), 52-1) TEST_REAL_SIMILAR(new_peptide.getMZ(2, Residue::Full), spec.getPrecursors()[0].getMZ()); vector<double> generated; for (Size i = 0; i != spec.size(); ++i) { generated.push_back(spec[i].getPosition()[0]); } std::sort(generated.begin(),generated.end()); for (Size i = 0; i != generated.size(); ++i) { TEST_REAL_SIMILAR(generated[i], result_all[i]) } // test loss creation and annotation spec.clear(true); param = ptr->getParameters(); param.setValue("add_first_prefix_ion", "true"); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "false"); 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_precursor_peaks", "false"); param.setValue("add_metainfo", "false"); param.setValue("add_losses", "true"); ptr->setParameters(param); ptr->getSpectrum(spec, peptide, 1, 1); TEST_EQUAL(spec.size(), 14) generated.clear(); for (Size i = 0; i != spec.size(); ++i) { generated.push_back(spec[i].getPosition()[0]); } for (Size i = 0; i != generated.size(); ++i) { TEST_REAL_SIMILAR(generated[i], result_x_losses[i]) } // test loss creation and annotation spec.clear(true); param = ptr->getParameters(); param.setValue("add_first_prefix_ion", "true"); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "false"); 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_precursor_peaks", "false"); param.setValue("add_metainfo", "true"); param.setValue("add_losses", "true"); ptr->setParameters(param); ptr->getSpectrum(spec, peptide, 1, 1); TEST_EQUAL(spec.size(), 14) generated.clear(); for (Size i = 0; i != spec.size(); ++i) { generated.push_back(spec[i].getPosition()[0]); } for (Size i = 0; i != generated.size(); ++i) { TEST_REAL_SIMILAR(generated[i], result_x_losses[i]) } std::sort(generated.begin(),generated.end()); // test loss creation and annotation spec.clear(true); param = ptr->getParameters(); param.setValue("add_first_prefix_ion", "true"); 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_precursor_peaks", "true"); param.setValue("add_metainfo", "true"); param.setValue("add_losses", "true"); ptr->setParameters(param); ptr->getSpectrum(spec, peptide, 1, 1); TEST_EQUAL(spec.size(), 30) set<String> ion_names; // ions without losses ion_names.insert("b1+"); ion_names.insert("x1+"); ion_names.insert("b2+"); ion_names.insert("x2+"); ion_names.insert("b3+"); ion_names.insert("x3+"); ion_names.insert("b4+"); ion_names.insert("x4+"); ion_names.insert("b5+"); ion_names.insert("x5+"); ion_names.insert("b6+"); ion_names.insert("x6+"); // currently losses are generated independent of ion ladder type (b,y,...) // if an amino acid with potential loss is present in the prefix/suffix, then the loss is applied // if multiple amino acids with the same e.g. water loss are present in the prefix/suffix ion then the loss is only applied once ion_names.insert("x1-H3N1+"); ion_names.insert("x2-H3N1+"); ion_names.insert("x3-H3N1+"); ion_names.insert("b3-H2O1+"); ion_names.insert("x4-H3N1+"); ion_names.insert("b4-H2O1+"); ion_names.insert("b4-H3N1+"); ion_names.insert("x5-H2O1+"); ion_names.insert("x5-H3N1+"); ion_names.insert("b5-H2O1+"); ion_names.insert("b5-H3N1+"); ion_names.insert("b6-H2O1+"); ion_names.insert("b6-H3N1+"); ion_names.insert("x6-H2O1+"); ion_names.insert("x6-H3N1+"); // precursors ion_names.insert("[M+H-H2O]+"); ion_names.insert("[M+H-NH3]+"); ion_names.insert("[M+H]+"); PeakSpectrum::StringDataArray string_array = spec.getStringDataArrays().at(0); // check if all losses have been annotated for (Size i = 0; i != spec.size(); ++i) { String name = string_array[i]; if (ion_names.find(name) == ion_names.end()) { std::cout << "Ion name generated by TSG: " << name << " not found in list of exected ion names." << std::endl; std::cout << "Expected ion names:" << std::endl; for (const auto& ion : ion_names) { std::cout << ion << std::endl; } } TEST_EQUAL(ion_names.find(name) != ion_names.end(), true); } // test for charges stored in IntegerDataArray PeakSpectrum charge3_spec; ptr->getSpectrum(charge3_spec, peptide, 1, 3); PeakSpectrum::IntegerDataArray charge_array = charge3_spec.getIntegerDataArrays().at(0); int charge_counts[3] = {0, 0, 0}; for (Size i = 0; i != charge3_spec.size(); ++i) { charge_counts[charge_array[i]-1]++; } TEST_EQUAL(charge_counts[0], 27) TEST_EQUAL(charge_counts[1], 27) TEST_EQUAL(charge_counts[2], 30) // 3 more for [M+H], [M+H]-H20, [M+H]-NH3 // test getSpectrum with one specific charge != 1 spec.clear(true); ptr->getSpectrum(spec, peptide, 3, 3); TEST_EQUAL(spec.size(), 30) TEST_REAL_SIMILAR(peptide.getMZ(4, Residue::Full), spec.getPrecursors()[0].getMZ()); ion_names.clear(); // ions without losses ion_names.insert("b1+++"); ion_names.insert("x1+++"); ion_names.insert("b2+++"); ion_names.insert("x2+++"); ion_names.insert("b3+++"); ion_names.insert("x3+++"); ion_names.insert("b4+++"); ion_names.insert("x4+++"); ion_names.insert("b5+++"); ion_names.insert("x5+++"); ion_names.insert("b6+++"); ion_names.insert("x6+++"); // currently losses are generated independent of ion ladder type (b,y,...) // if an amino acid with potential loss is present in the prefix/suffix, then the loss is applied // if multiple amino acids with the same e.g. water loss are present in the prefix/suffix ion then the loss is only applied once ion_names.insert("x1-H3N1+++"); ion_names.insert("x2-H3N1+++"); ion_names.insert("x3-H3N1+++"); ion_names.insert("b3-H2O1+++"); ion_names.insert("x4-H3N1+++"); ion_names.insert("b4-H2O1+++"); ion_names.insert("b4-H3N1+++"); ion_names.insert("x5-H2O1+++"); ion_names.insert("x5-H3N1+++"); ion_names.insert("b5-H2O1+++"); ion_names.insert("b5-H3N1+++"); ion_names.insert("b6-H2O1+++"); ion_names.insert("b6-H3N1+++"); ion_names.insert("x6-H2O1+++"); ion_names.insert("x6-H3N1+++"); // precursors ion_names.insert("[M+3H-H2O]+++"); ion_names.insert("[M+3H-NH3]+++"); ion_names.insert("[M+3H]+++"); string_array = spec.getStringDataArrays().at(0); // check if all losses have been annotated for (Size i = 0; i != spec.size(); ++i) { String name = string_array[i]; if (ion_names.find(name) == ion_names.end()) { std::cout << "Test Error: " << name << " not found." << std::endl; } TEST_EQUAL(ion_names.find(name) != ion_names.end(), true) } charge_array = spec.getIntegerDataArrays().at(0); charge_counts[0] = 0; charge_counts[1] = 0; charge_counts[2] = 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], 0) TEST_EQUAL(charge_counts[2], 30) // AbundantImmoniumIons test param = ptr->getParameters(); param.setValue("add_b_ions", "false"); param.setValue("add_x_ions", "false"); param.setValue("add_precursor_peaks", "false"); param.setValue("add_metainfo", "false"); param.setValue("add_losses", "false"); param.setValue("add_abundant_immonium_ions", "true"); ptr->setParameters(param); spec.clear(true); ptr->getSpectrum(spec, AASequence::fromString("HFYLWCP"), 1, 1); TEST_EQUAL(spec.size(), 7) TEST_REAL_SIMILAR(spec[0].getPosition()[0], 70.0656) TEST_REAL_SIMILAR(spec[1].getPosition()[0], 76.0221) TEST_REAL_SIMILAR(spec[2].getPosition()[0], 86.09698) TEST_REAL_SIMILAR(spec[3].getPosition()[0], 110.0718) TEST_REAL_SIMILAR(spec[4].getPosition()[0], 120.0813) TEST_REAL_SIMILAR(spec[5].getPosition()[0], 136.0762) TEST_REAL_SIMILAR(spec[6].getPosition()[0], 159.0922) spec.clear(true); ptr->getSpectrum(spec, AASequence::fromString("H"), 1, 1); TEST_EQUAL(spec.size(), 1) spec.clear(true); ptr->getSpectrum(spec, AASequence::fromString("A"), 1, 1); TEST_EQUAL(spec.size(), 0) spec.clear(true); ptr->getSpectrum(spec, peptide, 1, 1, 4); ptr->getSpectrum(spec, new_peptide, 1, 3); ABORT_IF(spec.getPrecursors().size() != 2); TEST_REAL_SIMILAR(spec.getPrecursors()[0].getMZ(), peptide.getMZ(4)); TEST_EQUAL(spec.getPrecursors()[0].getCharge(), 4); TEST_REAL_SIMILAR(spec.getPrecursors()[1].getMZ(), new_peptide.getMZ(4)); TEST_EQUAL(spec.getPrecursors()[1].getCharge(), 4); spec.clear(true); TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidParameter, ptr->getSpectrum(spec, peptide, 1, 2, 1), "'precursor_charge' has to be higher than or equal to 'max_charge'."); // // for quick benchmarking of implementation chances // param = ptr->getParameters(); // param.setValue("add_first_prefix_ion", "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_precursor_peaks", "true"); // param.setValue("add_metainfo", "true"); // param.setValue("add_losses", "true"); // ptr->setParameters(param); // peptide = AASequence::fromString("PEPTIDEPEPTIDEPEPTIDE"); // for (Size i = 0; i != 1e4; ++i) // { // PeakSpectrum spec; // ptr->getSpectrum(spec, peptide, 1, 3); // } END_SECTION START_SECTION(static MSSpectrum generateSpectrum(const Precursor::ActivationMethod& fm, const AASequence& seq, int precursor_charge)) MSSpectrum spec; Precursor prec; // Test CID/HCID spec = TheoreticalSpectrumGenerator::generateSpectrum(Precursor::ActivationMethod::CID, AASequence::fromString("HFYLWCP"), 1); ABORT_IF(spec.size() != 11); TEST_REAL_SIMILAR(spec[0].getPosition()[0], 116.0706); TEST_REAL_SIMILAR(spec[1].getPosition()[0], 219.0797); TEST_REAL_SIMILAR(spec[2].getPosition()[0], 285.1346); TEST_REAL_SIMILAR(spec[3].getPosition()[0], 405.1591); TEST_REAL_SIMILAR(spec[4].getPosition()[0], 448.1979); TEST_REAL_SIMILAR(spec[5].getPosition()[0], 518.2431); TEST_REAL_SIMILAR(spec[6].getPosition()[0], 561.2819); TEST_REAL_SIMILAR(spec[7].getPosition()[0], 681.3064); TEST_REAL_SIMILAR(spec[8].getPosition()[0], 747.3613); TEST_REAL_SIMILAR(spec[9].getPosition()[0], 828.3749); TEST_REAL_SIMILAR(spec[10].getPosition()[0], 850.3704); spec.clear(true); // Test ECD/ETD spec = TheoreticalSpectrumGenerator::generateSpectrum(Precursor::ActivationMethod::ECD, AASequence::fromString("HFYLWCP"), 1); TEST_EQUAL(spec.size(), 17); TEST_REAL_SIMILAR(spec[0].getPosition()[0], 100.0518816); TEST_REAL_SIMILAR(spec[1].getPosition()[0], 101.0597067); TEST_REAL_SIMILAR(spec[2].getPosition()[0], 203.0610665); TEST_REAL_SIMILAR(spec[3].getPosition()[0], 204.0688916); TEST_REAL_SIMILAR(spec[4].getPosition()[0], 302.1611520); TEST_REAL_SIMILAR(spec[5].getPosition()[0], 389.1403798); TEST_REAL_SIMILAR(spec[6].getPosition()[0], 390.1482049); TEST_REAL_SIMILAR(spec[7].getPosition()[0], 465.2244813); TEST_REAL_SIMILAR(spec[8].getPosition()[0], 502.2244442); TEST_REAL_SIMILAR(spec[9].getPosition()[0], 503.2322692); TEST_REAL_SIMILAR(spec[10].getPosition()[0], 578.3085457); // ... spec.clear(true); // Test precursor_charge > 2 spec = TheoreticalSpectrumGenerator::generateSpectrum(Precursor::ActivationMethod::HCID, AASequence::fromString("PEP"), 3); TEST_EQUAL(spec.size(), 8); TEST_REAL_SIMILAR(spec[0].getPosition()[0], 58.5389); TEST_REAL_SIMILAR(spec[1].getPosition()[0], 100.0574); TEST_REAL_SIMILAR(spec[2].getPosition()[0], 114.0549); TEST_REAL_SIMILAR(spec[3].getPosition()[0], 116.0706); TEST_REAL_SIMILAR(spec[4].getPosition()[0], 123.0602); TEST_REAL_SIMILAR(spec[5].getPosition()[0], 199.1077); TEST_REAL_SIMILAR(spec[6].getPosition()[0], 227.1026); TEST_REAL_SIMILAR(spec[7].getPosition()[0], 245.1131); // Test not supported activation method TEST_EXCEPTION(Exception::InvalidParameter, TheoreticalSpectrumGenerator::generateSpectrum(Precursor::ActivationMethod::SORI, AASequence::fromString("PEP"), 1)); END_SECTION START_SECTION(([EXTRA] bugfix test where losses lead to formulae with negative element frequencies)) { // this tests for the loss of CONH2 on Arginine, however it is not clear how // this loss would occur in the first place. AASequence tmp_aa = AASequence::fromString("RDAGGPALKK"); PeakSpectrum tmp; TheoreticalSpectrumGenerator t_gen; Param params; params.setValue("isotope_model", "coarse"); params.setValue("add_losses", "true"); params.setValue("add_first_prefix_ion", "true"); params.setValue("add_a_ions", "true"); t_gen.setParameters(params); t_gen.getSpectrum(tmp, tmp_aa, 1, 1); TEST_EQUAL(tmp.size(), 212) tmp.clear(true); params.setValue("isotope_model", "coarse"); params.setValue("add_losses", "true"); params.setValue("add_first_prefix_ion", "false"); params.setValue("add_a_ions", "true"); t_gen.setParameters(params); t_gen.getSpectrum(tmp, tmp_aa, 1, 1); TEST_EQUAL(tmp_aa[0].hasNeutralLoss(), true) TEST_EQUAL(tmp.size(), 198) tmp_aa = AASequence::fromString("RDK"); tmp.clear(true); params.setValue("isotope_model", "none"); params.setValue("add_losses", "true"); params.setValue("add_first_prefix_ion", "true"); params.setValue("add_a_ions", "true"); params.setValue("add_b_ions", "false"); params.setValue("add_y_ions", "false"); params.setValue("add_metainfo", "true"); t_gen.setParameters(params); TEST_EQUAL(tmp.size(), 0) t_gen.getSpectrum(tmp, tmp_aa, 1, 1); // TEST_EQUAL(tmp.size(), 8) tmp.clear(true); params.setValue("add_losses", "true"); params.setValue("add_first_prefix_ion", "true"); params.setValue("add_a_ions", "true"); params.setValue("add_b_ions", "false"); params.setValue("add_y_ions", "false"); params.setValue("add_metainfo", "false"); t_gen.setParameters(params); t_gen.getSpectrum(tmp, tmp_aa, 1, 1); // TEST_EQUAL(tmp.size(), 8) } END_SECTION START_SECTION(([EXTRA] test monomer extreme case)) { AASequence tmp_aa = AASequence::fromString("R"); PeakSpectrum tmp; TheoreticalSpectrumGenerator t_gen; Param params; params.setValue("add_first_prefix_ion", "true"); params.setValue("add_x_ions", "true"); t_gen.setParameters(params); TEST_EXCEPTION(Exception::InvalidSize, t_gen.getSpectrum(tmp, tmp_aa, 1, 1)); params.setValue("add_first_prefix_ion", "true"); params.setValue("add_x_ions", "false"); params.setValue("add_c_ions", "true"); t_gen.setParameters(params); TEST_EXCEPTION(Exception::InvalidSize, t_gen.getSpectrum(tmp, tmp_aa, 1, 1)); params.setValue("add_x_ions", "false"); params.setValue("add_c_ions", "false"); params.setValue("add_precursor_peaks", "true"); t_gen.setParameters(params); t_gen.getSpectrum(tmp, tmp_aa, 1, 1); TEST_EQUAL(tmp.size(), 3) } END_SECTION START_SECTION(([EXTRA] test isotope clusters for all peak types)) { AASequence tmp_aa = AASequence::fromString("ARRGH"); PeakSpectrum spec; TheoreticalSpectrumGenerator t_gen; Param params; params.setValue("isotope_model", "coarse"); params.setValue("max_isotope", 2); params.setValue("add_b_ions", "false"); t_gen.setParameters(params); // isotope cluster for y-ions t_gen.getSpectrum(spec, tmp_aa, 2, 2); TEST_EQUAL(spec.size(), 8) TOLERANCE_ABSOLUTE(0.001) double neutron_shift = Constants::C13C12_MASSDIFF_U; // 4 monoisotopic masses, 4 second peaks with added neutron mass / 2 std::vector<double> result = { 78.54206, 107.05279, 185.10335, 263.15390, 78.54206+(neutron_shift/2), 107.05279+(neutron_shift/2), 185.10335+(neutron_shift/2), 263.15390+(neutron_shift/2) }; std::sort(result.begin(), result.end()); for (Size i = 0; i != spec.size(); ++i) { TEST_REAL_SIMILAR(spec[i].getPosition()[0], result[i]) } spec.clear(true); params.setValue("isotope_model", "fine"); params.setValue("max_isotope", 2); params.setValue("add_b_ions", "false"); t_gen.setParameters(params); // isotope cluster for y-ions t_gen.getSpectrum(spec, tmp_aa, 2, 2); TEST_EQUAL(spec.size(), 10) result = { 78.54206, 107.05279, 185.10335, 263.15390, // 405: POS: 78.54256367545 INT: 0.921514272689819 79.04424117545, // 405: POS: 107.0532957233 INT: 0.89608770608902 107.5549732233, // 405: POS: 185.1038514147 INT: 0.824628114700317 185.6023689147, 185.6055289147, // 405: POS: 263.1544071061 INT: 0.758867204189301 263.6529246061, 263.6560846061, }; std::sort(result.begin(), result.end()); for (Size i = 0; i != spec.size(); ++i) { TEST_REAL_SIMILAR(spec[i].getPosition()[0], result[i]) } spec.clear(true); params.setValue("isotope_model", "fine"); params.setValue("max_isotope", 2); params.setValue("max_isotope_probability", 0.20); params.setValue("add_b_ions", "false"); t_gen.setParameters(params); // isotope cluster for y-ions t_gen.getSpectrum(spec, tmp_aa, 2, 2); TEST_EQUAL(spec.size(), 5) result = { 78.54206, 107.05279, 185.10335, 263.15390, // 405: POS: 78.54256367545 INT: 0.921514272689819 // 405: POS: 107.0532957233 INT: 0.89608770608902 // 405: POS: 185.1038514147 INT: 0.824628114700317 // 405: POS: 263.1544071061 INT: 0.758867204189301 263.6560846061, }; std::sort(result.begin(), result.end()); for (Size i = 0; i != spec.size(); ++i) { TEST_REAL_SIMILAR(spec[i].getPosition()[0], result[i]) } spec.clear(true); params.setValue("isotope_model", "fine"); params.setValue("max_isotope", 2); params.setValue("max_isotope_probability", 0.01); params.setValue("add_b_ions", "false"); t_gen.setParameters(params); // isotope cluster for y-ions t_gen.getSpectrum(spec, tmp_aa, 2, 2); // TEST_EQUAL(spec.size(), 34) // isotope cluster for losses spec.clear(true); params.setValue("isotope_model", "coarse"); params.setValue("add_losses", "true"); params.setValue("add_b_ions", "false"); t_gen.setParameters(params); t_gen.getSpectrum(spec, tmp_aa, 1, 2); TEST_EQUAL(spec.size(), 40) double proton_shift = Constants::PROTON_MASS_U; // 10 monoisotopic peaks with charge=1, 10 second peaks, 20 with charge=2 std::vector<double> result_losses = { 156.07675, 213.09821, 325.18569, 327.17753, 352.17278, 369.19932, 481.28680, 483.27864, 508.27389, 525.30044, 156.07675+neutron_shift, 213.09821+neutron_shift, 325.18569+neutron_shift, 327.17753+neutron_shift, 352.17278+neutron_shift, 369.19932+neutron_shift, 481.28680+neutron_shift, 483.27864+neutron_shift, 508.27389+neutron_shift, 525.30044+neutron_shift, (156.07675+proton_shift)/2, (213.09821+proton_shift)/2, (325.18569+proton_shift)/2, (327.17753+proton_shift)/2, (352.17278+proton_shift)/2, (369.19932+proton_shift)/2, (481.28680+proton_shift)/2, (483.27864+proton_shift)/2, (508.27389+proton_shift)/2, (525.30044+proton_shift)/2, (156.07675+proton_shift)/2+(neutron_shift/2), (213.09821+proton_shift)/2+(neutron_shift/2), (325.18569+proton_shift)/2+(neutron_shift/2), (327.17753+proton_shift)/2+(neutron_shift/2), (352.17278+proton_shift)/2+(neutron_shift/2), (369.19932+proton_shift)/2+(neutron_shift/2), (481.28680+proton_shift)/2+(neutron_shift/2), (483.27864+proton_shift)/2+(neutron_shift/2), (508.27389+proton_shift)/2+(neutron_shift/2), (525.30044+proton_shift)/2+(neutron_shift/2)}; std::sort(result_losses.begin(), result_losses.end()); for (Size i = 0; i != spec.size(); ++i) { TEST_REAL_SIMILAR(spec[i].getPosition()[0], result_losses[i]) } result_losses = { 0.927642, 0.0723581}; // check intensity for (Size i = 0; i != 2; ++i) { TEST_REAL_SIMILAR(spec[i].getIntensity(), result_losses[i]) } // last two entries: TEST_REAL_SIMILAR( spec[ spec.size() -2 ].getMZ(), 525.30044) TEST_REAL_SIMILAR( spec[ spec.size() -1 ].getMZ(), 526.304) spec.clear(true); params.setValue("isotope_model", "fine"); params.setValue("max_isotope_probability", 0.05); params.setValue("add_losses", "true"); params.setValue("add_b_ions", "false"); t_gen.setParameters(params); t_gen.getSpectrum(spec, tmp_aa, 1, 2); TEST_EQUAL(spec.size(), 50) result_losses = { 78.5426, 79.0442, 107.0532, 107.5549}; for (Size i = 0; i != 4; ++i) { TEST_REAL_SIMILAR(spec[i].getMZ(), result_losses[i]) } result_losses = { 0.921514, 0.0598011, 0.896088, 0.0775347}; // check intensity for (Size i = 0; i != 4; ++i) { TEST_REAL_SIMILAR(spec[i].getIntensity(), result_losses[i]) } // last entries TEST_REAL_SIMILAR( spec[ spec.size() -5 ].getMZ(), 509.271) TEST_REAL_SIMILAR( spec[ spec.size() -4 ].getMZ(), 509.277) TEST_REAL_SIMILAR( spec[ spec.size() -3 ].getMZ(), 525.301) TEST_REAL_SIMILAR( spec[ spec.size() -2 ].getMZ(), 526.298) TEST_REAL_SIMILAR( spec[ spec.size() -1 ].getMZ(), 526.304) // isotope cluster for precursor peaks with losses spec.clear(true); params.setValue("add_precursor_peaks", "true"); params.setValue("isotope_model", "coarse"); params.setValue("add_b_ions", "false"); params.setValue("add_y_ions", "false"); t_gen.setParameters(params); t_gen.getSpectrum(spec, tmp_aa, 2, 2); TEST_EQUAL(spec.size(), 6) // 3 monoisotopic peaks, 3 second peaks double result_precursors[] = { (578.32698+proton_shift)/2, (579.31100+proton_shift)/2, (596.33755+proton_shift)/2, (578.32698+proton_shift)/2+(neutron_shift/2), (579.31100+proton_shift)/2+(neutron_shift/2), (596.33755+proton_shift)/2+(neutron_shift/2)}; std::sort(result_precursors, result_precursors+6); for (Size i = 0; i != spec.size(); ++i) { TEST_REAL_SIMILAR(spec[i].getPosition()[0], result_precursors[i]) } spec.clear(true); params.setValue("add_precursor_peaks", "true"); params.setValue("isotope_model", "fine"); params.setValue("add_b_ions", "false"); params.setValue("add_y_ions", "false"); t_gen.setParameters(params); t_gen.getSpectrum(spec, tmp_aa, 2, 2); TEST_EQUAL(spec.size(), 12) TEST_REAL_SIMILAR(spec[0].getMZ(), (578.32698+proton_shift)/2 ) TEST_REAL_SIMILAR(spec[1].getMZ(), (579.31100+proton_shift)/2 ) TEST_REAL_SIMILAR(spec[11].getMZ(), (598.34481333943+proton_shift)/2 ) } END_SECTION START_SECTION(([EXTRA] test SpectrumAnnotator )) { // use same params as SpectrumAnnotator AASequence tmp_aa = AASequence::fromString("IALSRPNVEVVALNDPFITNDYAAYM(Oxidation)FK"); PeakSpectrum tmp; TheoreticalSpectrumGenerator t_gen; Param tgp; tgp.setValue("add_metainfo", "true"); tgp.setValue("add_losses", "true"); tgp.setValue("add_precursor_peaks", "true"); tgp.setValue("add_abundant_immonium_ions", "true"); tgp.setValue("add_first_prefix_ion", "true"); tgp.setValue("add_y_ions", "true"); tgp.setValue("add_b_ions", "true"); tgp.setValue("add_a_ions", "true"); tgp.setValue("add_x_ions", "true"); t_gen.setParameters(tgp); t_gen.getSpectrum(tmp, tmp_aa, 1, 1); TEST_EQUAL(tmp.size(), 465) tmp.clear(true); tgp.setValue("add_metainfo", "true"); tgp.setValue("add_losses", "true"); tgp.setValue("add_precursor_peaks", "false"); tgp.setValue("add_abundant_immonium_ions", "false"); tgp.setValue("add_first_prefix_ion", "false"); tgp.setValue("add_y_ions", "false"); tgp.setValue("add_b_ions", "false"); tgp.setValue("add_a_ions", "true"); tgp.setValue("add_x_ions", "false"); t_gen.setParameters(tgp); t_gen.getSpectrum(tmp, tmp_aa, 1, 1); TEST_EQUAL(tmp.size(), 121) // for (Size k = 0; k < tmp.size(); k++) // { // std::cout << tmp[k] << " -- " << tmp.getStringDataArrays()[0][k] << std::endl; // } } END_SECTION START_SECTION(([EXTRA] test first prefix loss)) { AASequence tmp_aa = AASequence::fromString("RDAGGPALKK"); PeakSpectrum tmp; TheoreticalSpectrumGenerator t_gen; Param params; params.setValue("isotope_model", "none"); params.setValue("add_losses", "true"); params.setValue("add_first_prefix_ion", "true"); params.setValue("add_a_ions", "true"); params.setValue("add_metainfo", "true"); t_gen.setParameters(params); t_gen.getSpectrum(tmp, tmp_aa, 1, 1); TEST_EQUAL(tmp.size(), 107) auto anno = tmp.getStringDataArrays()[0]; TEST_EQUAL(std::find(anno.begin(), anno.end(), "b1+") != anno.end(), true) TEST_EQUAL(std::find(anno.begin(), anno.end(), "b1-H3N1+") != anno.end(), true) TEST_EQUAL(std::find(anno.begin(), anno.end(), "b1-C1H2N2+") != anno.end(), true) TEST_EQUAL(std::find(anno.begin(), anno.end(), "b1-C1H2N1O1+") != anno.end(), true) // test without prefix ion (but still requires correct losses elsewhere) tmp.clear(true); params.setValue("add_first_prefix_ion", "false"); t_gen.setParameters(params); t_gen.getSpectrum(tmp, tmp_aa, 1, 1); TEST_EQUAL(tmp_aa[0].hasNeutralLoss(), true) TEST_EQUAL(tmp.size(), 99) // missing a1 and b1 ions as well as their losses -H3N1+ C1H2N2+ -C1H2N1O1+ anno = tmp.getStringDataArrays()[0]; TEST_EQUAL(std::find(anno.begin(), anno.end(), "b1+") == anno.end(), true) TEST_EQUAL(std::find(anno.begin(), anno.end(), "b1-H3N1+") == anno.end(), true) TEST_EQUAL(std::find(anno.begin(), anno.end(), "b1-C1H2N2+") == anno.end(), true) TEST_EQUAL(std::find(anno.begin(), anno.end(), "b1-C1H2N1O1+") == anno.end(), true) } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeakPickerChromatogram_test.cpp
.cpp
7,949
169
// 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/TraMLFile.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <boost/assign/std/vector.hpp> #include <OpenMS/ANALYSIS/OPENSWATH/PeakPickerChromatogram.h> using namespace OpenMS; using namespace std; typedef MSChromatogram RichPeakChromatogram; RichPeakChromatogram get_chrom(int i) { // this is a simulated SRM experiment where the two traces are not sampled at // the exact same time points, thus a resampling is necessary before applying // the algorithm. static const double rtdata_1[] = {1474.34, 1477.11, 1479.88, 1482.64, 1485.41, 1488.19, 1490.95, 1493.72, 1496.48, 1499.25, 1502.03, 1504.8 , 1507.56, 1510.33, 1513.09, 1515.87, 1518.64, 1521.42}; static const double rtdata_2[] = {1473.55, 1476.31, 1479.08, 1481.84, 1484.61, 1487.39, 1490.15, 1492.92, 1495.69, 1498.45, 1501.23, 1504 , 1506.76, 1509.53, 1512.29, 1515.07, 1517.84, 1520.62}; static const double intdata_1[] = {3.26958, 3.74189, 3.31075, 86.1901, 3.47528, 387.864, 13281 , 6375.84, 39852.6, 2.66726, 612.747, 3.34313, 793.12 , 3.29156, 4.00586, 4.1591 , 3.23035, 3.90591}; static const double intdata_2[] = {3.44054, 2142.31, 3.58763, 3076.97, 6663.55, 45681 , 157694 , 122844 , 86034.7, 85391.1, 15992.8, 2293.94, 6934.85, 2735.18, 459.413, 3.93863, 3.36564, 3.44005}; RichPeakChromatogram chromatogram; for (int k = 0; k < 18; k++) { ChromatogramPeak peak; if (i == 0) { peak.setRT(rtdata_1[k]); peak.setIntensity(intdata_1[k]); } else if (i == 1) { peak.setRT(rtdata_2[k]); peak.setIntensity(intdata_2[k]); } chromatogram.push_back(peak); } return chromatogram; } START_TEST(PeakPickerChromatogram, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeakPickerChromatogram* ptr = nullptr; PeakPickerChromatogram* nullPointer = nullptr; START_SECTION(PeakPickerChromatogram()) { ptr = new PeakPickerChromatogram(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~PeakPickerChromatogram()) { delete ptr; } END_SECTION START_SECTION(void pickChromatogram(const RichPeakChromatogram &chromatogram, RichPeakChromatogram &picked_chrom)) { RichPeakChromatogram picked_chrom, smoothed_chrom, chrom; //RichPeakChromatogram chrom = transition_group.getChromatograms()[0]; chrom = get_chrom(0); PeakPickerChromatogram picker; Param picker_param = picker.getDefaults(); picker_param.setValue("method", "legacy"); // old parameters picker_param.setValue("peak_width", 40.0); // old parameters picker.setParameters(picker_param); picker.pickChromatogram(chrom, picked_chrom); TEST_EQUAL( picked_chrom.size(), 1); TEST_EQUAL( picked_chrom.getFloatDataArrays().size(), PeakPickerChromatogram::SIZE_OF_FLOATINDICES); // Peak picking is done by cubic spline interpolation and searching for the // point with zero derivative. TEST_REAL_SIMILAR( picked_chrom[0].getIntensity(), 9981.93933103869); TEST_REAL_SIMILAR( picked_chrom[0].getRT(), 1495.11321013749); TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE][0], 60124.9); // IntegratedIntensity TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][0], 1490.95); // leftWidth TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][0], 1502.03); // rightWidth // chrom = transition_group.getChromatograms()[1]; chrom = get_chrom(1); picker.pickChromatogram(chrom, picked_chrom); TEST_EQUAL( picked_chrom.size(), 1); TEST_EQUAL( picked_chrom.getFloatDataArrays().size(), PeakPickerChromatogram::SIZE_OF_FLOATINDICES); // Peak picking is done by cubic spline interpolation and searching for the // point with zero derivative. TEST_REAL_SIMILAR( picked_chrom[0].getIntensity(), 78719.134569503); TEST_REAL_SIMILAR( picked_chrom[0].getRT(), 1492.830608593); TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE][0], 523378); // IntegratedIntensity TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][0], 1481.84); // leftWidth TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][0], 1501.23); // rightWidth /////////////////////////////////////////////////////////////////////////// // New method: Peak picking is done on the smoothed data and no minimal peak // width is set. chrom = get_chrom(0); picker_param.setValue("method", "corrected"); picker_param.setValue("peak_width", -1.0); picker.setParameters(picker_param); picker.pickChromatogram(chrom, picked_chrom); TEST_REAL_SIMILAR( picked_chrom[0].getIntensity(), 9981.93933103869); TEST_REAL_SIMILAR( picked_chrom[0].getRT(), 1495.11368082583); TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE][0], 60605.7); // IntegratedIntensity TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][0], 1482.64); // leftWidth TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][0], 1504.8); // rightWidth chrom = get_chrom(1); picker.pickChromatogram(chrom, picked_chrom); TEST_EQUAL( picked_chrom.size(), 1); TEST_EQUAL( picked_chrom.getFloatDataArrays().size(), PeakPickerChromatogram::SIZE_OF_FLOATINDICES); TEST_REAL_SIMILAR( picked_chrom[0].getIntensity(), 78719.1346); TEST_REAL_SIMILAR( picked_chrom[0].getRT(), 1492.8305); TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE][0], 525672.0); // IntegratedIntensity TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][0], 1481.84); // leftWidth TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][0], 1504.0); // rightWidth #ifdef WITH_CRAWDAD chrom = get_chrom(0); picker_param.setValue("method", "crawdad"); picker_param.setValue("peak_width", 40.0); // old parameters picker.setParameters(picker_param); picker.pickChromatogram(chrom, picked_chrom); TEST_REAL_SIMILAR( picked_chrom[0].getIntensity(), 61366.56640625); TEST_REAL_SIMILAR( picked_chrom[0].getRT(), 1496.48); TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE][0], 61366.6); // IntegratedIntensity TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][0], 1479.88); // leftWidth TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][0], 1510.33); // rightWidth chrom = get_chrom(1); picker.pickChromatogram(chrom, picked_chrom); TEST_EQUAL( picked_chrom.size(), 1); TEST_EQUAL( picked_chrom.getFloatDataArrays().size(), 3); TEST_REAL_SIMILAR( picked_chrom[0].getIntensity(), 533936.875); TEST_REAL_SIMILAR( picked_chrom[0].getRT(), 1490.15); TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE][0], 533936.875); // IntegratedIntensity TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][0], 1479.08); // leftWidth TEST_REAL_SIMILAR( picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][0], 1509.53); // rightWidth #endif } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/OSWFile_test.cpp
.cpp
7,005
160
// 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/OSWFile.h> /////////////////////////// using namespace OpenMS; using namespace std; /* Creating an OWS test database from pyProphet osw-db files (which provided the SCORE_MS2 table, which is missing in OpenSwathWorkflow outputs) Using DBBrowser for SQLite: 1) open a full blown OSW file 2) export the DB schema to a new test DB file (without the data) 3) To fill the empty test DB, we start at the highest (=Protein) level and pick all dependent rows from downstream tables using the SQL-commands below. The resulting data can be copied "as SQL-commands" and inserted into the test DB. This has to be done table by table. Sometimes, only the first columns must be selected using the mouse, because the query contains more columns from joins with other tables. Note: not all tables are populated. Only the ones we need at the moment.. SELECT * FROM PROTEIN WHERE ID IN (2,3866) --> insert data into PROTEIN table select * from PEPTIDE INNER JOIN (SELECT PEPTIDE_ID as PID, PROTEIN_ID as POD FROM PEPTIDE_PROTEIN_MAPPING) AS PEP ON PEP.PID=PEPTIDE.ID WHERE PEP.POD IN (2,3866) --> insert data into PEPTIDE table SELECT * FROM PEPTIDE_PROTEIN_MAPPING WHERE PROTEIN_ID IN (2,3866) --> insert data into PEPTIDE_PROTEIN_MAPPING table select PEPTIDE_ID, PRECURSOR_ID FROM PRECURSOR_PEPTIDE_MAPPING INNER JOIN (SELECT PEPTIDE_ID as PID, PROTEIN_ID as POD FROM PEPTIDE_PROTEIN_MAPPING) AS PEP ON PEP.PID=PEPTIDE_ID WHERE PEP.POD IN (2,3866) AND PRECURSOR_PEPTIDE_MAPPING.PEPTIDE_ID=PEP.PID --> insert data into PRECURSOR_PEPTIDE_MAPPING table SELECT * FROM PRECURSOR INNER JOIN (select PEPTIDE_ID, PRECURSOR_ID FROM PRECURSOR_PEPTIDE_MAPPING INNER JOIN (SELECT PEPTIDE_ID as PID, PROTEIN_ID as POD FROM PEPTIDE_PROTEIN_MAPPING) AS PEP ON PEP.PID=PEPTIDE_ID WHERE PEP.POD IN (2,3866) AND PRECURSOR_PEPTIDE_MAPPING.PEPTIDE_ID=PEP.PID) as PC ON PC.PRECURSOR_ID=PRECURSOR.ID --> insert data into PRECURSOR table SELECT * from FEATURE INNER JOIN (SELECT * FROM PRECURSOR INNER JOIN (select PEPTIDE_ID, PRECURSOR_ID FROM PRECURSOR_PEPTIDE_MAPPING INNER JOIN (SELECT PEPTIDE_ID as PID, PROTEIN_ID as POD FROM PEPTIDE_PROTEIN_MAPPING) AS PEP ON PEP.PID=PEPTIDE_ID WHERE PEP.POD IN (2,3866) AND PRECURSOR_PEPTIDE_MAPPING.PEPTIDE_ID=PEP.PID) as PC ON PC.PRECURSOR_ID=PRECURSOR.ID) AS PREC ON PREC.ID=FEATURE.PRECURSOR_ID --> insert data into FEATURE table SELECT * from FEATURE_TRANSITION INNER JOIN (SELECT * from FEATURE INNER JOIN (SELECT * FROM PRECURSOR INNER JOIN (select PEPTIDE_ID, PRECURSOR_ID FROM PRECURSOR_PEPTIDE_MAPPING INNER JOIN (SELECT PEPTIDE_ID as PID, PROTEIN_ID as POD FROM PEPTIDE_PROTEIN_MAPPING) AS PEP ON PEP.PID=PEPTIDE_ID WHERE PEP.POD IN (2,3866) AND PRECURSOR_PEPTIDE_MAPPING.PEPTIDE_ID=PEP.PID) as PC ON PC.PRECURSOR_ID=PRECURSOR.ID) AS PREC ON PREC.ID=FEATURE.PRECURSOR_ID) AS FEAT ON FEAT.ID=FEATURE_TRANSITION.FEATURE_ID --> insert data into FEATURE_TRANSITION table SELECT * from TRANSITION INNER JOIN (SELECT DISTINCT TRANSITION_ID from FEATURE_TRANSITION INNER JOIN (SELECT * from FEATURE INNER JOIN (SELECT * FROM PRECURSOR INNER JOIN (select PEPTIDE_ID, PRECURSOR_ID FROM PRECURSOR_PEPTIDE_MAPPING INNER JOIN (SELECT PEPTIDE_ID as PID, PROTEIN_ID as POD FROM PEPTIDE_PROTEIN_MAPPING) AS PEP ON PEP.PID=PEPTIDE_ID WHERE PEP.POD IN (2,3866) AND PRECURSOR_PEPTIDE_MAPPING.PEPTIDE_ID=PEP.PID) as PC ON PC.PRECURSOR_ID=PRECURSOR.ID) AS PREC ON PREC.ID=FEATURE.PRECURSOR_ID) AS FEAT ON FEAT.ID=FEATURE_TRANSITION.FEATURE_ID) AS FEATTR ON FEATTR.TRANSITION_ID=TRANSITION.ID --> insert data into TRANSITION table SELECT * from SCORE_MS2 INNER JOIN (SELECT * from FEATURE INNER JOIN (SELECT * FROM PRECURSOR INNER JOIN (select PEPTIDE_ID, PRECURSOR_ID FROM PRECURSOR_PEPTIDE_MAPPING INNER JOIN (SELECT PEPTIDE_ID as PID, PROTEIN_ID as POD FROM PEPTIDE_PROTEIN_MAPPING) AS PEP ON PEP.PID=PEPTIDE_ID WHERE PEP.POD IN (2,3866) AND PRECURSOR_PEPTIDE_MAPPING.PEPTIDE_ID=PEP.PID) as PC ON PC.PRECURSOR_ID=PRECURSOR.ID) AS PREC ON PREC.ID=FEATURE.PRECURSOR_ID) AS FEAT ON FEAT.ID=SCORE_MS2.FEATURE_ID --> insert data into SCORE_MS2 table (only available after pyProphet ran!) */ void checkData(OSWData& res) { const OSWProtein& prot = *res.getProteins().begin(); TEST_EQUAL(prot.getAccession(), "1/P00167ups|CYB5_HUMAN_UPS"); const OSWPeptidePrecursor& prec = *prot.getPeptidePrecursors().begin(); TEST_EQUAL(prec.getCharge(), 2); TEST_EQUAL(prec.isDecoy(), false); TEST_REAL_SIMILAR(prec.getPCMz(), 1103.4676); TEST_EQUAL(prec.getSequence(), "EQAGGDATENFEDVGHSTDAR"); TEST_EQUAL(prec.getFeatures().size(), 5); const std::vector<UInt32> tr{ 236830, 236831, 236832, 236833, 236834 }; const auto& trd = prec.getFeatures().back().getTransitionIDs(); TEST_TRUE(trd == tr); // check last transition const OSWProtein& prot_last = res.getProteins().back(); TEST_EQUAL(prot_last.getPeptidePrecursors().back().getFeatures().back().getTransitionIDs().back(), 99); // all features should have 5 transitions for (const auto& prot : res.getProteins()) { for (const auto& pc : prot.getPeptidePrecursors()) { for (const auto& feat : pc.getFeatures()) { TEST_EQUAL(feat.getTransitionIDs().size(), 5); } } } } START_TEST(OSWFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(UInt64 getRunID() const) OSWFile oswf(OPENMS_GET_TEST_DATA_PATH("OSWFile_test.osw")); TEST_EQUAL(oswf.getRunID(), 6996169951924032342); END_SECTION START_SECTION(void read(OSWData& swath_result)) OSWData res; OSWFile oswf(OPENMS_GET_TEST_DATA_PATH("OSWFile_test.osw")); oswf.read(res); TEST_EQUAL(res.getProteins().size(), 2); TEST_EQUAL(res.transitionCount(), 140); TEST_EQUAL(res.getRunID(), 6996169951924032342); checkData(res); END_SECTION START_SECTION(void readMinimal(OSWData & swath_result)) OSWData res; OSWFile oswf(OPENMS_GET_TEST_DATA_PATH("OSWFile_test.osw")); oswf.readMinimal(res); TEST_EQUAL(res.getProteins().size(), 2); TEST_EQUAL(res.transitionCount(), 140); TEST_EQUAL(res.getRunID(), 6996169951924032342); // make sure proteins are actually empty TEST_EQUAL(res.getProteins()[0].getPeptidePrecursors().empty(), true); TEST_EQUAL(res.getProteins()[1].getPeptidePrecursors().empty(), true); // now fill them... for (Size i = 0; i < res.getProteins().size(); ++i) { oswf.readProtein(res, i); } checkData(res); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/RANSACModel_test.cpp
.cpp
1,620
46
// 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/RANSACModel.h> /////////////////////////// using namespace std; using namespace OpenMS; /////////////////////////// START_TEST(RANSACModel, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION((ModelParameters rm_fit(const DVecIt& begin, const DVecIt& end) const)) NOT_TESTABLE // since base class; test derived classes END_SECTION START_SECTION((double rm_rsq(const DVecIt& begin, const DVecIt& end) const)) NOT_TESTABLE // since base class; test derived classes END_SECTION START_SECTION((double rm_rss(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients) const)) NOT_TESTABLE // since base class; test derived classes END_SECTION START_SECTION((DVec rm_inliers(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients, double max_threshold) const)) NOT_TESTABLE // since base class; test derived classes END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SplineInterpolatedPeaks_test.cpp
.cpp
5,886
172
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Lars Nilse $ // $Authors: Lars Nilse $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <OpenMS/PROCESSING/MISC/SplineInterpolatedPeaks.h> using namespace OpenMS; double Gauss1(double x) { return exp(- pow(x-416.8, 2)/(2*0.15*0.15)); } double Gauss2(double x) { return exp(- pow(x-418.7, 2)/(2*0.15*0.15)); } START_TEST(SplineInterpolatedPeaks, "$Id$") std::vector<double> pos; std::vector<double> intensity; for (int i=0; i < 11; ++i) { pos.push_back(416.3 + 0.1*i); intensity.push_back(Gauss1(416.3+0.1*i)); } for (int i=0; i < 11; ++i) { pos.push_back(418.2 + 0.1*i); intensity.push_back(Gauss2(418.2+0.1*i)); } MSSpectrum spectrum; Peak1D peak; spectrum.setRT(1789.0714); for (size_t i=0; i < pos.size(); ++i) { peak.setMZ(pos[i]); peak.setIntensity(intensity[i]); spectrum.push_back(peak); } MSChromatogram chromatogram; ChromatogramPeak peak_c; for (size_t i=0; i < pos.size(); ++i) { peak_c.setRT(pos[i]); peak_c.setIntensity(intensity[i]); chromatogram.push_back(peak_c); } SplineInterpolatedPeaks* nullPointer = nullptr; SplineInterpolatedPeaks* ptr; START_SECTION(SplineInterpolatedPeaks(const std::vector<double>& pos, const std::vector<double>& intensity)) SplineInterpolatedPeaks spline(pos, intensity); TEST_REAL_SIMILAR(spline.getPosMin(), 416.3); ptr = new SplineInterpolatedPeaks(pos, intensity); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION START_SECTION(SplineInterpolatedPeaks(const MSSpectrum& raw_spectrum)) SplineInterpolatedPeaks spline(spectrum); TEST_REAL_SIMILAR(spline.getPosMin(), 416.3) ptr = new SplineInterpolatedPeaks(spectrum); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION START_SECTION(SplineInterpolatedPeaks(const MSChromatogram& raw_chromatogram)) SplineInterpolatedPeaks spline(chromatogram); TEST_REAL_SIMILAR(spline.getPosMin(), 416.3) ptr = new SplineInterpolatedPeaks(chromatogram); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION SplineInterpolatedPeaks spectrum2(pos, intensity); START_SECTION(double getPosMin() const) TEST_EQUAL(spectrum2.getPosMin(), 416.3); END_SECTION START_SECTION(double getPosMax() const) TEST_EQUAL(spectrum2.getPosMax(), 419.2); END_SECTION START_SECTION(size_t size() const) TEST_EQUAL(spectrum2.size(), 2) END_SECTION START_SECTION(SplineInterpolatedPeaks::Navigator getNavigator(double scaling)) // just to test if it can be called SplineInterpolatedPeaks::Navigator nav = spectrum2.getNavigator(); END_SECTION START_SECTION(double SplineInterpolatedPeaks::Navigator::eval(double pos)) // outside range of Gaussians TEST_EQUAL(spectrum2.getNavigator().eval(400.0), 0); TEST_EQUAL(spectrum2.getNavigator().eval(417.8), 0); TEST_EQUAL(spectrum2.getNavigator().eval(500.0), 0); // near the edge TEST_REAL_SIMILAR(spectrum2.getNavigator().eval(416.33), 0.007848195698809); // expected 0.00738068453767004 differs by 6% // near the maximum TEST_REAL_SIMILAR(spectrum2.getNavigator().eval(416.81), 0.997572728799559); // expected 0.99778024508561 differs by 0.02% // evaluation in first package, then search in last package SplineInterpolatedPeaks::Navigator nav = spectrum2.getNavigator(); TEST_REAL_SIMILAR(nav.eval(416.81), 0.997572728799559); TEST_REAL_SIMILAR(nav.eval(418.75), 0.944147611428987); // evaluation in last package, then search in first package SplineInterpolatedPeaks::Navigator nav2 = spectrum2.getNavigator(); TEST_REAL_SIMILAR(nav2.eval(418.75), 0.944147611428987); TEST_REAL_SIMILAR(nav2.eval(416.81), 0.997572728799559); END_SECTION START_SECTION(double SplineInterpolatedPeaks::Navigator::getNextPos(double pos)) // advancing within package TEST_EQUAL(spectrum2.getNavigator().getNextPos(417.0), 417.07); // advancing to next package TEST_EQUAL(spectrum2.getNavigator().getNextPos(417.29), 418.2); // advancing beyond range TEST_REAL_SIMILAR(spectrum2.getNavigator().getNextPos(500.0), 419.2); END_SECTION // Each SplinePackage in a SplineInterpolatedPeaks must contain two or more data points. If this is not the case, the interpolation might lead to unexpected results. // In the example below, a single data point @ 407.5 is placed between two packages. It does not form a SplinePackage on its own, but is instead part of the second SplinePackage. std::vector<double> pos3; std::vector<double> intensity3; for (size_t i=0; i<4; ++i) { pos3.push_back(400+i*0.5); intensity3.push_back(10.0); } pos3.push_back(407.5); intensity3.push_back(10.0); for (size_t i=0; i<4; ++i) { pos3.push_back(410+i*0.5); intensity3.push_back(10.0); } SplineInterpolatedPeaks spectrum3(pos3, intensity3); START_SECTION(double SplineInterpolatedPeaks::Navigator::eval(double pos)) TEST_EQUAL(spectrum3.size(),2); TEST_EQUAL(spectrum3.getNavigator().eval(405),0); // Zero as expected, since 405 is between packages. TEST_EQUAL(spectrum3.getNavigator().eval(408),10); // One might expect zero, but 407.5 is part of the second package. END_SECTION std::vector<double> pos4; std::vector<double> intensity4; pos4.push_back(407.5); intensity4.push_back(10.0); START_SECTION(SplineInterpolatedPeaks(const std::vector<double>& pos, const std::vector<double>& intensity)) TEST_EXCEPTION(Exception::IllegalArgument, new SplineInterpolatedPeaks(pos4,intensity4)); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/KDTreeFeatureMaps_test.cpp
.cpp
4,459
166
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Johannes Veit $ // $Authors: Johannes Veit $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.h> #include <OpenMS/KERNEL/FeatureMap.h> using namespace OpenMS; using namespace std; START_TEST(KDTreeFeatureMaps, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Feature f1; f1.setCharge(2); f1.setIntensity(100); f1.setMZ(400); f1.setRT(1000); Feature f2; f2.setCharge(3); f2.setIntensity(1000); f2.setMZ(500); f2.setRT(2000); FeatureMap fmap; fmap.push_back(f1); fmap.push_back(f2); vector<FeatureMap> fmaps; fmaps.push_back(fmap); Param p; p.setValue("rt_tol", 100); p.setValue("mz_tol", 10); p.setValue("mz_unit", "ppm"); KDTreeFeatureMaps* ptr = nullptr; KDTreeFeatureMaps* nullPointer = nullptr; START_SECTION((KDTreeFeatureMaps())) ptr = new KDTreeFeatureMaps(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~KDTreeFeatureMaps())) delete ptr; END_SECTION START_SECTION((KDTreeFeatureMaps(const std::vector<MapType>& maps, const Param& param))) ptr = new KDTreeFeatureMaps(fmaps, p); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION KDTreeFeatureMaps kd_data_1(fmaps, p); START_SECTION((KDTreeFeatureMaps(const KDTreeFeatureMaps& rhs))) ptr = new KDTreeFeatureMaps(kd_data_1); TEST_NOT_EQUAL(ptr, nullPointer) TEST_EQUAL(ptr->size(), kd_data_1.size()) TEST_EQUAL(ptr->size(), 2) TEST_EQUAL(ptr->mz(0), kd_data_1.mz(0)) TEST_EQUAL(ptr->mz(1), kd_data_1.mz(1)) END_SECTION START_SECTION((KDTreeFeatureMaps& operator=(const KDTreeFeatureMaps& rhs))) KDTreeFeatureMaps kd_data_2 = kd_data_1; TEST_EQUAL(kd_data_2.size(), kd_data_1.size()) TEST_EQUAL(kd_data_2.size(), 2) TEST_EQUAL(kd_data_2.mz(0), kd_data_1.mz(0)) TEST_EQUAL(kd_data_2.mz(1), kd_data_1.mz(1)) END_SECTION KDTreeFeatureMaps kd_data_3; START_SECTION((void addMaps(const std::vector<MapType>& maps))) kd_data_3.addMaps(fmaps); TEST_EQUAL(kd_data_3.size(), 2); END_SECTION START_SECTION((void addFeature(Size mt_map_index, const BaseFeature* feature))) Feature f3; f3.setMZ(300); f3.setRT(500); kd_data_3.addFeature(2, &f3); TEST_EQUAL(kd_data_3.size(), 3); END_SECTION START_SECTION((const BaseFeature* feature(Size i) const)) TEST_EQUAL(kd_data_1.feature(0), &(fmaps[0][0])) TEST_EQUAL(kd_data_1.feature(1), &(fmaps[0][1])) END_SECTION START_SECTION((double rt(Size i) const)) TEST_REAL_SIMILAR(kd_data_1.rt(0), 1000) END_SECTION START_SECTION((double mz(Size i) const)) TEST_REAL_SIMILAR(kd_data_1.mz(0), 400) END_SECTION START_SECTION((float intensity(Size i) const)) TEST_REAL_SIMILAR(kd_data_1.intensity(0), 100) END_SECTION START_SECTION((Int charge(Size i) const)) TEST_EQUAL(kd_data_1.charge(0), 2) END_SECTION START_SECTION((Size mapIndex(Size i) const)) TEST_EQUAL(kd_data_1.mapIndex(0), 0) END_SECTION START_SECTION((Size size() const)) TEST_EQUAL(kd_data_1.size(), 2) TEST_EQUAL(kd_data_3.size(), 3) END_SECTION START_SECTION((Size treeSize() const)) TEST_EQUAL(kd_data_1.treeSize(), 2) TEST_EQUAL(kd_data_3.treeSize(), 3) END_SECTION START_SECTION((Size numMaps() const)) TEST_EQUAL(kd_data_1.numMaps(), 1) END_SECTION START_SECTION((void clear())) kd_data_3.clear(); TEST_EQUAL(kd_data_3.size(), 0) TEST_EQUAL(kd_data_3.treeSize(), 0) END_SECTION START_SECTION((void optimizeTree())) NOT_TESTABLE; END_SECTION START_SECTION((void getNeighborhood(Size index, std::vector<Size>& result_indices, bool include_features_from_same_map = false) const)) NOT_TESTABLE; END_SECTION START_SECTION((void queryRegion(double rt_low, double rt_high, double mz_low, double mz_high, std::vector<Size>& result_indices, Size ignored_map_index = std::numeric_limits<Size>::max()) const)) NOT_TESTABLE; END_SECTION START_SECTION((void applyTransformations(const std::vector<TransformationModelLowess*>& trafos))) NOT_TESTABLE; END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/UniqueIdIndexer_test.cpp
.cpp
4,756
203
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CONCEPT/UniqueIdIndexer.h> #include <OpenMS/DATASTRUCTURES/ExposedVector.h> #include <OpenMS/MATH/MathFunctions.h> #include <vector> /////////////////////////// using namespace OpenMS; using namespace std; namespace OpenMS { struct Dummy : UniqueIdInterface { Dummy () : dummy(0) {} Size dummy; }; class DummyVectorIndexed : public ExposedVector<Dummy>, public UniqueIdIndexer<DummyVectorIndexed> { public: EXPOSED_VECTOR_INTERFACE(Dummy) }; // this is used for testing purposes only template < typename T > struct CanAccessTheUniqueIdMap : T { DummyVectorIndexed::UniqueIdMap & getUniqueIdMap() { return this->uniqueid_to_index_; } }; // this saves us some typing template < typename T > CanAccessTheUniqueIdMap<T>& canAccessTheUniqueIdMap(T &rhs) { return static_cast<CanAccessTheUniqueIdMap<T>&>(rhs); } } START_TEST(UniqueIdIndexer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// DummyVectorIndexed* ptr = nullptr; DummyVectorIndexed* nullPointer = nullptr; START_SECTION((UniqueIdIndexer())) { ptr = new DummyVectorIndexed(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((~UniqueIdIndexer())) { delete ptr; } END_SECTION START_SECTION((Size uniqueIdToIndex(UInt64 unique_id) const)) { DummyVectorIndexed dvi; Size num_uii = 10; dvi.resize(num_uii); for ( Size i = 0; i < num_uii; ++i ) { dvi[i].dummy = i; dvi[i].setUniqueId(10*i+1000); } for ( Size i = 0; i < num_uii; ++i ) { TEST_EQUAL(dvi.uniqueIdToIndex(10*i+1000),i); } STATUS("shuffling ..."); Math::RandomShuffler r{0}; r.portable_random_shuffle(dvi.begin(), dvi.end()); for ( Size i = 0; i < num_uii; ++i ) { Dummy const & current_dummy = dvi[i]; TEST_EQUAL(dvi.uniqueIdToIndex(current_dummy.getUniqueId()),i); // TEST_EQUAL(dvidvi[current_dummy.dummy].getUniqueId()),current_dummy.dummy); } dvi.pop_back(); dvi.pop_back(); dvi.push_back(Dummy()); dvi.back().setUniqueId(12345678); dvi.push_back(Dummy()); dvi.push_back(Dummy()); dvi.back().setUniqueId(12345678); dvi.push_back(Dummy()); STATUS("shuffling ..."); r.portable_random_shuffle(dvi.begin(), dvi.end()); TEST_EXCEPTION_WITH_MESSAGE(Exception::Postcondition,dvi.updateUniqueIdToIndex(),"Duplicate valid unique ids detected! RandomAccessContainer has size()==12, num_valid_unique_id==10, uniqueid_to_index_.size()==9"); } END_SECTION START_SECTION((void updateUniqueIdToIndex() const)) { // see uniqueIdToIndex() NOT_TESTABLE; } END_SECTION START_SECTION((Size resolveUniqueIdConflicts())) DummyVectorIndexed dvi; Size num_uii = 10; dvi.resize(num_uii); for ( Size i = 0; i < num_uii; ++i ) { dvi[i].dummy = i; dvi[i].setUniqueId(10*i+1000); } TEST_EQUAL(dvi.resolveUniqueIdConflicts(), 0); // introduce three doubles Dummy a,b; a.setUniqueId(1000); b.setUniqueId(1000+30); dvi.push_back(a); dvi.push_back(b); dvi.push_back(b); TEST_EXCEPTION(Exception::Postcondition,dvi.updateUniqueIdToIndex()); TEST_EQUAL(dvi.resolveUniqueIdConflicts(), 3); END_SECTION START_SECTION((void swap(UniqueIdIndexer &rhs))) { DummyVectorIndexed dvi; Size num_uii = 10; dvi.resize(num_uii); for ( Size i = 0; i < num_uii; ++i ) { dvi[i].dummy = i; dvi[i].setUniqueId(10*i+1000); } dvi.updateUniqueIdToIndex(); DummyVectorIndexed dvi2; TEST_EQUAL(canAccessTheUniqueIdMap(dvi).getUniqueIdMap().size(),num_uii); TEST_EQUAL(canAccessTheUniqueIdMap(dvi2).getUniqueIdMap().size(),0); std::swap(dvi, dvi2); TEST_EQUAL(canAccessTheUniqueIdMap(dvi).getUniqueIdMap().size(),0); TEST_EQUAL(canAccessTheUniqueIdMap(dvi2).getUniqueIdMap().size(),num_uii); dvi = dvi2; TEST_EQUAL(canAccessTheUniqueIdMap(dvi).getUniqueIdMap().size(),num_uii); canAccessTheUniqueIdMap(dvi).getUniqueIdMap().clear(); TEST_EQUAL(canAccessTheUniqueIdMap(dvi).getUniqueIdMap().size(),0); TEST_EQUAL(dvi.uniqueIdToIndex(4321234324124ull),Size(-1)); TEST_EQUAL(canAccessTheUniqueIdMap(dvi).getUniqueIdMap().size(),num_uii); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SourceFile_test.cpp
.cpp
6,629
215
// 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/SourceFile.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(SourceFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// SourceFile* ptr = nullptr; SourceFile* nullPointer = nullptr; START_SECTION((SourceFile())) ptr = new SourceFile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~SourceFile())) delete ptr; END_SECTION START_SECTION((float getFileSize() const)) SourceFile tmp; TEST_EQUAL(tmp.getFileSize(),0); END_SECTION START_SECTION((void setFileSize(float file_size))) SourceFile tmp; tmp.setFileSize(1.667f); TEST_REAL_SIMILAR(tmp.getFileSize(),1.667f); END_SECTION START_SECTION((const String& getFileType() const)) SourceFile tmp; TEST_EQUAL(tmp.getFileType(), ""); END_SECTION START_SECTION((void setFileType(const String& file_type))) SourceFile tmp; tmp.setFileType("PEAKDATA"); TEST_EQUAL(tmp.getFileType(), "PEAKDATA"); END_SECTION START_SECTION((const String& getNameOfFile() const)) SourceFile tmp; TEST_EQUAL(tmp.getNameOfFile(),""); END_SECTION START_SECTION((void setNameOfFile(const String& name_of_file))) SourceFile tmp; tmp.setNameOfFile("The White Stripes - Ball and Biscuit"); TEST_EQUAL(tmp.getNameOfFile(),"The White Stripes - Ball and Biscuit"); END_SECTION START_SECTION((const String& getPathToFile() const)) SourceFile tmp; TEST_EQUAL(tmp.getPathToFile(),""); END_SECTION START_SECTION((void setPathToFile(const String& path_path_to_file))) SourceFile tmp; tmp.setPathToFile("/misc/sturm/mp3/"); TEST_EQUAL(tmp.getPathToFile(),"/misc/sturm/mp3/"); END_SECTION START_SECTION((const String& getChecksum() const)) SourceFile tmp; TEST_EQUAL(tmp.getChecksum(), ""); END_SECTION START_SECTION(ChecksumType getChecksumType() const) SourceFile tmp; TEST_EQUAL(tmp.getChecksumType(), SourceFile::ChecksumType::UNKNOWN_CHECKSUM); END_SECTION START_SECTION((void setChecksum(const String& checksum, ChecksumType type))) SourceFile tmp; tmp.setChecksum("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",SourceFile::ChecksumType::SHA1); TEST_EQUAL(tmp.getChecksum(), "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"); TEST_EQUAL(tmp.getChecksumType(), SourceFile::ChecksumType::SHA1); END_SECTION START_SECTION((const String& getNativeIDType() const)) SourceFile tmp; TEST_STRING_EQUAL(tmp.getNativeIDType(), ""); END_SECTION START_SECTION((void setNativeIDType(const String& type))) SourceFile tmp; tmp.setNativeIDType("bla"); TEST_STRING_EQUAL(tmp.getNativeIDType(), "bla"); END_SECTION START_SECTION((SourceFile(const SourceFile& source))) SourceFile tmp; tmp.setFileType("CALIBRATIONINFO"); tmp.setNameOfFile("The White Stripes - Ball and Biscuit"); tmp.setPathToFile("/misc/sturm/mp3/"); tmp.setChecksum("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12", SourceFile::ChecksumType::MD5); tmp.setMetaValue("bla",4.0); SourceFile tmp2(tmp); TEST_EQUAL(tmp2.getFileType(), "CALIBRATIONINFO"); TEST_EQUAL(tmp2.getNameOfFile(),"The White Stripes - Ball and Biscuit"); TEST_EQUAL(tmp2.getPathToFile(),"/misc/sturm/mp3/"); TEST_EQUAL(tmp2.getChecksum(), "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"); TEST_EQUAL(tmp2.getChecksumType(), SourceFile::ChecksumType::MD5); TEST_REAL_SIMILAR(tmp2.getMetaValue("bla"), 4.0); END_SECTION START_SECTION((SourceFile& operator= (const SourceFile& source))) SourceFile tmp; tmp.setFileType("PUBLICATION"); tmp.setNameOfFile("The White Stripes - Ball and Biscuit"); tmp.setPathToFile("/misc/sturm/mp3/"); tmp.setChecksum("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12", SourceFile::ChecksumType::MD5); tmp.setMetaValue("bla",4.0); //normal assignment SourceFile tmp2; tmp2 = tmp; TEST_EQUAL(tmp2.getFileType(),"PUBLICATION"); TEST_EQUAL(tmp2.getNameOfFile(),"The White Stripes - Ball and Biscuit"); TEST_EQUAL(tmp2.getPathToFile(),"/misc/sturm/mp3/"); TEST_EQUAL(tmp2.getChecksum(),"2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"); TEST_EQUAL(tmp2.getChecksumType(), SourceFile::ChecksumType::MD5); TEST_REAL_SIMILAR(tmp2.getMetaValue("bla"), 4.0); //assignment of empty object tmp2 = SourceFile(); TEST_EQUAL(tmp2.getFileType(), ""); TEST_EQUAL(tmp2.getNameOfFile(),""); TEST_EQUAL(tmp2.getPathToFile(),""); TEST_EQUAL(tmp2.getChecksum(),""); TEST_EQUAL(tmp2.getChecksumType(), SourceFile::ChecksumType::UNKNOWN_CHECKSUM); TEST_EQUAL(tmp2.metaValueExists("bla"), false); END_SECTION START_SECTION((bool operator== (const SourceFile& rhs) const)) SourceFile tmp,tmp2; TEST_TRUE(tmp == tmp2); tmp2.setFileType("PARAMETERSFILE"); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setNameOfFile("The White Stripes - Ball and Biscuit"); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setChecksum("", SourceFile::ChecksumType::MD5); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setMetaValue("bla",4.0); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setPathToFile("/misc/sturm/mp3/"); TEST_EQUAL(tmp==tmp2, false); END_SECTION START_SECTION((bool operator!= (const SourceFile& rhs) const)) SourceFile tmp,tmp2; TEST_EQUAL(tmp!=tmp2, false); tmp2.setFileType("MISC"); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setNameOfFile("The White Stripes - Ball and Biscuit"); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setChecksum("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12", SourceFile::ChecksumType::UNKNOWN_CHECKSUM); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setMetaValue("bla",4.0); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setPathToFile("/misc/sturm/mp3/"); TEST_FALSE(tmp == tmp2); END_SECTION START_SECTION((static StringList getAllNamesOfChecksumType())) StringList names = SourceFile::getAllNamesOfChecksumType(); TEST_EQUAL(names.size(), static_cast<size_t>(SourceFile::ChecksumType::SIZE_OF_CHECKSUMTYPE)); TEST_EQUAL(names[static_cast<size_t>(SourceFile::ChecksumType::SHA1)], "SHA-1"); TEST_EQUAL(names[static_cast<size_t>(SourceFile::ChecksumType::MD5)], "MD5"); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DataProcessing_test.cpp
.cpp
5,198
175
// 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/DataProcessing.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(DataProcessing, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// DateTime time; time.set("2000-10-09 08:07:40"); DataProcessing* ptr = nullptr; DataProcessing* nullPointer = nullptr; START_SECTION(DataProcessing()) ptr = new DataProcessing(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~DataProcessing()) delete ptr; END_SECTION START_SECTION(const DateTime& getCompletionTime() const) DataProcessing tmp; TEST_EQUAL(tmp.getCompletionTime().get(),"0000-00-00 00:00:00"); END_SECTION START_SECTION(void setCompletionTime(const DateTime& completion_time)) DataProcessing tmp; tmp.setCompletionTime(time); TEST_EQUAL(tmp.getCompletionTime()==time,true); END_SECTION START_SECTION(Software& getSoftware()) DataProcessing tmp; TEST_EQUAL(tmp.getSoftware()==Software(),true) END_SECTION START_SECTION(const Software& getSoftware() const) DataProcessing tmp; tmp.getSoftware().setName("name"); TEST_STRING_EQUAL(tmp.getSoftware().getName(),"name") END_SECTION START_SECTION(void setSoftware(const Software& software)) DataProcessing tmp; Software tmp2; tmp2.setName("name"); tmp.setSoftware(tmp2); TEST_STRING_EQUAL(tmp.getSoftware().getName(),"name") END_SECTION START_SECTION(const std::set<ProcessingAction>& getProcessingActions() const) DataProcessing tmp; TEST_EQUAL(tmp.getProcessingActions().size(),0) END_SECTION START_SECTION(std::set<ProcessingAction>& getProcessingActions()) DataProcessing tmp; tmp.getProcessingActions().insert(DataProcessing::DEISOTOPING); TEST_EQUAL(tmp.getProcessingActions().size(),1) END_SECTION START_SECTION(void setProcessingActions(const std::set<ProcessingAction>& actions)) DataProcessing tmp; std::set<DataProcessing::ProcessingAction> tmp2; tmp2.insert(DataProcessing::DEISOTOPING); tmp2.insert(DataProcessing::CHARGE_DECONVOLUTION); tmp.setProcessingActions(tmp2); TEST_EQUAL(tmp.getProcessingActions().size(),2) END_SECTION START_SECTION(DataProcessing& operator= (const DataProcessing& source)) DataProcessing tmp; tmp.setCompletionTime(time); tmp.getProcessingActions().insert(DataProcessing::DEISOTOPING); tmp.getSoftware().setName("name"); tmp.setMetaValue("label",String("label")); DataProcessing tmp2; tmp2 = tmp; TEST_EQUAL(tmp2.getCompletionTime()==time,true); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_EQUAL(tmp2.getProcessingActions().size(),1) TEST_STRING_EQUAL(tmp2.getSoftware().getName(),"name") END_SECTION START_SECTION(DataProcessing(const DataProcessing& source)) DataProcessing tmp; tmp.setCompletionTime(time); tmp.getProcessingActions().insert(DataProcessing::DEISOTOPING); tmp.getSoftware().setName("name"); tmp.setMetaValue("label",String("label")); DataProcessing tmp2(tmp); tmp2 = tmp; TEST_EQUAL(tmp2.getCompletionTime()==time,true); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_EQUAL(tmp2.getProcessingActions().size(),1) TEST_STRING_EQUAL(tmp2.getSoftware().getName(),"name") END_SECTION START_SECTION(bool operator== (const DataProcessing& rhs) const) DataProcessing edit, empty; TEST_TRUE(edit == empty); edit.setCompletionTime(time); TEST_EQUAL(edit==empty, false); edit = empty; edit.getProcessingActions().insert(DataProcessing::DEISOTOPING); TEST_EQUAL(edit==empty, false); edit = empty; edit.getSoftware().setName("name"); TEST_EQUAL(edit==empty, false); edit = empty; edit.setMetaValue("label",String("label")); TEST_EQUAL(edit==empty, false); END_SECTION START_SECTION(bool operator!= (const DataProcessing& rhs) const) DataProcessing edit, empty; TEST_EQUAL(edit!=empty, false); edit.setCompletionTime(time); TEST_FALSE(edit == empty); edit = empty; edit.getProcessingActions().insert(DataProcessing::DEISOTOPING); TEST_FALSE(edit == empty); edit = empty; edit.getSoftware().setName("name"); TEST_FALSE(edit == empty); edit = empty; edit.setMetaValue("label",String("label")); TEST_FALSE(edit == empty); END_SECTION START_SECTION((static StringList getAllNamesOfProcessingAction())) StringList names = DataProcessing::getAllNamesOfProcessingAction(); TEST_EQUAL(names.size(), DataProcessing::SIZE_OF_PROCESSINGACTION); TEST_EQUAL(names[DataProcessing::PEAK_PICKING], "Peak picking"); TEST_EQUAL(names[DataProcessing::SMOOTHING], "Smoothing"); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DistanceMatrix_test.cpp
.cpp
5,880
236
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer$ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/DistanceMatrix.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(DistanceMatrix, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// DistanceMatrix<double>* ptr = nullptr; DistanceMatrix<double>* nullPointer = nullptr; START_SECTION(DistanceMatrix()) { ptr = new DistanceMatrix<double>(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~DistanceMatrix()) { delete ptr; } END_SECTION DistanceMatrix<double> dm(8,1.0); START_SECTION((DistanceMatrix(SizeType dimensionsize, Value value=Value()))) { TEST_EQUAL(dm.dimensionsize(), 8) TEST_EQUAL(dm(6,7),1) } END_SECTION DistanceMatrix<double> dm2(dm); START_SECTION((DistanceMatrix(const DistanceMatrix &source))) { TEST_EQUAL(dm2.dimensionsize(), 8) TEST_EQUAL(dm2(2,3),1) } END_SECTION START_SECTION(void resize(SizeType dimensionsize, Value value=Value())) { dm2.resize(5); TEST_EQUAL(dm2.dimensionsize(),5) } END_SECTION START_SECTION((SizeType dimensionsize() const)) { TEST_EQUAL(dm2.dimensionsize(),5) } END_SECTION START_SECTION((void setValue(SizeType i, SizeType j, ValueType value))) { dm.setValue(0,1,10); dm.setValue(0,2,9); dm.setValue(0,3,8); dm.setValue(0,4,7); dm.setValue(1,2,6); dm.setValue(1,3,5); dm.setValue(1,4,4); dm.setValue(2,3,3); dm.setValue(2,4,2); dm.setValue(3,4,0.5); TEST_EQUAL(dm.getValue(0,1),10) TEST_EQUAL(dm.getValue(dm.getMinElementCoordinates().first, dm.getMinElementCoordinates().second),0.5) dm.setValue(3,4,1); TEST_EQUAL(dm.getValue(dm.getMinElementCoordinates().first, dm.getMinElementCoordinates().second),1.0) //more tested below } END_SECTION START_SECTION((const ValueType getValue(SizeType i, SizeType j) const)) { TEST_EQUAL(dm.getValue(0,1),10) TEST_EQUAL(dm.getValue(0,2),9) TEST_EQUAL(dm.getValue(0,3),8) TEST_EQUAL(dm.getValue(0,4),7) TEST_EQUAL(dm.getValue(1,2),6) TEST_EQUAL(dm.getValue(1,3),5) TEST_EQUAL(dm.getValue(1,4),4) TEST_EQUAL(dm.getValue(2,3),3) TEST_EQUAL(dm.getValue(2,4),2) TEST_EQUAL(dm.getValue(3,4),1) } END_SECTION START_SECTION((ValueType getValue(SizeType i, SizeType j))) { TEST_EQUAL(dm.getValue(0,1),10) TEST_EQUAL(dm.getValue(0,2),9) TEST_EQUAL(dm.getValue(0,3),8) TEST_EQUAL(dm.getValue(0,4),7) TEST_EQUAL(dm.getValue(1,2),6) TEST_EQUAL(dm.getValue(1,3),5) TEST_EQUAL(dm.getValue(1,4),4) TEST_EQUAL(dm.getValue(2,3),3) TEST_EQUAL(dm.getValue(2,4),2) TEST_EQUAL(dm.getValue(3,4),1) } END_SECTION START_SECTION((void clear())) { dm2.clear(); TEST_EQUAL(dm2.dimensionsize(),0) } END_SECTION START_SECTION((void setValueQuick(SizeType i, SizeType j, ValueType value))) { dm.setValueQuick(0,1,1); dm.setValueQuick(0,2,2); dm.setValueQuick(0,3,3); dm.setValueQuick(0,4,4); dm.setValueQuick(1,2,5); dm.setValueQuick(1,3,6); dm.setValueQuick(1,4,7); dm.setValueQuick(2,3,8); dm.setValueQuick(2,4,9); dm.setValueQuick(3,4,10); TEST_EQUAL(dm.getValue(0,1),1) TEST_EQUAL(dm.getValue(0,2),2) TEST_EQUAL(dm.getValue(0,3),3) TEST_EQUAL(dm.getValue(0,4),4) TEST_EQUAL(dm.getValue(1,2),5) TEST_EQUAL(dm.getValue(1,3),6) TEST_EQUAL(dm.getValue(1,4),7) TEST_EQUAL(dm.getValue(2,3),8) TEST_EQUAL(dm.getValue(2,4),9) TEST_EQUAL(dm.getValue(3,4),10) } END_SECTION START_SECTION((const ValueType operator()(SizeType i, SizeType j) const)) { TEST_EQUAL(dm.getValue(0,1),dm(0,1)) TEST_EQUAL(dm.getValue(0,2),dm(0,2)) TEST_EQUAL(dm.getValue(0,3),dm(0,3)) TEST_EQUAL(dm.getValue(0,4),dm(0,4)) TEST_EQUAL(dm.getValue(1,2),dm(1,2)) TEST_EQUAL(dm.getValue(1,3),dm(1,3)) TEST_EQUAL(dm.getValue(1,4),dm(1,4)) TEST_EQUAL(dm.getValue(2,3),dm(2,3)) TEST_EQUAL(dm.getValue(2,4),dm(2,4)) TEST_EQUAL(dm.getValue(3,4),dm(3,4)) } END_SECTION START_SECTION((ValueType operator()(SizeType i, SizeType j))) { TEST_EQUAL(dm.getValue(0,1),dm(0,1)) TEST_EQUAL(dm.getValue(0,2),dm(0,2)) TEST_EQUAL(dm.getValue(0,3),dm(0,3)) TEST_EQUAL(dm.getValue(0,4),dm(0,4)) TEST_EQUAL(dm.getValue(1,2),dm(1,2)) TEST_EQUAL(dm.getValue(1,3),dm(1,3)) TEST_EQUAL(dm.getValue(1,4),dm(1,4)) TEST_EQUAL(dm.getValue(2,3),dm(2,3)) TEST_EQUAL(dm.getValue(2,4),dm(2,4)) TEST_EQUAL(dm.getValue(3,4),dm(3,4)) } END_SECTION START_SECTION((void reduce(SizeType j))) { dm.reduce(2); TEST_EQUAL(dm.getValue(0,1),1) TEST_EQUAL(dm.getValue(0,2),3) TEST_EQUAL(dm.getValue(0,3),4) TEST_EQUAL(dm.getValue(1,2),6) TEST_EQUAL(dm.getValue(1,3),7) TEST_EQUAL(dm.getValue(2,3),10) TEST_EQUAL(dm.dimensionsize(),7) } END_SECTION START_SECTION((std::pair<SizeType,SizeType> getMinElementCoordinates() const)) { dm.updateMinElement(); pair<Size,Size> min = dm.getMinElementCoordinates(); TEST_EQUAL(min.first,1) TEST_EQUAL(min.second,0) } END_SECTION START_SECTION((void updateMinElement())) { dm.setValueQuick(2,3,0.5); dm.updateMinElement(); std::pair<Size,Size> min = dm.getMinElementCoordinates(); TEST_EQUAL(min.first,3) TEST_EQUAL(min.second,2) } END_SECTION DistanceMatrix<double> dm3(dm); START_SECTION(bool operator==(DistanceMatrix< ValueType > const &rhs) const) { TEST_EQUAL((dm==dm3),true) } END_SECTION START_SECTION((template <typename Value> std::ostream & operator<<(std::ostream &os, const DistanceMatrix< Value > &matrix))) { NOT_TESTABLE } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IsotopeFitter1D_test.cpp
.cpp
2,732
96
// 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/IsotopeFitter1D.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(IsotopeFitter1D, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// IsotopeFitter1D* ptr = nullptr; IsotopeFitter1D* nullPointer = nullptr; START_SECTION(IsotopeFitter1D()) { ptr = new IsotopeFitter1D(); TEST_EQUAL(ptr->getName(), "IsotopeFitter1D") TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((IsotopeFitter1D(const IsotopeFitter1D &source))) IsotopeFitter1D isof1; 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( "charge", 1 ); param.setValue( "isotope:stdev", 0.04 ); param.setValue( "isotope:maximum", 20 ); isof1.setParameters(param); IsotopeFitter1D isof2(isof1); IsotopeFitter1D isof3; isof3.setParameters(param); isof1 = IsotopeFitter1D(); TEST_EQUAL(isof3.getParameters(), isof2.getParameters()) END_SECTION START_SECTION((virtual ~IsotopeFitter1D())) delete ptr; END_SECTION START_SECTION((virtual IsotopeFitter1D& operator=(const IsotopeFitter1D &source))) IsotopeFitter1D isof1; 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( "charge", 1 ); param.setValue( "isotope:stdev", 0.04 ); param.setValue( "isotope:maximum", 20 ); isof1.setParameters(param); IsotopeFitter1D isof2; isof2 = isof1; IsotopeFitter1D isof3; isof3.setParameters(param); isof1 = IsotopeFitter1D(); TEST_EQUAL(isof3.getParameters(), isof3.getParameters()) END_SECTION START_SECTION((QualityType fit1d(const RawDataArrayType &range, InterpolationModel *&model))) // dummy subtest IsotopeFitter1D if1; if1 = IsotopeFitter1D(); TEST_EQUAL(if1.getParameters(), if1.getParameters()) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MultiplexClustering_test.cpp
.cpp
4,285
102
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Lars Nilse $ // $Authors: Lars Nilse $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FEATUREFINDER/MultiplexDeltaMasses.h> #include <OpenMS/FEATUREFINDER/MultiplexFilteringProfile.h> #include <OpenMS/FEATUREFINDER/MultiplexFilteredMSExperiment.h> #include <OpenMS/FEATUREFINDER/MultiplexClustering.h> #include <OpenMS/FORMAT/MzMLFile.h> using namespace OpenMS; START_TEST(MultiplexFilteringProfile, "$Id$") // read data MSExperiment exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MultiplexClustering.mzML"), exp); exp.updateRanges(); // pick data 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; MSExperiment exp_picked; picker.pickExperiment(exp, exp_picked, boundaries_exp_s, boundaries_exp_c); // set parameters int charge_min = 1; int charge_max = 4; int isotopes_per_peptide_min = 3; int isotopes_per_peptide_max = 6; double intensity_cutoff = 10.0; double rt_band = 3; double rt_typical = 90; double mz_tolerance = 40; bool mz_tolerance_unit = true; // ppm (true), Da (false) double peptide_similarity = 0.8; double averagine_similarity = 0.75; double averagine_similarity_scaling = 0.75; String averagine_type="peptide"; // construct list of peak patterns MultiplexDeltaMasses shifts1; shifts1.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(0, "no_label")); shifts1.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(8.0443702794, "Arg8")); MultiplexDeltaMasses shifts2; shifts2.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(0, "no_label")); MultiplexDeltaMasses::LabelSet label_set; label_set.insert("Arg8"); label_set.insert("Arg8"); shifts2.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(2*8.0443702794, label_set)); std::vector<MultiplexIsotopicPeakPattern> patterns; for (int c = charge_max; c >= charge_min; --c) { MultiplexIsotopicPeakPattern pattern1(c, isotopes_per_peptide_max, shifts1, 0); patterns.push_back(pattern1); MultiplexIsotopicPeakPattern pattern2(c, isotopes_per_peptide_max, shifts2, 1); patterns.push_back(pattern2); } MultiplexFilteringProfile filtering(exp, exp_picked, boundaries_exp_s, patterns, isotopes_per_peptide_min, isotopes_per_peptide_max, intensity_cutoff, rt_band, mz_tolerance, mz_tolerance_unit, peptide_similarity, averagine_similarity, averagine_similarity_scaling, averagine_type); std::vector<MultiplexFilteredMSExperiment> filter_results = filtering.filter(); MultiplexClustering* nullPointer = nullptr; MultiplexClustering* ptr; START_SECTION(MultiplexClustering(const MSExperiment& exp_profile, const MSExperiment& exp_picked, const std::vector<std::vector<PeakPickerHiRes::PeakBoundary> >& boundaries, double rt_typical)) MultiplexClustering clustering(exp, exp_picked, boundaries_exp_s, rt_typical); std::vector<std::map<int,GridBasedCluster> > cluster_results = clustering.cluster(filter_results); ptr = new MultiplexClustering(exp, exp_picked, boundaries_exp_s, rt_typical); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION MultiplexClustering clustering(exp, exp_picked, boundaries_exp_s, rt_typical); START_SECTION(cluster(const std::vector<MultiplexFilteredMSExperiment>& filter_results)) std::vector<std::map<int,GridBasedCluster> > cluster_results = clustering.cluster(filter_results); TEST_EQUAL(cluster_results[0].size(), 0); TEST_EQUAL(cluster_results[1].size(), 0); TEST_EQUAL(cluster_results[2].size(), 0); TEST_EQUAL(cluster_results[3].size(), 0); TEST_EQUAL(cluster_results[4].size(), 2); TEST_EQUAL(cluster_results[5].size(), 0); TEST_EQUAL(cluster_results[6].size(), 0); TEST_EQUAL(cluster_results[7].size(), 0); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Base64_test.cpp
.cpp
16,200
507
// 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/Base64.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/UniqueIdGenerator.h> using namespace std; START_TEST(Base64, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; // default ctor Base64* ptr = nullptr; Base64* nullPointer = nullptr; START_SECTION((Base64())) ptr = new Base64; TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION // destructor START_SECTION((virtual ~Base64())) delete ptr; END_SECTION /* Python # Little Endian floats >>> import base64 >>> import struct >>> mynr = base64.standard_b64decode("pDiTRQ==") >>> [struct.unpack('<f', mynr[i:i+4]) for i in range(0, len(mynr), 4) ] [(4711.080078125,)] # Big Endian doubles >>> import base64 >>> import struct >>> mynr = base64.standard_b64decode("QHLCZmZmZmZAcv/3ztkWh0BzCZmZmZma") >>> [struct.unpack('>d', mynr[i:i+8]) for i in range(0, len(mynr), 8) ] [(300.15,), (303.998,), (304.6,)] */ START_SECTION((template < typename FromType > void encode(std::vector< FromType > &in, ByteOrder to_byte_order, String &out, bool zlib_compression=false))) TOLERANCE_ABSOLUTE(0.001) { Base64 b64; std::vector<float> data; std::vector<float> res; String dest; b64.encode(data, Base64::BYTEORDER_LITTLEENDIAN, dest); TEST_EQUAL(dest, ""); data.push_back(300.15f); data.push_back(303.998f); data.push_back(304.6f); b64.encode(data, Base64::BYTEORDER_LITTLEENDIAN, dest); TEST_EQUAL(dest, "MxOWQ77/l0PNTJhD"); // please remember that it is possible that two different strings can // decode to the "same" floating point number (considering such a low // precision like 0.001). data = std::vector<float>(); data.push_back(4711.08f); b64.encode(data, Base64::BYTEORDER_LITTLEENDIAN, dest); TEST_EQUAL(dest, "pDiTRQ==") // testing the encoding of double vectors std::vector<double> data_double; std::vector<double> res_double; data_double.push_back(300.15); data_double.push_back(303.998); data_double.push_back(304.6); b64.encode(data_double, Base64::BYTEORDER_BIGENDIAN, dest); TEST_EQUAL(dest, "QHLCZmZmZmZAcv/3ztkWh0BzCZmZmZma"); b64.decode(dest,Base64::BYTEORDER_BIGENDIAN,res_double); } END_SECTION START_SECTION((template < typename ToType > void decode(const String &in, ByteOrder from_byte_order, std::vector< ToType > &out, bool zlib_compression=false))) TOLERANCE_ABSOLUTE(0.001) { Base64 b64; String src; std::vector<float> res; std::vector<double> res_double; b64.decode(src, Base64::BYTEORDER_BIGENDIAN, res); TEST_EQUAL(res.size(), 0) src = "Q+vIuEec9YBD7TgoR/HTgEPt23hHA8UA"; b64.decode(src, Base64::BYTEORDER_BIGENDIAN, res); TEST_REAL_SIMILAR(res[0], 471.568) TEST_REAL_SIMILAR(res[1], 80363) TEST_REAL_SIMILAR(res[2], 474.439) TEST_REAL_SIMILAR(res[3], 123815) TEST_REAL_SIMILAR(res[4], 475.715) TEST_REAL_SIMILAR(res[5], 33733) src = "JhOWQ8b/l0PMTJhD"; b64.decode(src, Base64::BYTEORDER_LITTLEENDIAN, res); TEST_REAL_SIMILAR(res[0], 300.15) TEST_REAL_SIMILAR(res[1], 303.998) TEST_REAL_SIMILAR(res[2], 304.6) src = "QGYTSADLaUgAAABA"; b64.decode(src, Base64::BYTEORDER_LITTLEENDIAN, res); TEST_REAL_SIMILAR(res[0], 150937) TEST_REAL_SIMILAR(res[1], 239404) TEST_REAL_SIMILAR(res[2], 2) src = "QHLCZmZmZmZAcv/3ztkWh0BzCZmZmZma"; b64.decode(src, Base64::BYTEORDER_BIGENDIAN, res_double); TEST_REAL_SIMILAR(res_double[0], 300.15) TEST_REAL_SIMILAR(res_double[1], 303.998) TEST_REAL_SIMILAR(res_double[2], 304.6) // test some corrupted strings src = "=="; b64.decode(src, Base64::BYTEORDER_BIGENDIAN, res); TEST_EQUAL(res.size(), 0) src = "Q=="; b64.decode(src, Base64::BYTEORDER_BIGENDIAN, res); TEST_EQUAL(res.size(), 0) src = "===="; b64.decode(src, Base64::BYTEORDER_BIGENDIAN, res); TEST_EQUAL(res.size(), 0) // corrupted data src = "whoPutMeHere:somecrazyperson,obviously!WhatifIcontaininvalidcharacterslikethese"; TEST_EXCEPTION(Exception::ConversionError, b64.decode(src, Base64::BYTEORDER_BIGENDIAN, res) ); // TODO : some error checking and handling // currently there is no "safe" Base64 decoding that checks that all // characters are actually valid and the string is actually encoding to // floats. // // src = "Q A..A=="; // spaces and dots are not allowed // b64.decode(src, Base64::BYTEORDER_BIGENDIAN, res); // TEST_EQUAL(res.size(), 0) } END_SECTION START_SECTION([EXTRA] zlib functionality) { TOLERANCE_ABSOLUTE(0.001) Base64 b64; String str,src; std::vector<float> data, res; std::vector<double> data_double, res_double; // double data - big endian data_double.push_back(300.15); data_double.push_back(15.124); data_double.push_back(304.2); b64.encode(data_double,Base64::BYTEORDER_BIGENDIAN,str,true); b64.decode(str,Base64::BYTEORDER_BIGENDIAN, res_double,true); TEST_REAL_SIMILAR(res_double[0],300.15); TEST_REAL_SIMILAR(res_double[1],15.124); TEST_REAL_SIMILAR(res_double[2],304.2); data.clear(); data.push_back(120.0f); data.push_back(100.0f); b64.encode(data,Base64::BYTEORDER_BIGENDIAN,str,true); b64.decode(str,Base64::BYTEORDER_BIGENDIAN,res,true); TEST_REAL_SIMILAR(res[0], 120) TEST_REAL_SIMILAR(res[1], 100) // float data -big endian data.clear(); data.push_back(471.568f); data.push_back(80363.0f); data.push_back(474.439f); data.push_back(123815.0f); data.push_back(475.715f); data.push_back(33733.0f); b64.encode(data,Base64::BYTEORDER_BIGENDIAN,str,true); b64.decode(str,Base64::BYTEORDER_BIGENDIAN, res,true); TEST_REAL_SIMILAR(res[0], 471.568) TEST_REAL_SIMILAR(res[1], 80363) TEST_REAL_SIMILAR(res[2], 474.439) TEST_REAL_SIMILAR(res[3], 123815) TEST_REAL_SIMILAR(res[4], 475.715) TEST_REAL_SIMILAR(res[5], 33733) // double data - little endian data.clear(); data.push_back(300.15f); data.push_back(303.998f); data.push_back(304.61f); b64.encode(data,Base64::BYTEORDER_BIGENDIAN,str,true); b64.decode(str,Base64::BYTEORDER_BIGENDIAN, res,true); TEST_REAL_SIMILAR(res[0], 300.151) TEST_REAL_SIMILAR(res[1], 303.9981) TEST_REAL_SIMILAR(res[2], 304.61) src = "JhOWQ8b/l0PMTJhD"; b64.decode(src, Base64::BYTEORDER_LITTLEENDIAN, res); b64.encode(res,Base64::BYTEORDER_LITTLEENDIAN,str,true); b64.decode(str,Base64::BYTEORDER_LITTLEENDIAN,data,true); TEST_REAL_SIMILAR(data[0], 300.15f) TEST_REAL_SIMILAR(data[1], 303.998f) TEST_REAL_SIMILAR(data[2], 304.6f) } END_SECTION START_SECTION(( void encodeStrings(const std::vector<String> & in, String & out, bool zlib_compression = false, bool append_zero_byte = true))) { Base64 b64; String src,str; //without zlib compression src="ZGFzAGlzdABlaW4AdGVzdAAxMjM0"; vector<String> strings; b64.decodeStrings(src,strings,false); TEST_EQUAL(strings.size() == 5,true ) TEST_EQUAL(strings[0],"das") TEST_EQUAL(strings[1],"ist") TEST_EQUAL(strings[2],"ein") TEST_EQUAL(strings[3],"test") TEST_EQUAL(strings[4],"1234") //same as above but this time the whole String is null-terminated as well src="ZGFzAGlzdABlaW4AdGVzdAAxMjM0AA=="; b64.decodeStrings(src,strings,false); TEST_EQUAL(strings.size() == 5,true ) TEST_EQUAL(strings[0],"das") TEST_EQUAL(strings[1],"ist") TEST_EQUAL(strings[2],"ein") TEST_EQUAL(strings[3],"test") TEST_EQUAL(strings[4],"1234") //zlib compressed src = "eJxLSSxmyCwuYUjNzGMoSQUyDI2MTRgAUX4GTw=="; b64.decodeStrings(src,strings,true); TEST_EQUAL(strings.size() == 5,true ) TEST_EQUAL(strings[0],"das") TEST_EQUAL(strings[1],"ist") TEST_EQUAL(strings[2],"ein") TEST_EQUAL(strings[3],"test") TEST_EQUAL(strings[4],"1234") //without zlib compression b64.encodeStrings(strings,str,false); b64.decodeStrings(str,strings,false); TEST_EQUAL(strings.size() == 5,true ) TEST_EQUAL(strings[0],"das") TEST_EQUAL(strings[1],"ist") TEST_EQUAL(strings[2],"ein") TEST_EQUAL(strings[3],"test") TEST_EQUAL(strings[4],"1234") // test some corrupted strings src = "=="; b64.decodeStrings(src, strings, false); TEST_EQUAL(strings.size(), 0) src = "Q=="; b64.decodeStrings(src, strings, false); TEST_EQUAL(strings.size(), 0) src = "===="; b64.decodeStrings(src, strings, false); TEST_EQUAL(strings.size(), 0) src = "Q A..A=="; // spaces and dots are not allowed b64.decodeStrings(src, strings, false); // TODO : some error checking and handling // TEST_EQUAL(strings.size(), 0) } END_SECTION START_SECTION((void decodeStrings(const String& in, std::vector<String>& out, bool zlib_compression = false))) //this functionality is tested in the encodeString test NOT_TESTABLE END_SECTION START_SECTION((void decodeSingleString(const String & in, QByteArray & base64_uncompressed, bool zlib_compression))) //this functionality is tested in the decodeStrings test NOT_TESTABLE END_SECTION START_SECTION((template < typename ToType > void decodeIntegers(const String &in, ByteOrder from_byte_order, std::vector< ToType > &out, bool zlib_compression=false))) { Base64 b64; String src,str; vector<Int32> res; vector<Int64> double_res; //with zlib compression src="eJwNw4c2QgEAANAniezMIrKyUrKyMooIIdki4/8/wr3n3CAIgjZDthu2w4iddhm12x577bPfAQeNOeSwI4465rhxE044adIpp00546xzzrtg2kWXXHbFVTOumTXnunk33HTLbXcsuOue+x54aNEjjz3x1JJlzzy34oWXVr3y2htr3nrnvXUfbPjok8+++Oqb737Y9NMvW377469//gPgoxL0"; b64.decodeIntegers(src, Base64::BYTEORDER_LITTLEENDIAN,res,true); for(Size i = 0 ; i < res.size();++i) { TEST_EQUAL(res[i], i) } src="eJwtxdciAgAAAMDMZBWyiUrZLdlkZJRC9l79/0f04O7lAoF/bW53hzvd5W4H3eOQe93nfg940GFHPORhjzjqUY953BOe9JSnPeNZxzznecedcNILTjntRS952Ste9ZrXnXHWOedd8IaL3vSWt73jXe953wc+dMlHPvaJT132mc994UtXXPWVa6772je+dcN3vveDH/3kZ7/41W9+94c//eVv//jXf266BcFVEvQ="; b64.decodeIntegers(src,Base64::BYTEORDER_LITTLEENDIAN,double_res,true); for(Size i = 0 ; i < double_res.size();++i) { TEST_EQUAL(double_res[i], i) } src="eJxjZGBgYAJiZiAGAAA0AAc="; b64.decodeIntegers(src,Base64::BYTEORDER_BIGENDIAN,res,true); TEST_EQUAL(res[0],16777216) TEST_EQUAL(res[1],33554432) TEST_EQUAL(res[2],50331648) //without zlib compression 32bit src = "AAAAAQAAAAUAAAAGAAAABwAAAAgAAAAJAAACCg=="; b64.decodeIntegers(src, Base64::BYTEORDER_BIGENDIAN,res,false); TEST_EQUAL(res[0],1) TEST_EQUAL(res[1],5) TEST_EQUAL(res[2],6) TEST_EQUAL(res[3],7) TEST_EQUAL(res[4],8) TEST_EQUAL(res[5],9) TEST_EQUAL(res[6],522) //64bit src = "AAAAAAAAAAUAAAAAAAAAAwAAAAAAAAAJ"; b64.decodeIntegers(src, Base64::BYTEORDER_BIGENDIAN,double_res,false); TEST_EQUAL(double_res[0],5) TEST_EQUAL(double_res[1],3) TEST_EQUAL(double_res[2],9) //64bit src = "BQAAAAAAAAADAAAAAAAAAAkAAAAAAAAA"; b64.decodeIntegers(src, Base64::BYTEORDER_LITTLEENDIAN,double_res,false); TEST_EQUAL(double_res[0],5) TEST_EQUAL(double_res[1],3) TEST_EQUAL(double_res[2],9) //32bit src ="AQAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgIAAA=="; b64.decodeIntegers(src, Base64::BYTEORDER_LITTLEENDIAN,res,false); TEST_EQUAL(res[0],1) TEST_EQUAL(res[1],5) TEST_EQUAL(res[2],6) TEST_EQUAL(res[3],7) TEST_EQUAL(res[4],8) TEST_EQUAL(res[5],9) TEST_EQUAL(res[6],522) // test some corrupted strings src = "=="; b64.decodeIntegers(src, Base64::BYTEORDER_BIGENDIAN,res,false); TEST_EQUAL(res.size(), 0) src = "Q=="; b64.decodeIntegers(src, Base64::BYTEORDER_BIGENDIAN,res,false); TEST_EQUAL(res.size(), 0) src = "===="; b64.decodeIntegers(src, Base64::BYTEORDER_BIGENDIAN,res,false); TEST_EQUAL(res.size(), 0) // src = "Q A..A=="; // spaces and dots are not allowed // b64.decodeIntegers(src, Base64::BYTEORDER_BIGENDIAN,res,false); // TODO : some error checking and handling // TEST_EQUAL(res.size(), 0) } END_SECTION START_SECTION((template <typename FromType> void encodeIntegers(std::vector<FromType>& in, ByteOrder to_byte_order, String& out, bool zlib_compression=false))) { Base64 b64; String tmp; //64 bit tests vector<Int64> vec64, vec64_in, vec64_out; vec64.push_back(0); vec64.push_back(1); vec64.push_back(2); vec64.push_back(3); vec64.push_back(4); vec64.push_back(5); //test with little endian and without compression tmp=""; vec64_in = vec64; vec64_out.clear(); b64.encodeIntegers(vec64_in, Base64::BYTEORDER_LITTLEENDIAN, tmp, false); b64.decodeIntegers(tmp, Base64::BYTEORDER_LITTLEENDIAN, vec64_out, false); TEST_EQUAL(vec64.size(),vec64_out.size()) for (Size i=0; i<vec64.size(); ++i) { TEST_EQUAL(vec64[i],vec64_out[i]) } //test with big endian and compression vec64.push_back(999999); tmp = ""; vec64_in = vec64; vec64_out.clear(); b64.encodeIntegers(vec64_in, Base64::BYTEORDER_BIGENDIAN, tmp, true); b64.decodeIntegers(tmp, Base64::BYTEORDER_BIGENDIAN, vec64_out, true); TEST_EQUAL(vec64.size(),vec64_out.size()) for (Size i=0; i<vec64.size(); ++i) { TEST_EQUAL(vec64[i],vec64_out[i]) } //32 bit tests vector<Int32> vec32, vec32_in, vec32_out; vec32.push_back(0); vec32.push_back(5); vec32.push_back(10); vec32.push_back(15); vec32.push_back(20); vec32.push_back(25); //test with little endian and without compression tmp = ""; vec32_in = vec32; vec32_out.clear(); b64.encodeIntegers(vec32_in, Base64::BYTEORDER_LITTLEENDIAN, tmp, false); b64.decodeIntegers(tmp, Base64::BYTEORDER_LITTLEENDIAN, vec32_out, false); TEST_EQUAL(vec32.size(),vec32_out.size()) for (Size i=0; i<vec32.size(); ++i) { TEST_EQUAL(vec32[i],vec32_out[i]) } //test with big endian and compression vec32.push_back(999999); tmp = ""; vec32_in = vec32; vec32_out.clear(); b64.encodeIntegers(vec32_in, Base64::BYTEORDER_BIGENDIAN, tmp, true); b64.decodeIntegers(tmp, Base64::BYTEORDER_BIGENDIAN, vec32_out, true); TEST_EQUAL(vec32.size(),vec32_out.size()) for (Size i=0; i<vec32.size(); ++i) { TEST_EQUAL(vec32[i],vec32_out[i]) } } END_SECTION ptr = new Base64; START_SECTION(inline UInt32 endianize32(const UInt32& n)) TEST_EQUAL(0, endianize32(0)) // swapping 0 should do nothing TEST_EQUAL(std::numeric_limits<UInt32>::max(), endianize32(std::numeric_limits<UInt32>::max())) // swapping MAX should do nothing TEST_EQUAL(0x000000FF, endianize32(0xFF000000)) TEST_EQUAL(0x0000FF00, endianize32(0x00FF0000)) TEST_EQUAL(0x00FF0000, endianize32(0x0000FF00)) TEST_EQUAL(0xFF000000, endianize32(0x000000FF)) // random value should stay the same upon double call UInt32 r = (UInt32)UniqueIdGenerator::getUniqueId(); TEST_EQUAL(r, endianize32(endianize32(r))) END_SECTION START_SECTION(inline UInt64 endianize64(const UInt64& n)) TEST_EQUAL(0, endianize64(0)) // swapping 0 should do nothing TEST_EQUAL(std::numeric_limits<UInt64>::max(), endianize64(std::numeric_limits<UInt64>::max())) // swapping MAX should do nothing TEST_EQUAL(0x00000000000000FF, endianize64(0xFF00000000000000)) TEST_EQUAL(0x000000000000FF00, endianize64(0x00FF000000000000)) TEST_EQUAL(0x0000000000FF0000, endianize64(0x0000FF0000000000)) TEST_EQUAL(0x00000000FF000000, endianize64(0x000000FF00000000)) TEST_EQUAL(0x000000FF00000000, endianize64(0x00000000FF000000)) TEST_EQUAL(0x0000FF0000000000, endianize64(0x0000000000FF0000)) TEST_EQUAL(0x00FF000000000000, endianize64(0x000000000000FF00)) TEST_EQUAL(0xFF00000000000000, endianize64(0x00000000000000FF)) // random value should stay the same upon double call UInt64 r = UniqueIdGenerator::getUniqueId(); TEST_EQUAL(r, endianize64(endianize64(r))) END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ListUtils_test.cpp
.cpp
6,488
209
// 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/ListUtils.h> using namespace OpenMS; using namespace std; START_TEST(ListUtils, "$Id$") START_SECTION((template < typename T, typename E > static bool contains(const std::vector< T > &container, const E &elem))) { // Int std::vector<Int> iv; iv.push_back(1); iv.push_back(2); iv.push_back(3); iv.push_back(4); TEST_EQUAL(ListUtils::contains(iv, 1),true) TEST_EQUAL(ListUtils::contains(iv, 2),true) TEST_EQUAL(ListUtils::contains(iv, 3),true) TEST_EQUAL(ListUtils::contains(iv, 4),true) TEST_EQUAL(ListUtils::contains(iv, 5),false) TEST_EQUAL(ListUtils::contains(iv, 1011),false) // String std::vector<String> sv; sv.push_back("yes"); sv.push_back("no"); TEST_EQUAL(ListUtils::contains(sv, "yes"),true) TEST_EQUAL(ListUtils::contains(sv, "no"),true) TEST_EQUAL(ListUtils::contains(sv, "jup"),false) TEST_EQUAL(ListUtils::contains(sv, ""),false) TEST_EQUAL(ListUtils::contains(sv, "noe"),false) } END_SECTION START_SECTION((static bool contains(const std::vector< double > &container, const double &elem, double tolerance=0.00001))) { // std::vector<double> dv; dv.push_back(1.2); dv.push_back(3.4); TEST_EQUAL(ListUtils::contains(dv, 1.2),true) TEST_EQUAL(ListUtils::contains(dv, 1.21),false) TEST_EQUAL(ListUtils::contains(dv, 1.19),false) TEST_EQUAL(ListUtils::contains(dv, 1.21,0.02),true) TEST_EQUAL(ListUtils::contains(dv, 1.19,0.02),true) TEST_EQUAL(ListUtils::contains(dv, 3.4),true) TEST_EQUAL(ListUtils::contains(dv, 4.2),false) TEST_EQUAL(ListUtils::contains(dv, 2.0),false) TEST_EQUAL(ListUtils::contains(dv, 0.0),false) } END_SECTION START_SECTION((template < typename T > static std::vector<T> create(const std::vector< String > &s))) { std::vector<String> iv; iv.push_back("1.2"); iv.push_back("1.56"); iv.push_back("10.4"); std::vector<String> sv = ListUtils::create<String>(iv); TEST_EQUAL(sv.size(), 3) ABORT_IF(sv.size() != 3) TEST_EQUAL(sv[0], iv[0]) TEST_EQUAL(sv[1], iv[1]) TEST_EQUAL(sv[2], iv[2]) // create double vector std::vector<double> dv = ListUtils::create<double>(iv); TEST_EQUAL(dv.size(), 3) ABORT_IF(dv.size() != 3) TEST_EQUAL(dv[0], 1.2) TEST_EQUAL(dv[1], 1.56) TEST_EQUAL(dv[2], 10.4) iv.push_back("a"); std::vector<String> sv2 = ListUtils::create<String>(iv); TEST_EQUAL(sv2.size(), 4) ABORT_IF(sv2.size() != 4) TEST_EQUAL(sv2[3], iv[3]) TEST_EXCEPTION(Exception::ConversionError, ListUtils::create<double>(iv)) } END_SECTION START_SECTION((template < typename T > static std::vector<T> create(const String &str, const char splitter= ','))) { std::vector<String> sv = ListUtils::create<String>("yes,no, maybe"); TEST_EQUAL(sv.size(), 3) ABORT_IF(sv.size() != 3) TEST_EQUAL(sv[0], "yes") TEST_EQUAL(sv[1], "no") TEST_EQUAL(sv[2], " maybe") std::vector<double> dv = ListUtils::create<double>("1.2,3.5"); TEST_EQUAL(dv.size(), 2) ABORT_IF(dv.size() != 2) TEST_EQUAL(dv[0], 1.2) TEST_EQUAL(dv[1], 3.5) std::vector<Int> iv = ListUtils::create<Int>("1,5"); TEST_EQUAL(iv.size(),2) ABORT_IF(iv.size() != 2) TEST_EQUAL(iv[0], 1) TEST_EQUAL(iv[1], 5) IntList iv2 = ListUtils::create<Int>("2"); TEST_EQUAL(iv2.size(),1) TEST_EQUAL(iv2[0],2) IntList iv3 = ListUtils::create<Int>(""); TEST_EQUAL(iv3.size(),0) StringList sl1 = ListUtils::create<String>("test string,string2,last string"); TEST_EQUAL(sl1.size(),3) ABORT_IF(sl1.size() != 3) TEST_EQUAL(sl1[0], "test string") TEST_EQUAL(sl1[1], "string2") TEST_EQUAL(sl1[2], "last string") StringList list = ListUtils::create<String>("yes,no"); TEST_EQUAL(list.size(),2) ABORT_IF(list.size() != 2) TEST_STRING_EQUAL(list[0],"yes") TEST_STRING_EQUAL(list[1],"no") StringList list2 = ListUtils::create<String>("no"); TEST_EQUAL(list2.size(),1) ABORT_IF(list2.size() != 1) TEST_STRING_EQUAL(list2[0],"no") StringList list3 = ListUtils::create<String>(""); TEST_EQUAL(list3.size(),0) StringList sl4 = ListUtils::create<String>("test string#string2#last string", '#'); TEST_EQUAL(sl4.size(),3) ABORT_IF(sl4.size() != 3) TEST_EQUAL(sl4[0], "test string") TEST_EQUAL(sl4[1], "string2") TEST_EQUAL(sl4[2], "last string") } END_SECTION START_SECTION((template < typename T > static String concatenate(const std::vector< T > &container, const String &glue=""))) { std::vector<String> list; list.push_back("1"); list.push_back("2"); list.push_back("3"); list.push_back("4"); list.push_back("5"); TEST_STRING_EQUAL(ListUtils::concatenate(list, "g"),"1g2g3g4g5"); TEST_STRING_EQUAL(ListUtils::concatenate(list, ""),"12345"); list.clear(); TEST_STRING_EQUAL(ListUtils::concatenate(list, "g"),""); TEST_STRING_EQUAL(ListUtils::concatenate(list, ""),""); //test2 (from StringList) std::vector<String> tmp; TEST_EQUAL(ListUtils::concatenate(tmp),"") tmp.push_back("1\n"); tmp.push_back("2\n"); tmp.push_back("3\n"); TEST_EQUAL(ListUtils::concatenate(tmp),"1\n2\n3\n") } END_SECTION START_SECTION((template <typename T> static Int getIndex(const std::vector<T>& container, const E& elem))) { IntList ints; ints.push_back(4); ints.push_back(3); ints.push_back(1); ints.push_back(2); TEST_EQUAL(ListUtils::getIndex<Int>(ints, 0), -1); TEST_EQUAL(ListUtils::getIndex<Int>(ints, 1), 2); TEST_EQUAL(ListUtils::getIndex<Int>(ints, 2), 3); TEST_EQUAL(ListUtils::getIndex<Int>(ints, 3), 1); TEST_EQUAL(ListUtils::getIndex<Int>(ints, 4), 0); TEST_EQUAL(ListUtils::getIndex<Int>(ints, 5), -1); StringList strings; strings.push_back("four"); strings.push_back("three"); strings.push_back("one"); strings.push_back("two"); TEST_EQUAL(ListUtils::getIndex<String>(strings, "zero"), -1); TEST_EQUAL(ListUtils::getIndex<String>(strings, "one"), 2); TEST_EQUAL(ListUtils::getIndex<String>(strings, "two"), 3); TEST_EQUAL(ListUtils::getIndex<String>(strings, "three"), 1); TEST_EQUAL(ListUtils::getIndex<String>(strings, "four"), 0); TEST_EQUAL(ListUtils::getIndex<String>(strings, "five"), -1); } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MSDataChainingConsumer_test.cpp
.cpp
8,095
244
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/DATAACCESS/MSDataChainingConsumer.h> #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/FORMAT/DATAACCESS/NoopMSDataConsumer.h> #include <OpenMS/FORMAT/DATAACCESS/MSDataTransformingConsumer.h> /////////////////////////// #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/MzMLFile.h> START_TEST(MSDataChainingConsumer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; MSDataChainingConsumer* chaining_consumer_ptr = nullptr; MSDataChainingConsumer* chaining_consumer_nullPointer = nullptr; START_SECTION((MSDataChainingConsumer())) chaining_consumer_ptr = new MSDataChainingConsumer(); TEST_NOT_EQUAL(chaining_consumer_ptr, chaining_consumer_nullPointer) END_SECTION START_SECTION((~MSDataChainingConsumer())) delete chaining_consumer_ptr; END_SECTION START_SECTION(( MSDataChainingConsumer(std::vector<IMSDataConsumer*> consumers) )) std::vector<Interfaces::IMSDataConsumer *> consumer_list; chaining_consumer_ptr = new MSDataChainingConsumer(consumer_list); TEST_NOT_EQUAL(chaining_consumer_ptr, chaining_consumer_nullPointer) delete chaining_consumer_ptr; END_SECTION START_SECTION((void consumeSpectrum(SpectrumType & s))) { std::vector<Interfaces::IMSDataConsumer *> consumer_list; consumer_list.push_back(new NoopMSDataConsumer()); consumer_list.push_back(new NoopMSDataConsumer()); consumer_list.push_back(new NoopMSDataConsumer()); MSDataChainingConsumer * chaining_consumer = new MSDataChainingConsumer(consumer_list); PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) MSSpectrum first_spectrum = exp.getSpectrum(0); chaining_consumer->setExpectedSize(2,0); chaining_consumer->consumeSpectrum(exp.getSpectrum(0)); TEST_EQUAL(first_spectrum == exp.getSpectrum(0), true) // nothing happened for (auto& consumer : consumer_list) { delete consumer; } delete chaining_consumer; } END_SECTION START_SECTION(([EXTRA] void consumeSpectrum(SpectrumType & s))) { auto f = [](OpenMS::MSSpectrum & s) { s.sortByIntensity(); }; MSDataTransformingConsumer * transforming_consumer = new MSDataTransformingConsumer(); transforming_consumer->setExpectedSize(2,0); transforming_consumer->setSpectraProcessingFunc(f); std::vector<Interfaces::IMSDataConsumer *> consumer_list; consumer_list.push_back(new NoopMSDataConsumer()); consumer_list.push_back(transforming_consumer); consumer_list.push_back(new NoopMSDataConsumer()); MSDataChainingConsumer * chaining_consumer = new MSDataChainingConsumer(consumer_list); PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) MSSpectrum first_spectrum = exp.getSpectrum(0); chaining_consumer->setExpectedSize(2,0); chaining_consumer->consumeSpectrum(exp.getSpectrum(0)); TEST_EQUAL(first_spectrum == exp.getSpectrum(0), false) // something happened TEST_EQUAL(first_spectrum.isSorted(), true) TEST_EQUAL(exp.getSpectrum(0).isSorted(), false) // note how the transforming consumer still works as deleting the chaining // consumer does not take ownership of the consumers transforming_consumer->consumeSpectrum(exp.getSpectrum(0) ); TEST_EQUAL(first_spectrum.isSorted(), true) TEST_EQUAL(exp.getSpectrum(0).isSorted(), false) for (auto& consumer : consumer_list) { delete consumer; } delete chaining_consumer; } END_SECTION START_SECTION((void consumeChromatogram(ChromatogramType & c))) { std::vector<Interfaces::IMSDataConsumer *> consumer_list; consumer_list.push_back(new NoopMSDataConsumer()); consumer_list.push_back(new NoopMSDataConsumer()); consumer_list.push_back(new NoopMSDataConsumer()); MSDataChainingConsumer * chaining_consumer = new MSDataChainingConsumer(consumer_list); PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrChromatograms() > 0, true) MSChromatogram first_chromatogram = exp.getChromatogram(0); chaining_consumer->setExpectedSize(0,1); chaining_consumer->consumeChromatogram(exp.getChromatogram(0)); TEST_EQUAL(first_chromatogram == exp.getChromatogram(0), true) // nothing happened for (auto& consumer : consumer_list) { delete consumer; } delete chaining_consumer; } END_SECTION START_SECTION(([EXTRA]void consumeChromatogram(ChromatogramType & c))) { auto f2 = [](OpenMS::MSChromatogram & c) { c.sortByIntensity(); }; MSDataTransformingConsumer * transforming_consumer = new MSDataTransformingConsumer(); transforming_consumer->setExpectedSize(2,0); transforming_consumer->setChromatogramProcessingFunc(f2); std::vector<Interfaces::IMSDataConsumer *> consumer_list; consumer_list.push_back(new NoopMSDataConsumer()); consumer_list.push_back(transforming_consumer); consumer_list.push_back(new NoopMSDataConsumer()); MSDataChainingConsumer * chaining_consumer = new MSDataChainingConsumer(consumer_list); PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrChromatograms() > 0, true) MSChromatogram first_chromatogram = exp.getChromatogram(0); chaining_consumer->setExpectedSize(0,1); chaining_consumer->consumeChromatogram(exp.getChromatogram(0)); TEST_EQUAL(first_chromatogram == exp.getChromatogram(0), false) // something happened TEST_EQUAL(first_chromatogram.isSorted(), true) TEST_EQUAL(exp.getChromatogram(0).isSorted(), false) for (auto& consumer : consumer_list) { delete consumer; } delete chaining_consumer; } END_SECTION START_SECTION((void setExpectedSize(Size, Size))) NOT_TESTABLE // tested above END_SECTION START_SECTION((void setExperimentalSettings(const ExperimentalSettings&))) { MSDataChainingConsumer * chaining_consumer = new MSDataChainingConsumer(); chaining_consumer->setExpectedSize(2,0); ExperimentalSettings s; chaining_consumer->setExperimentalSettings( s ); TEST_NOT_EQUAL(chaining_consumer, chaining_consumer_nullPointer) delete chaining_consumer; } END_SECTION START_SECTION(( void appendConsumer(IMSDataConsumer * consumer) )) { MSDataTransformingConsumer * transforming_consumer = new MSDataTransformingConsumer(); auto f = [](OpenMS::MSSpectrum & s) { s.sortByIntensity(); }; transforming_consumer->setExpectedSize(2,0); transforming_consumer->setSpectraProcessingFunc(f); std::vector<Interfaces::IMSDataConsumer *> consumer_list; consumer_list.push_back(new NoopMSDataConsumer()); consumer_list.push_back(new NoopMSDataConsumer()); MSDataChainingConsumer * chaining_consumer = new MSDataChainingConsumer(consumer_list); chaining_consumer->appendConsumer(transforming_consumer); PeakMap exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); TEST_EQUAL(exp.getNrSpectra() > 0, true) MSSpectrum first_spectrum = exp.getSpectrum(0); chaining_consumer->setExpectedSize(2,0); chaining_consumer->consumeSpectrum(exp.getSpectrum(0)); TEST_EQUAL(first_spectrum == exp.getSpectrum(0), false) // something happened TEST_EQUAL(first_spectrum.isSorted(), true) TEST_EQUAL(exp.getSpectrum(0).isSorted(), false) for (auto& consumer : consumer_list) { delete consumer; } delete transforming_consumer; delete chaining_consumer; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MassExplainer_test.cpp
.cpp
3,492
142
// 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/MassExplainer.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/Compomer.h> using namespace OpenMS; using namespace std; START_TEST(MassExplainer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MassExplainer* ptr = nullptr; MassExplainer* nullPointer = nullptr; START_SECTION(MassExplainer()) { ptr = new MassExplainer(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~MassExplainer()) { delete ptr; } END_SECTION START_SECTION((MassExplainer(AdductsType adduct_base))) { Adduct a(2, 1, 123.12, "Na", -0.5,0); MassExplainer::AdductsType va; va.push_back(a); MassExplainer me(va); TEST_EQUAL(me.getAdductBase().size(), 1); } END_SECTION START_SECTION((MassExplainer(Int q_min, Int q_max, Int max_span, double thresh_logp))) { MassExplainer me(5,10,2,-10.3); TEST_EQUAL(me.getAdductBase().size(), 4); } END_SECTION START_SECTION((MassExplainer(AdductsType adduct_base, Int q_min, Int q_max, Int max_span, double thresh_logp, Size max_neutrals))) { MassExplainer::AdductsType va; Adduct a1(2, 1, 123.12, "Na", -0.5,0); Adduct a2(3, 1, 123.12, "K", -0.7,0); va.push_back(a1); va.push_back(a2); MassExplainer me(va,5,10,2,-10.3,0); TEST_EQUAL(me.getAdductBase().size(), 2); } END_SECTION START_SECTION((MassExplainer& operator=(const MassExplainer &rhs))) { MassExplainer::AdductsType va; Adduct a1(2, 1, 123.12, "Na", -0.5,0); Adduct a2(3, 1, 123.12, "K", -0.7,0); va.push_back(a1); va.push_back(a2); MassExplainer me(va,5,10,2,-10.3,0); MassExplainer me2; me2 = me; TEST_EQUAL(me.getAdductBase().size(), 2); } END_SECTION START_SECTION((void setAdductBase(AdductsType adduct_base))) { MassExplainer::AdductsType va; Adduct a1(2, 1, 123.12, "Na", -0.5,0); Adduct a2(3, 1, 123.12, "K", -0.7,0); va.push_back(a1); va.push_back(a2); MassExplainer me; me.setAdductBase(va); TEST_EQUAL(me.getAdductBase().size(),2); } END_SECTION START_SECTION((AdductsType getAdductBase() const)) { NOT_TESTABLE; // tested above } END_SECTION START_SECTION((const Compomer& getCompomerById(Size id) const)) { MassExplainer me; me.compute(); TEST_EQUAL(me.getCompomerById(0).getID(), 0) } END_SECTION START_SECTION((void compute())) { NOT_TESTABLE; // tested above } END_SECTION START_SECTION((SignedSize query(const Int net_charge, const float mass_to_explain, const float mass_delta, const float thresh_log_p, std::vector< Compomer >::const_iterator &firstExplanation, std::vector< Compomer >::const_iterator &lastExplanation) const)) { MassExplainer me; me.compute(); MassExplainer::CompomerIterator s,e; SignedSize hits = me.query(2, 45.0, 13.0, -100000,s,e); std::cout << "hits: " << hits << std::endl; for (; s!=e; ++s) { std::cout << *s << std::endl; } TEST_EQUAL(hits, 5); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FeatureHandle_test.cpp
.cpp
5,080
204
// 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/FeatureHandle.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/KERNEL/ConsensusFeature.h> /////////////////////////// using namespace OpenMS; using namespace std; typedef FeatureMap ContainerType; typedef ContainerType::value_type ElementType; typedef Feature::PositionType PositionType; START_TEST(FeatureHandle, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FeatureHandle* ptr = nullptr; FeatureHandle* nullPointer = nullptr; START_SECTION((FeatureHandle())) ptr = new FeatureHandle(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~FeatureHandle())) delete ptr; END_SECTION START_SECTION((FeatureHandle& operator=(const FeatureHandle &rhs))) ElementType e; e.setUniqueId(2); FeatureHandle it(1,e); FeatureHandle it_copy; it_copy = it; TEST_EQUAL(it.getUniqueId() == it_copy.getUniqueId(), true) TEST_EQUAL(it.getMapIndex() == it_copy.getMapIndex(), true) TEST_EQUAL(it.getIntensity() == it_copy.getIntensity(), true) TEST_EQUAL(it.getPosition() == it_copy.getPosition(), true) END_SECTION START_SECTION((FeatureHandle(const FeatureHandle &rhs))) ElementType e; e.setUniqueId(2); FeatureHandle it(1,e); FeatureHandle it_copy(it); TEST_EQUAL(it.getUniqueId() == it_copy.getUniqueId(), true) TEST_EQUAL(it.getMapIndex() == it_copy.getMapIndex(), true) TEST_EQUAL(it.getIntensity() == it_copy.getIntensity(), true) TEST_EQUAL(it.getPosition() == it_copy.getPosition(), true) END_SECTION START_SECTION((void setCharge(ChargeType charge))) { FeatureHandle fh; fh.setCharge(-17); TEST_EQUAL(fh.getCharge(),-17); fh.setCharge(-1717); TEST_EQUAL(fh.getCharge(),-1717); } END_SECTION START_SECTION((ChargeType getCharge() const)) { NOT_TESTABLE; // see setCharge() } END_SECTION START_SECTION((void setWidth(WidthType width))) { FeatureHandle fh_tmp; fh_tmp.setWidth(10.7); TEST_REAL_SIMILAR(fh_tmp.getWidth(), 10.7); fh_tmp.setWidth(-8.9); TEST_REAL_SIMILAR(fh_tmp.getWidth(), -8.9); } END_SECTION START_SECTION((WidthType getWidth() const )) { NOT_TESTABLE; } END_SECTION START_SECTION((FeatureHandle(UInt64 map_index, const Peak2D &point, UInt64 element_index))) ElementType e; FeatureHandle it(1,e,2); TEST_EQUAL(it.getUniqueId() == 2, true) TEST_EQUAL(it.getMapIndex() == 1, true) TEST_EQUAL(it.getPosition() == e.getPosition(), true) END_SECTION START_SECTION((FeatureHandle(UInt64 map_index, const BaseFeature& feature))) Feature f; f.setCharge(-17); f.setRT(44324.6); f.setMZ(867.4); f.setUniqueId(23); const Feature& f_cref = f; FeatureHandle fh(99,f_cref); TEST_EQUAL(fh.getMapIndex(),99); TEST_EQUAL(fh.getUniqueId(),23); TEST_EQUAL(fh.getRT(),44324.6); TEST_EQUAL(fh.getMZ(),867.4); TEST_EQUAL(fh.getCharge(),-17); END_SECTION START_SECTION((FeatureHandleMutable_ & asMutable() const)) ConsensusFeature f; f.setCharge(-17); f.setRT(44324.6); f.setMZ(867.4); f.setUniqueId(23); const ConsensusFeature& f_cref = f; FeatureHandle fh(99, f_cref); const FeatureHandle& fh_cref = fh; // fh_cref.setRT(-64544.3); // compile time error fh_cref.asMutable().setRT(-64544.3); // ok TEST_EQUAL(fh.getMapIndex(),99); TEST_EQUAL(fh.getUniqueId(),23); TEST_EQUAL(fh.getRT(),-64544.3); TEST_EQUAL(fh.getMZ(),867.4); TEST_EQUAL(fh.getCharge(),-17); END_SECTION START_SECTION((bool operator!=(const FeatureHandle &i) const)) ElementType e; e.setUniqueId(2); FeatureHandle it1(1,e); FeatureHandle it2(2,e); TEST_FALSE(it1 == it2) END_SECTION START_SECTION((bool operator==(const FeatureHandle &i) const)) ElementType e; e.setUniqueId(2); FeatureHandle it1(2,e); FeatureHandle it2(2,e); TEST_TRUE(it1 == it2) END_SECTION START_SECTION((UInt64 getMapIndex() const)) ElementType e; e.setUniqueId(2); FeatureHandle it(1,e); TEST_EQUAL(it.getMapIndex() == 1, true) END_SECTION START_SECTION((void setMapIndex(UInt64 i))) FeatureHandle it; it.setMapIndex(2); it.setUniqueId(77); TEST_EQUAL(it.getMapIndex() == 2, true) END_SECTION START_SECTION(([FeatureHandle::IndexLess] bool operator()(FeatureHandle const &left, FeatureHandle const &right) const)) FeatureHandle lhs, rhs; lhs.setMapIndex(2); lhs.setUniqueId(77); rhs.setMapIndex(4); lhs.setUniqueId(29); FeatureHandle::IndexLess il; TEST_EQUAL(il(lhs, rhs), 1); TEST_EQUAL(il(rhs, lhs), 0); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IdentificationDataConverter_test.cpp
.cpp
17,188
372
// 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 <functional> /////////////////////////// #include <OpenMS/METADATA/ID/IdentificationDataConverter.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/FORMAT/MzTabFile.h> #include <OpenMS/FORMAT/PepXMLFile.h> /////////////////////////// using namespace OpenMS; using namespace std; using namespace std::placeholders; struct ComparePIdSize { bool operator()(const ProteinIdentification& lhs, const ProteinIdentification& rhs) const { return lhs.getHits().size() < rhs.getHits().size(); } }; START_TEST(IdentificationDataConverter, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION((void importIDs(IdentificationData&, const vector<ProteinIdentification>&, const PeptideIdentificationList&))) { 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); IdentificationData ids; IdentificationDataConverter::importIDs(ids, proteins_in, peptides_in); vector<ProteinIdentification> proteins_out; PeptideIdentificationList peptides_out; IdentificationDataConverter::exportIDs(ids, proteins_out, peptides_out); TEST_EQUAL(peptides_in.size(), peptides_out.size()); vector<PeptideHit> hits_in, hits_out; for (const auto& pep : peptides_in) { hits_in.insert(hits_in.end(), pep.getHits().begin(), pep.getHits().end()); } for (const auto& pep : peptides_out) { hits_out.insert(hits_out.end(), pep.getHits().begin(), pep.getHits().end()); } TEST_EQUAL(hits_in.size(), hits_out.size()); // order of hits is different, check that every output one is in the input: for (const auto& hit : hits_out) { TEST_EQUAL(find(hits_in.begin(), hits_in.end(), hit) != hits_in.end(), true); } std::sort(proteins_in.begin(), proteins_in.end(), ComparePIdSize()); std::sort(proteins_out.begin(), proteins_out.end(), ComparePIdSize()); TEST_EQUAL(proteins_in.size(), proteins_out.size()); TEST_EQUAL(proteins_in[0].getHits().size(), 1) // is sorted TEST_EQUAL(proteins_in[1].getHits().size(), 2) // is sorted // the exporter adds target/decoy information (default: target): for (auto& hit : proteins_in[0].getHits()) hit.setMetaValue("target_decoy", "target"); for (auto& hit : proteins_in[1].getHits()) hit.setMetaValue("target_decoy", "target"); // TEST_EQUAL(proteins_in[0].getIdentifier(), proteins_out[0].getIdentifier() ) // identifiers are not equal // TEST_EQUAL(proteins_in[1].getIdentifier(), proteins_out[1].getIdentifier() ) // identifiers are not equal TEST_EQUAL(proteins_in[0].getHits().size(), proteins_out[0].getHits().size()); TEST_EQUAL(proteins_in[1].getHits().size(), proteins_out[1].getHits().size()); TEST_EQUAL(proteins_in[0].getHits() == proteins_out[0].getHits(), true); TEST_EQUAL(proteins_in[1].getHits() == proteins_out[1].getHits(), true); TEST_EQUAL(proteins_in[0].getDateTime().get(), proteins_out[0].getDateTime().get()); TEST_EQUAL(proteins_in[1].getDateTime().get(), proteins_out[1].getDateTime().get()); TEST_EQUAL(proteins_in[0].getSearchParameters() == proteins_out[0].getSearchParameters(), true); TEST_EQUAL(proteins_in[1].getSearchParameters() == proteins_out[1].getSearchParameters(), true); // if something breaks and the search parameters don't match, find where the difference is: /* for (Size i = 0; i <= 1; ++i) { TEST_EQUAL(static_cast<MetaInfoInterface>(proteins_in[i].getSearchParameters()) == static_cast<MetaInfoInterface>(proteins_out[i].getSearchParameters()), true); TEST_EQUAL(proteins_in[i].getSearchParameters().db, proteins_out[i].getSearchParameters().db); TEST_EQUAL(proteins_in[i].getSearchParameters().db_version, proteins_out[i].getSearchParameters().db_version); TEST_EQUAL(proteins_in[i].getSearchParameters().taxonomy, proteins_out[i].getSearchParameters().taxonomy); TEST_EQUAL(proteins_in[i].getSearchParameters().charges, proteins_out[i].getSearchParameters().charges); TEST_EQUAL(proteins_in[i].getSearchParameters().mass_type, proteins_out[i].getSearchParameters().mass_type); TEST_EQUAL(proteins_in[i].getSearchParameters().fixed_modifications == proteins_out[i].getSearchParameters().fixed_modifications, true); TEST_EQUAL(proteins_in[i].getSearchParameters().variable_modifications == proteins_out[i].getSearchParameters().variable_modifications, true); TEST_EQUAL(proteins_in[i].getSearchParameters().missed_cleavages, proteins_out[i].getSearchParameters().missed_cleavages); TEST_EQUAL(proteins_in[i].getSearchParameters().fragment_mass_tolerance, proteins_out[i].getSearchParameters().fragment_mass_tolerance); TEST_EQUAL(proteins_in[i].getSearchParameters().fragment_mass_tolerance_ppm, proteins_out[i].getSearchParameters().fragment_mass_tolerance_ppm); TEST_EQUAL(proteins_in[i].getSearchParameters().precursor_mass_tolerance, proteins_out[i].getSearchParameters().precursor_mass_tolerance); TEST_EQUAL(proteins_in[i].getSearchParameters().precursor_mass_tolerance_ppm, proteins_out[i].getSearchParameters().precursor_mass_tolerance_ppm); TEST_EQUAL(proteins_in[i].getSearchParameters().digestion_enzyme == proteins_out[i].getSearchParameters().digestion_enzyme, true); } */ // String filename = OPENMS_GET_TEST_DATA_PATH("IdentificationDataConverter_out.idXML"); // IdXMLFile().store(filename, proteins_out, peptides_out); } END_SECTION START_SECTION((void importSequences(IdentificationData&, const vector<FASTAFile::FASTAEntry>&, IdentificationData::MoleculeType, const String&))) { vector<FASTAFile::FASTAEntry> fasta; FASTAFile().load(OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta"), fasta); IdentificationData ids; IdentificationDataConverter::importSequences(ids, fasta); TEST_EQUAL(ids.getParentSequences().size(), 5); } END_SECTION START_SECTION((void exportIDs(const IdentificationData&, vector<ProteinIdentification>&, PeptideIdentificationList&))) { vector<ProteinIdentification> proteins_in; PeptideIdentificationList peptides_in; String filename = OPENMS_GET_TEST_DATA_PATH("../../../topp/THIRDPARTY/FidoAdapter_4_output.idXML"); //String filename = OPENMS_GET_TEST_DATA_PATH("debug_fraction_1_IDs_after_transfer.idXML"); IdXMLFile().load(filename, proteins_in, peptides_in); IdentificationData ids; IdentificationDataConverter::importIDs(ids, proteins_in, peptides_in); vector<ProteinIdentification> proteins_out; PeptideIdentificationList peptides_out; IdentificationDataConverter::exportIDs(ids, proteins_out, peptides_out); TEST_EQUAL(proteins_in.size(), proteins_out.size()); TEST_EQUAL(proteins_in[0].getHits().size(), proteins_out[0].getHits().size()); TEST_EQUAL(proteins_in[0].getHits() == proteins_out[0].getHits(), true); TEST_EQUAL(proteins_in[0].getIndistinguishableProteins() == proteins_out[0].getIndistinguishableProteins(), true); TEST_EQUAL(proteins_in[0].getProteinGroups() == proteins_out[0].getProteinGroups(), true); TEST_EQUAL(peptides_in.size(), peptides_out.size()); // no "operator<" for PeptideHit, otherwise we could use a set: vector<PeptideHit> hits_in, hits_out; for (const auto& pep : peptides_in) { hits_in.insert(hits_in.end(), pep.getHits().begin(), pep.getHits().end()); } for (const auto& pep : peptides_out) { hits_out.insert(hits_out.end(), pep.getHits().begin(), pep.getHits().end()); } for (auto& hit : hits_in) { // "target+decoy" is counted as "target" in IdentificationData: if (hit.getMetaValue("target_decoy") == "target+decoy") { hit.setMetaValue("target_decoy", "target"); } } TEST_EQUAL(hits_in.size(), hits_out.size()); // order of hits is different, check that every output one is in the input: TEST_EQUAL(all_of(hits_out.begin(), hits_out.end(), [&hits_in](const PeptideHit& hit) { return find(hits_in.begin(), hits_in.end(), hit) != hits_in.end(); }), true); // and the other way round! TEST_EQUAL(all_of(hits_in.begin(), hits_in.end(), [&hits_out](const PeptideHit& hit) { return find(hits_out.begin(), hits_out.end(), hit) != hits_out.end(); }), true); auto mzrtcomp = [](const PeptideIdentification& p1, const PeptideIdentification& p2) {return p1.getMZ() == p2.getMZ() && p1.getRT() == p2.getRT();}; TEST_EQUAL(peptides_in.size(), peptides_out.size()); // order of ids is different, check that every output one is in the input: TEST_EQUAL(all_of(peptides_out.begin(), peptides_out.end(), [&peptides_in, &mzrtcomp](const PeptideIdentification& hit) -> bool { return std::find_if(peptides_in.begin(), peptides_in.end(), std::bind(mzrtcomp, hit, std::placeholders::_1)) != peptides_in.end(); }), true); // and the other way round! TEST_EQUAL(all_of(peptides_in.begin(), peptides_in.end(), [&peptides_out, &mzrtcomp](const PeptideIdentification& hit) -> bool { return std::find_if(peptides_out.begin(), peptides_out.end(), std::bind(mzrtcomp, hit, std::placeholders::_1)) != peptides_out.end(); }), true); // filename = OPENMS_GET_TEST_DATA_PATH("IdentificationDataConverter_out2.idXML"); // IdXMLFile().store(filename, proteins_out, peptides_out); } END_SECTION START_SECTION((MzTab exportMzTab(const IdentificationData& id_data))) { vector<ProteinIdentification> proteins_in; PeptideIdentificationList peptides_in; String filename = OPENMS_GET_TEST_DATA_PATH("../../../topp/THIRDPARTY/FidoAdapter_4_output.idXML"); IdXMLFile().load(filename, proteins_in, peptides_in); IdentificationData ids; IdentificationDataConverter::importIDs(ids, proteins_in, peptides_in); MzTab mztab = IdentificationDataConverter::exportMzTab(ids); NEW_TMP_FILE(filename); MzTabFile().store(filename, mztab); TEST_FILE_SIMILAR(filename, OPENMS_GET_TEST_DATA_PATH("IdentificationDataConverter_out1.mzTab")); // RNA data, oligonucleotide that matches several times in the same RNA: IdentificationData rna_ids; IdentificationData::ParentSequence rna("test", IdentificationData::MoleculeType::RNA, "AUCGAUCG"); IdentificationData::ParentSequenceRef ref = rna_ids.registerParentSequence(rna); IdentificationData::IdentifiedOligo oli(NASequence::fromString("AUCG")); IdentificationData::ParentMatch match1(0, 3), match2(4, 7); oli.parent_matches[ref].insert(match1); oli.parent_matches[ref].insert(match2); rna_ids.registerIdentifiedOligo(oli); mztab = IdentificationDataConverter::exportMzTab(rna_ids); NEW_TMP_FILE(filename); MzTabFile().store(filename, mztab); TEST_FILE_SIMILAR(filename, OPENMS_GET_TEST_DATA_PATH("IdentificationDataConverter_out2.mzTab")); } END_SECTION /* // performance test on a large file: START_SECTION(([[EXTRA]] void importIDs(IdentificationData&, const vector<ProteinIdentification>&, const PeptideIdentificationList&))) { SysInfo::MemUsage mem_usage; vector<ProteinIdentification> proteins_in; PeptideIdentificationList peptides_in; IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("large_test.idXML"), proteins_in, peptides_in); STATUS(mem_usage.delta("PeptideIdentification/ProteinIdentification")); TEST_EQUAL(proteins_in.size(), 1); TEST_EQUAL(proteins_in[0].getHits().size(), 11098); TEST_EQUAL(peptides_in.size(), 328591); TEST_EQUAL(proteins_in[0].getIndistinguishableProteins().size(), 10853); TEST_EQUAL(proteins_in[0].getProteinGroups().size(), 9092); mem_usage.reset(); mem_usage.before(); IdentificationData ids; IdentificationDataConverter::importIDs(ids, proteins_in, peptides_in); STATUS(mem_usage.delta("IdentificationData")); TEST_EQUAL(ids.getParentSequences().size(), 11098); // problem: input data comes from multiple files, spectra with matching names // in different files get merged together -> lower number of input items: TEST_EQUAL(ids.getObservations().size(), 55522); TEST_EQUAL(ids.getIdentifiedPeptides().size(), 73950); // according to "grep" on the input file, there should be 335250 peptide hits // in total - maybe some duplicates?: TEST_EQUAL(ids.getObservationMatches().size(), 332778); TEST_EQUAL(ids.getParentGroupSets().size(), 2); TEST_EQUAL(ids.getParentGroupSets()[0].groups.size(), 10853); TEST_EQUAL(ids.getParentGroupSets()[1].groups.size(), 9092); } END_SECTION */ FeatureMap features; // persist through sections START_SECTION((void importFeatureIDs(FeatureMap& features, bool clear_original))) { FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_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); TEST_EQUAL(features.getIdentificationData().getObservations().size(), 5); TEST_EQUAL(features.getIdentificationData().getObservationMatches().size(), 7); TEST_EQUAL(features.getIdentificationData().getIdentifiedPeptides().size(), 7); TEST_EQUAL(features.getIdentificationData().getParentSequences().size(), 3); TEST_EQUAL(features[0].getIDMatches().size(), 3); TEST_EQUAL(features[1].getIDMatches().size(), 1); TEST_EQUAL(features.getUnassignedIDMatches().size(), 3); // check that original IDs were cleared: TEST_EQUAL(features.getProteinIdentifications().size(), 0); TEST_EQUAL(features.getUnassignedPeptideIdentifications().size(), 0); TEST_EQUAL(features[0].getPeptideIdentifications().size(), 0); TEST_EQUAL(features[1].getPeptideIdentifications().size(), 0); } END_SECTION START_SECTION((void exportFeatureIDs(FeatureMap& features, bool clear_original))) { // convert IDs from previous test back: IdentificationDataConverter::exportFeatureIDs(features); TEST_EQUAL(features.getProteinIdentifications().size(), 2); TEST_EQUAL(features.getUnassignedPeptideIdentifications().size(), 2); TEST_EQUAL(features[0].getPeptideIdentifications().size(), 2); TEST_EQUAL(features[1].getPeptideIdentifications().size(), 1); // check that "original" IDs were cleared: TEST_EQUAL(features.getIdentificationData().empty(), true); } END_SECTION ConsensusMap consensus; // persist through sections START_SECTION((void importConsensusIDs(ConsensusMap& consensus, bool clear_original))) { 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); TEST_EQUAL(consensus.getIdentificationData().getObservations().size(), 5); TEST_EQUAL(consensus.getIdentificationData().getObservationMatches().size(), 7); TEST_EQUAL(consensus.getIdentificationData().getIdentifiedPeptides().size(), 7); TEST_EQUAL(consensus.getIdentificationData().getParentSequences().size(), 3); TEST_EQUAL(consensus[0].getIDMatches().size(), 3); TEST_EQUAL(consensus[1].getIDMatches().size(), 1); TEST_EQUAL(consensus.getUnassignedIDMatches().size(), 3); // check that original IDs were cleared: TEST_EQUAL(consensus.getProteinIdentifications().size(), 0); TEST_EQUAL(consensus.getUnassignedPeptideIdentifications().size(), 0); TEST_EQUAL(consensus[0].getPeptideIdentifications().size(), 0); TEST_EQUAL(consensus[1].getPeptideIdentifications().size(), 0); } END_SECTION START_SECTION((void exportConsensusIDs(ConsensusMap& consensus, bool clear_original))) { // convert IDs from previous test back: IdentificationDataConverter::exportConsensusIDs(consensus); TEST_EQUAL(consensus.getProteinIdentifications().size(), 2); TEST_EQUAL(consensus.getUnassignedPeptideIdentifications().size(), 2); TEST_EQUAL(consensus[0].getPeptideIdentifications().size(), 2); TEST_EQUAL(consensus[1].getPeptideIdentifications().size(), 1); // check that "original" IDs were cleared: TEST_EQUAL(consensus.getIdentificationData().empty(), true); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MultiplexFilteredPeak_test.cpp
.cpp
3,201
99
// 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/MultiplexSatelliteCentroided.h> #include <OpenMS/FEATUREFINDER/MultiplexSatelliteProfile.h> using namespace OpenMS; START_TEST(MultiplexFilteredPeak, "$Id$") MultiplexFilteredPeak* nullPointer = nullptr; MultiplexFilteredPeak* ptr; START_SECTION(MultiplexFilteredPeak()) MultiplexFilteredPeak peak(654.32, 2345.67, 24, 42); TEST_EQUAL(peak.getMZidx(), 24); ptr = new MultiplexFilteredPeak(654.32, 2345.67, 24, 42); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION MultiplexFilteredPeak peak(654.32, 2345.67, 24, 42); MultiplexSatelliteCentroided satellite_centroided(26, 44); MultiplexSatelliteProfile satellite_profile(2346.67, 655.32, 1000.0); peak.addSatellite(25, 43, 3); peak.addSatellite(satellite_centroided, 3); peak.addSatelliteProfile(2347.67, 656.32, 1010.0, 4); peak.addSatelliteProfile(satellite_profile, 4); size_t n; START_SECTION(double getMZ()) TEST_REAL_SIMILAR(peak.getMZ(), 654.32); END_SECTION START_SECTION(double getRT()) TEST_REAL_SIMILAR(peak.getRT(), 2345.67); END_SECTION START_SECTION(size_t getMZidx()) TEST_EQUAL(peak.getMZidx(), 24); END_SECTION START_SECTION(size_t getRTidx()) TEST_EQUAL(peak.getRTidx(), 42); END_SECTION START_SECTION(void addSatellite(size_t rt_idx, size_t mz_idx, size_t pattern_idx)) n = peak.getSatellites().size(); peak.addSatellite(25, 43, 3); TEST_EQUAL(peak.getSatellites().size(), n+1); END_SECTION START_SECTION(void addSatellite(const MultiplexSatelliteCentroided& satellite, size_t pattern_idx)) n = peak.getSatellites().size(); MultiplexSatelliteCentroided satellite_centroided_temp(27, 45); peak.addSatellite(satellite_centroided_temp, 3); TEST_EQUAL(peak.getSatellites().size(), n+1); END_SECTION START_SECTION(void addSatelliteProfile(double rt, double mz, double intensity, size_t pattern_idx)) n = peak.getSatellitesProfile().size(); peak.addSatelliteProfile(2348.67, 657.32, 1020.0, 5); TEST_EQUAL(peak.getSatellitesProfile().size(), n+1); END_SECTION START_SECTION(void addSatelliteProfile(const MultiplexSatelliteProfile& satellite, size_t pattern_idx)) n = peak.getSatellitesProfile().size(); MultiplexSatelliteProfile satellite_profile_temp(2349.67, 658.32, 1030.0); peak.addSatelliteProfile(satellite_profile_temp, 6); TEST_EQUAL(peak.getSatellitesProfile().size(), n+1); END_SECTION START_SECTION(getSatellites()) TEST_EQUAL(peak.getSatellites().size(), 4); END_SECTION START_SECTION(getSatellitesProfile()) TEST_EQUAL(peak.getSatellitesProfile().size(), 4); END_SECTION START_SECTION(size_t size()) TEST_EQUAL(peak.size(), 4); END_SECTION START_SECTION(size_t sizeProfile()) TEST_EQUAL(peak.sizeProfile(), 4); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SemanticValidator_test.cpp
.cpp
5,076
127
// 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, Andreas Bertsch $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/VALIDATORS/SemanticValidator.h> #include <OpenMS/DATASTRUCTURES/CVMappings.h> #include <OpenMS/FORMAT/CVMappingFile.h> #include <OpenMS/FORMAT/ControlledVocabulary.h> #include <OpenMS/SYSTEM/File.h> /////////////////////////// START_TEST(SemanticValidator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace OpenMS::Internal; using namespace std; CVMappings mapping; CVMappingFile().load(OPENMS_GET_TEST_DATA_PATH("SemanticValidator_mapping.xml"),mapping); ControlledVocabulary cv; cv.loadFromOBO("PSI",OPENMS_GET_TEST_DATA_PATH("SemanticValidator_cv.obo")); cv.loadFromOBO("PATO",File::find("/CV/quality.obo")); cv.loadFromOBO("UO",File::find("/CV/unit.obo")); cv.loadFromOBO("brenda",File::find("/CV/brenda.obo")); cv.loadFromOBO("GO",File::find("/CV/goslim_goa.obo")); SemanticValidator* ptr = nullptr; SemanticValidator* nullPointer = nullptr; START_SECTION((SemanticValidator(const CVMappings& mapping, const ControlledVocabulary& cv))) ptr = new SemanticValidator(mapping,cv); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~SemanticValidator())) delete ptr; END_SECTION START_SECTION((void setTag(const String& tag))) NOT_TESTABLE END_SECTION START_SECTION((void setAccessionAttribute(const String& accession))) NOT_TESTABLE END_SECTION START_SECTION((void setNameAttribute(const String& name))) NOT_TESTABLE END_SECTION START_SECTION((void setValueAttribute(const String& value))) NOT_TESTABLE END_SECTION START_SECTION((bool validate(const String &filename, StringList &errors, StringList &warnings))) StringList errors, warnings; //---------------------------------------------------------------------------------------- //test exceptions SemanticValidator sv(mapping, cv); TEST_EXCEPTION(Exception::FileNotFound, sv.validate("/does/not/exist", errors, warnings)); //---------------------------------------------------------------------------------------- //test of valid file TEST_EQUAL(sv.validate(OPENMS_GET_TEST_DATA_PATH("SemanticValidator_valid.xml"), errors, warnings),true); TEST_EQUAL(errors.size(),0) TEST_EQUAL(warnings.size(),0) //---------------------------------------------------------------------------------------- //test of corrupt file TEST_EQUAL(sv.validate(OPENMS_GET_TEST_DATA_PATH("SemanticValidator_corrupt.xml"), errors, warnings),false); TEST_EQUAL(errors.size(),5) TEST_STRING_EQUAL(errors[0],"Violated mapping rule 'R3' at element '/mzML/fileDescription/sourceFileList/sourceFile', 2 term(s) should be present, 1 found!") TEST_STRING_EQUAL(errors[1],"Name of CV term not correct: 'MS:1000554 - LCQ Deca2 - invalid repeat' should be 'LCQ Deca'") TEST_STRING_EQUAL(errors[2],"CV term used in invalid element: 'MS:1000030 - vendor' at element '/mzML/instrumentConfigurationList/instrumentConfiguration'") TEST_STRING_EQUAL(errors[3],"Violated mapping rule 'R6a' number of term repeats at element '/mzML/instrumentConfigurationList/instrumentConfiguration'") TEST_STRING_EQUAL(errors[4],"Violated mapping rule 'R17a' at element '/mzML/run/spectrumList/spectrum/spectrumDescription', 1 term(s) should be present, 0 found!") TEST_EQUAL(warnings.size(),4) TEST_STRING_EQUAL(warnings[0],"Unknown CV term: 'MS:1111569 - SHA-1' at element '/mzML/fileDescription/sourceFileList/sourceFile'") TEST_STRING_EQUAL(warnings[1],"Obsolete CV term: 'MS:1000030 - vendor' at element '/mzML/instrumentConfigurationList/instrumentConfiguration'") TEST_STRING_EQUAL(warnings[2],"No mapping rule found for element '/mzML/acquisitionSettingsList/acquisitionSettings/targetList/target'") TEST_STRING_EQUAL(warnings[3],"No mapping rule found for element '/mzML/acquisitionSettingsList/acquisitionSettings/targetList/target'") END_SECTION START_SECTION((void setCheckTermValueTypes(bool check))) SemanticValidator sv(mapping, cv); sv.setCheckTermValueTypes(true); NOT_TESTABLE END_SECTION START_SECTION((void setCheckUnits(bool check))) SemanticValidator sv(mapping, cv); sv.setCheckUnits(true); NOT_TESTABLE END_SECTION START_SECTION((void setUnitAccessionAttribute(const String &accession))) SemanticValidator sv(mapping, cv); sv.setUnitAccessionAttribute("unitAccession"); NOT_TESTABLE END_SECTION START_SECTION((void setUnitNameAttribute(const String &name))) SemanticValidator sv(mapping, cv); sv.setUnitNameAttribute("unit"); NOT_TESTABLE END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PythonInfo_test.cpp
.cpp
2,287
77
// 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/String.h> #include <OpenMS/SYSTEM/PythonInfo.h> #include <OpenMS/SYSTEM/File.h> #include <fstream> #include <QDir> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(TextFile, "$Id$") ///////////////////////////////////////////////////////////// START_SECTION((static bool canRun(String& python_executable, String& error_msg))) // test for missing python executable String py = "does_not_exist_@@"; String error_msg; TEST_EQUAL(PythonInfo::canRun(py, error_msg), false) TEST_EQUAL(error_msg.hasSubstring("Python not found at"), true) auto tmp_file = File::getTemporaryFile(); ofstream f(tmp_file); // create the file f.close(); TEST_EQUAL(PythonInfo::canRun(tmp_file, error_msg), false) TEST_EQUAL(error_msg.hasSubstring("failed to run"), true) py = "python"; if (PythonInfo::canRun(py, error_msg)) { TEST_EQUAL(File::exists(py), true) TEST_EQUAL(QDir::isRelativePath(py.toQString()), false) } END_SECTION START_SECTION(bool PythonInfo::isPackageInstalled(const String& python_executable, const String& package_name)) String error_msg; String py = "python"; if (PythonInfo::canRun(py, error_msg)) { TEST_EQUAL(PythonInfo::isPackageInstalled(py, "veryWeirdPackage___@@__@"), false) TEST_EQUAL(PythonInfo::isPackageInstalled(py, "math"), true) } END_SECTION START_SECTION(static String getVersion(const String& python_executable)) String py = "python"; String error_msg; if (PythonInfo::canRun(py, error_msg)) { String version = PythonInfo::getVersion(py); TEST_EQUAL(version.empty(), false) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FeatureMap_test.cpp
.cpp
20,913
711
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Marc Sturm, Chris Bielow, Clemens Groepl $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/KERNEL/Feature.h> #include <OpenMS/MATH/MathFunctions.h> #include <OpenMS/METADATA/DataProcessing.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <algorithm> #include <string> /////////////////////////// using namespace std; using namespace OpenMS; /////////////////////////// ///////////////////////////////////////////////////////////// START_TEST(FeatureMap, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FeatureMap* pl_ptr = nullptr; FeatureMap* nullPointer = nullptr; START_SECTION((FeatureMap())) pl_ptr = new FeatureMap(); TEST_NOT_EQUAL(pl_ptr, nullPointer) TEST_EQUAL(pl_ptr->size(), 0) TEST_EQUAL(pl_ptr->hasRange() == HasRangeType::NONE, true) END_SECTION START_SECTION((virtual ~FeatureMap())) delete pl_ptr; END_SECTION PeptideIdentificationList ids(1); PeptideHit hit; hit.setSequence(AASequence::fromString("ABCDE")); ids[0].setHits(std::vector<PeptideHit>(1, hit)); Feature feature1; feature1.getPosition()[0] = 2.0; feature1.getPosition()[1] = 3.0; feature1.setIntensity(1.0f); feature1.setPeptideIdentifications(ids); // single hit Feature feature2; feature2.getPosition()[0] = 0.0; feature2.getPosition()[1] = 2.5; feature2.setIntensity(0.5f); ids.resize(2); ids[1].setHits(std::vector<PeptideHit>(1, hit)); // same as first hit feature2.setPeptideIdentifications(ids); Feature feature3; feature3.getPosition()[0] = 10.5; feature3.getPosition()[1] = 0.0; feature3.setIntensity(0.01f); hit.setSequence(AASequence::fromString("KRGH")); ids[1].setHits(std::vector<PeptideHit>(1, hit)); // different to first hit feature3.setPeptideIdentifications(ids); //feature with convex hulls Feature feature4; feature4.getPosition()[0] = 5.25; feature4.getPosition()[1] = 1.5; feature4.setIntensity(0.5f); std::vector< ConvexHull2D > hulls(1); hulls[0].addPoint(DPosition<2>(-1.0,2.0)); hulls[0].addPoint(DPosition<2>(4.0,1.2)); hulls[0].addPoint(DPosition<2>(5.0,3.123)); feature4.setConvexHulls(hulls); START_SECTION((const std::vector<ProteinIdentification>& getProteinIdentifications() const)) FeatureMap tmp; TEST_EQUAL(tmp.getProteinIdentifications().size(),0) END_SECTION START_SECTION((std::vector<ProteinIdentification>& getProteinIdentifications())) FeatureMap tmp; tmp.getProteinIdentifications().resize(1); TEST_EQUAL(tmp.getProteinIdentifications().size(),1) END_SECTION START_SECTION((void setProteinIdentifications(const std::vector<ProteinIdentification>& protein_identifications))) FeatureMap tmp; tmp.setProteinIdentifications(std::vector<ProteinIdentification>(2)); TEST_EQUAL(tmp.getProteinIdentifications().size(),2) END_SECTION START_SECTION((const PeptideIdentificationList& getUnassignedPeptideIdentifications() const)) FeatureMap tmp; TEST_EQUAL(tmp.getUnassignedPeptideIdentifications().size(),0) END_SECTION START_SECTION((PeptideIdentificationList& getUnassignedPeptideIdentifications())) FeatureMap tmp; tmp.getUnassignedPeptideIdentifications().resize(1); TEST_EQUAL(tmp.getUnassignedPeptideIdentifications().size(),1) END_SECTION START_SECTION((void setUnassignedPeptideIdentifications(const PeptideIdentificationList& unassigned_peptide_identifications))) FeatureMap tmp; tmp.setUnassignedPeptideIdentifications(PeptideIdentificationList(2)); TEST_EQUAL(tmp.getUnassignedPeptideIdentifications().size(),2) END_SECTION START_SECTION((const std::vector<DataProcessing>& getDataProcessing() const)) FeatureMap tmp; TEST_EQUAL(tmp.getDataProcessing().size(),0) END_SECTION START_SECTION((std::vector<DataProcessing>& getDataProcessing())) FeatureMap tmp; tmp.getDataProcessing().resize(1); TEST_EQUAL(tmp.getDataProcessing().size(),1) END_SECTION START_SECTION((void setDataProcessing(const std::vector< DataProcessing > &processing_method))) FeatureMap tmp; std::vector<DataProcessing> dummy; dummy.resize(1); tmp.setDataProcessing(dummy); TEST_EQUAL(tmp.getDataProcessing().size(),1); END_SECTION START_SECTION((void updateRanges())) //test without convex hulls FeatureMap s; s.push_back(feature1); s.push_back(feature2); s.push_back(feature3); s.updateRanges(); s.updateRanges(); //second time to check the initialization TEST_REAL_SIMILAR(s.getMaxIntensity(),1.0) TEST_REAL_SIMILAR(s.getMinIntensity(), 0.01) TEST_REAL_SIMILAR(s.getMaxRT(),10.5) TEST_REAL_SIMILAR(s.getMaxMZ(),3.0) TEST_REAL_SIMILAR(s.getMinRT(),0.0) TEST_REAL_SIMILAR(s.getMinMZ(),0.0) //test with convex hull s.push_back(feature4); s.updateRanges(); TEST_REAL_SIMILAR(s.getMaxIntensity(), 1.0) TEST_REAL_SIMILAR(s.getMinIntensity(), 0.01) TEST_REAL_SIMILAR(s.getMaxRT(),10.5) TEST_REAL_SIMILAR(s.getMaxMZ(),3.123) TEST_REAL_SIMILAR(s.getMinRT(),-1.0) TEST_REAL_SIMILAR(s.getMinMZ(),0.0) END_SECTION START_SECTION((FeatureMap(const FeatureMap &source))) FeatureMap map1; map1.setMetaValue("meta",String("value")); map1.push_back(feature1); map1.push_back(feature2); map1.push_back(feature3); map1.updateRanges(); map1.setIdentifier("lsid");; map1.getDataProcessing().resize(1); map1.getProteinIdentifications().resize(1); map1.getUnassignedPeptideIdentifications().resize(1); FeatureMap map2(map1); TEST_EQUAL(map2.size(),3); TEST_EQUAL(map2.getMetaValue("meta").toString(),"value") TEST_REAL_SIMILAR(map2.getMaxIntensity(),1.0) TEST_STRING_EQUAL(map2.getIdentifier(),"lsid") TEST_EQUAL(map2.getDataProcessing().size(),1) TEST_EQUAL(map2.getProteinIdentifications().size(),1); TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),1); END_SECTION START_SECTION((FeatureMap& operator = (const FeatureMap& rhs))) FeatureMap map1; map1.setMetaValue("meta",String("value")); map1.push_back(feature1); map1.push_back(feature2); map1.push_back(feature3); map1.updateRanges(); map1.setIdentifier("lsid"); map1.getDataProcessing().resize(1); map1.getProteinIdentifications().resize(1); map1.getUnassignedPeptideIdentifications().resize(1); //assignment FeatureMap map2; map2 = map1; TEST_EQUAL(map2.size(),3); TEST_EQUAL(map2.getMetaValue("meta").toString(),"value") TEST_REAL_SIMILAR(map2.getMaxIntensity(),1.0) TEST_STRING_EQUAL(map2.getIdentifier(),"lsid") TEST_EQUAL(map2.getDataProcessing().size(),1) TEST_EQUAL(map2.getProteinIdentifications().size(),1); TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),1); //assignment of empty object map2 = FeatureMap(); TEST_EQUAL(map2.size(),0); TEST_EQUAL(map2.hasRange() == HasRangeType::NONE, true) TEST_STRING_EQUAL(map2.getIdentifier(),"") TEST_EQUAL(map2.getDataProcessing().size(),0) TEST_EQUAL(map2.getProteinIdentifications().size(),0); TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),0); END_SECTION START_SECTION((bool operator == (const FeatureMap& rhs) const)) FeatureMap empty,edit; TEST_TRUE(empty == edit) edit.setIdentifier("lsid");; TEST_EQUAL(empty==edit, false) edit = empty; edit.push_back(feature1); TEST_EQUAL(empty==edit, false) edit = empty; edit.getDataProcessing().resize(1); TEST_EQUAL(empty==edit, false) edit = empty; edit.getProteinIdentifications().resize(1); TEST_EQUAL(edit==empty, false) edit = empty; edit.getUnassignedPeptideIdentifications().resize(10); TEST_EQUAL(empty==edit, false) edit = empty; edit.push_back(feature1); edit.push_back(feature2); edit.updateRanges(); edit.clear(false); TEST_EQUAL(empty==edit, false) END_SECTION START_SECTION((bool operator != (const FeatureMap& rhs) const)) FeatureMap empty,edit; TEST_EQUAL(empty!=edit, false) edit.setIdentifier("lsid");; TEST_FALSE(empty == edit) edit = empty; edit.push_back(feature1); TEST_FALSE(empty == edit) edit = empty; edit.getDataProcessing().resize(1); TEST_FALSE(empty == edit) edit = empty; edit.getProteinIdentifications().resize(10); TEST_FALSE(edit == empty) edit = empty; edit.getUnassignedPeptideIdentifications().resize(10); TEST_FALSE(empty == edit) edit = empty; edit.push_back(feature1); edit.push_back(feature2); edit.updateRanges(); edit.clear(false); TEST_FALSE(empty == edit) END_SECTION START_SECTION((FeatureMap operator + (const FeatureMap& rhs) const)) // just some basic testing... most is done in operator +=() FeatureMap m1, m2, m3; TEST_EQUAL(m1+m2, m3) Feature f1; f1.setMZ(100.12); m1.push_back(f1); m3 = m1; TEST_EQUAL(m1+m2, m3) END_SECTION START_SECTION((FeatureMap& operator+= (const FeatureMap& rhs))) FeatureMap m1, m2, m3; // adding empty maps has no effect: m1+=m2; TEST_EQUAL(m1, m3) // with content: Feature f1; f1.setMZ(100.12); m1.push_back(f1); m3 = m1; m1+=m2; TEST_EQUAL(m1, m3) // test basic classes m1.setIdentifier ("123"); m1.getDataProcessing().resize(1); m1.getProteinIdentifications().resize(1); m1.getUnassignedPeptideIdentifications().resize(1); m1.ensureUniqueId(); m2.setIdentifier ("321"); m2.getDataProcessing().resize(2); m2.getProteinIdentifications().resize(2); m2.getUnassignedPeptideIdentifications().resize(2); m2.push_back(Feature()); m2.push_back(Feature()); m1+=m2; TEST_EQUAL(m1.getIdentifier(), "") TEST_EQUAL(UniqueIdInterface::isValid(m1.getUniqueId()), false) TEST_EQUAL(m1.getDataProcessing().size(), 3) TEST_EQUAL(m1.getProteinIdentifications().size(),3) TEST_EQUAL(m1.getUnassignedPeptideIdentifications().size(),3) TEST_EQUAL(m1.size(),3); END_SECTION START_SECTION((void sortByIntensity(bool reverse=false))) FeatureMap to_be_sorted; Feature f1; f1.setIntensity(10.0f); to_be_sorted.push_back(f1); Feature f2; f2.setIntensity(5.0f); to_be_sorted.push_back(f2); Feature f3; f3.setIntensity(3.0f); to_be_sorted.push_back(f3); to_be_sorted.sortByIntensity(); TEST_EQUAL(to_be_sorted[0].getIntensity(),3) TEST_EQUAL(to_be_sorted[1].getIntensity(),5) TEST_EQUAL(to_be_sorted[2].getIntensity(),10) to_be_sorted.sortByIntensity(true); TEST_EQUAL(to_be_sorted[0].getIntensity(),10) TEST_EQUAL(to_be_sorted[1].getIntensity(),5) TEST_EQUAL(to_be_sorted[2].getIntensity(),3) END_SECTION START_SECTION((void sortByPosition())) FeatureMap to_be_sorted; Feature f1; f1.getPosition()[0] = 10; to_be_sorted.push_back(f1); Feature f2; f2.getPosition()[0] = 5; to_be_sorted.push_back(f2); Feature f3; f3.getPosition()[0] = 3; to_be_sorted.push_back(f3); to_be_sorted.sortByPosition(); TEST_EQUAL(to_be_sorted[0].getPosition()[0],3) TEST_EQUAL(to_be_sorted[1].getPosition()[0],5) TEST_EQUAL(to_be_sorted[2].getPosition()[0],10) END_SECTION START_SECTION((void sortByMZ())) FeatureMap to_be_sorted; Feature f1; f1.getPosition()[0] = 10; f1.getPosition()[1] = 25; to_be_sorted.push_back(f1); Feature f2; f2.getPosition()[0] = 5; f2.getPosition()[1] = 15; to_be_sorted.push_back(f2); Feature f3; f3.getPosition()[0] = 3; f3.getPosition()[1] = 10; to_be_sorted.push_back(f3); to_be_sorted.sortByMZ(); TEST_EQUAL(to_be_sorted[0].getPosition()[1],10) TEST_EQUAL(to_be_sorted[1].getPosition()[1],15) TEST_EQUAL(to_be_sorted[2].getPosition()[1],25) END_SECTION START_SECTION((void sortByRT())) FeatureMap to_be_sorted; Feature f1; f1.getPosition()[0] = 10; f1.getPosition()[1] = 25; to_be_sorted.push_back(f1); Feature f2; f2.getPosition()[0] = 5; f2.getPosition()[1] = 15; to_be_sorted.push_back(f2); Feature f3; f3.getPosition()[0] = 3; f3.getPosition()[1] = 10; to_be_sorted.push_back(f3); to_be_sorted.sortByRT(); TEST_EQUAL(to_be_sorted[0].getPosition()[0],3) TEST_EQUAL(to_be_sorted[1].getPosition()[0],5) TEST_EQUAL(to_be_sorted[2].getPosition()[0],10) END_SECTION START_SECTION((void swap(FeatureMap& from))) { FeatureMap map1, map2; map1.setIdentifier("stupid comment"); map1.push_back(feature1); map1.push_back(feature2); map1.updateRanges(); map1.getDataProcessing().resize(1); map1.getProteinIdentifications().resize(1); map1.getUnassignedPeptideIdentifications().resize(1); map1.swap(map2); TEST_EQUAL(map1.getIdentifier(),"") TEST_EQUAL(map1.size(),0) TEST_EQUAL(map1.hasRange() == HasRangeType::NONE, true) TEST_EQUAL(map1.getDataProcessing().size(),0) TEST_EQUAL(map1.getProteinIdentifications().size(),0) TEST_EQUAL(map1.getUnassignedPeptideIdentifications().size(),0) TEST_EQUAL(map2.getIdentifier(),"stupid comment") TEST_EQUAL(map2.size(),2) TEST_REAL_SIMILAR(map2.getMinIntensity(),0.5) TEST_EQUAL(map2.getDataProcessing().size(),1) TEST_EQUAL(map2.getProteinIdentifications().size(),1) TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),1) } END_SECTION START_SECTION((void swapFeaturesOnly(FeatureMap& from))) { FeatureMap map1, map2; map1.setIdentifier("stupid comment"); map1.push_back(feature1); map1.push_back(feature2); map1.updateRanges(); map1.getDataProcessing().resize(1); map1.getProteinIdentifications().resize(1); map1.getUnassignedPeptideIdentifications().resize(1); map1.swapFeaturesOnly(map2); TEST_EQUAL(map1.getIdentifier(),"stupid comment") TEST_EQUAL(map1.size(),0) TEST_EQUAL(map1.hasRange() == HasRangeType::NONE, true) TEST_EQUAL(map1.getDataProcessing().size(),1) TEST_EQUAL(map1.getProteinIdentifications().size(),1) TEST_EQUAL(map1.getUnassignedPeptideIdentifications().size(),1) TEST_EQUAL(map2.getIdentifier(),"") TEST_EQUAL(map2.size(),2) TEST_REAL_SIMILAR(map2.getMinIntensity(),0.5) TEST_EQUAL(map2.getDataProcessing().size(),0) TEST_EQUAL(map2.getProteinIdentifications().size(),0) TEST_EQUAL(map2.getUnassignedPeptideIdentifications().size(),0) } END_SECTION START_SECTION((void sortByOverallQuality(bool reverse=false))) FeatureMap to_be_sorted; Feature f1; f1.getPosition()[0] = 1; f1.getPosition()[1] = 1; f1.setOverallQuality(10); to_be_sorted.push_back(f1); Feature f2; f2.getPosition()[0] = 2; f2.getPosition()[1] = 2; f2.setOverallQuality(30); to_be_sorted.push_back(f2); Feature f3; f3.getPosition()[0] = 3; f3.getPosition()[1] = 3; f3.setOverallQuality(20); to_be_sorted.push_back(f3); to_be_sorted.sortByOverallQuality(); TEST_EQUAL(to_be_sorted[0].getPosition()[0],1) TEST_EQUAL(to_be_sorted[1].getPosition()[0],3) TEST_EQUAL(to_be_sorted[2].getPosition()[0],2) TEST_EQUAL(to_be_sorted[0].getOverallQuality(),10) TEST_EQUAL(to_be_sorted[1].getOverallQuality(),20) TEST_EQUAL(to_be_sorted[2].getOverallQuality(),30) to_be_sorted.sortByOverallQuality(true); TEST_EQUAL(to_be_sorted[0].getPosition()[0],2) TEST_EQUAL(to_be_sorted[1].getPosition()[0],3) TEST_EQUAL(to_be_sorted[2].getPosition()[0],1) TEST_EQUAL(to_be_sorted[0].getOverallQuality(),30) TEST_EQUAL(to_be_sorted[1].getOverallQuality(),20) TEST_EQUAL(to_be_sorted[2].getOverallQuality(),10) END_SECTION START_SECTION((void clear(bool clear_meta_data=true))) FeatureMap map1; map1.setIdentifier("stupid comment"); map1.push_back(feature1); map1.push_back(feature2); map1.updateRanges(); map1.getDataProcessing().resize(1); map1.getProteinIdentifications().resize(1); map1.getUnassignedPeptideIdentifications().resize(1); map1.clear(false); TEST_EQUAL(map1.size(),0) TEST_EQUAL(map1 == FeatureMap(),false) TEST_EQUAL(map1.empty(),true) map1.clear(true); TEST_EQUAL(map1.size(),0) TEST_EQUAL(map1 == FeatureMap(),true) TEST_EQUAL(map1.empty(),true) END_SECTION START_SECTION(([EXTRA] void uniqueIdToIndex())) { FeatureMap fm; Feature f; f.setMZ(23.9); std::vector<std::pair <Size, UInt64>> pairs; const Size num_features = 4; for (Size i = 0; i < num_features; ++i) { f.setRT(i*100); f.setUniqueId(); pairs.push_back(make_pair(i,f.getUniqueId())); fm.push_back(f); } for (Size i = 0; i < num_features; ++i) { TEST_EQUAL(fm.uniqueIdToIndex(pairs[i].second),pairs[i].first) } STATUS("shuffling ..."); Math::RandomShuffler r{0}; r.portable_random_shuffle(pairs.begin(),pairs.end()); r.portable_random_shuffle(fm.begin(),fm.end()); for ( Size i = 0; i < num_features; ++i ) { STATUS("pairs[i]: " << pairs[i].first << ", " << pairs[i].second ) TEST_EQUAL(fm.uniqueIdToIndex(fm[pairs[i].first].getUniqueId()),pairs[i].first) TEST_EQUAL(fm[fm.uniqueIdToIndex(pairs[i].second)].getUniqueId(),pairs[i].second) } f.setRT(98765421); f.setUniqueId(); pairs.push_back(make_pair(987654321,f.getUniqueId())); TEST_EQUAL(fm.uniqueIdToIndex(pairs.back().second),Size(-1)) fm.push_back(f); TEST_EQUAL(fm.uniqueIdToIndex(pairs.back().second),fm.size()-1) fm.push_back(Feature()); fm.push_back(f); fm.push_back(Feature()); fm.push_back(Feature()); STATUS("fm: " << fm); fm.erase(fm.begin()+1); fm.erase(fm.begin()+2); STATUS("fm: " << fm); TEST_EXCEPTION_WITH_MESSAGE(Exception::Postcondition,fm.updateUniqueIdToIndex(),"Duplicate valid unique ids detected! RandomAccessContainer has size()==7, num_valid_unique_id==4, uniqueid_to_index_.size()==3"); } END_SECTION START_SECTION((template <typename Type> Size applyMemberFunction(Size(Type::*member_function)()))) { FeatureMap fm; fm.push_back(Feature()); fm.push_back(Feature()); fm.back().getSubordinates().push_back(Feature()); TEST_EQUAL(fm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),4) fm.setUniqueId(); TEST_EQUAL(fm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),3) fm.applyMemberFunction(&UniqueIdInterface::setUniqueId); TEST_EQUAL(fm.applyMemberFunction(&UniqueIdInterface::hasValidUniqueId),4) TEST_EQUAL(fm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),0) fm.begin()->clearUniqueId(); TEST_EQUAL(fm.applyMemberFunction(&UniqueIdInterface::hasValidUniqueId),3) TEST_EQUAL(fm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),1) } END_SECTION START_SECTION((template <typename Type> Size applyMemberFunction(Size(Type::*member_function)() const) const)) { FeatureMap fm; FeatureMap const & fmc(fm); fm.push_back(Feature()); fm.push_back(Feature()); fm.back().getSubordinates().push_back(Feature()); TEST_EQUAL(fmc.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),4) fm.setUniqueId(); TEST_EQUAL(fmc.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),3) fm.applyMemberFunction(&UniqueIdInterface::setUniqueId); TEST_EQUAL(fmc.applyMemberFunction(&UniqueIdInterface::hasValidUniqueId),4) TEST_EQUAL(fm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),0) fm.begin()->clearUniqueId(); TEST_EQUAL(fmc.applyMemberFunction(&UniqueIdInterface::hasValidUniqueId),3) TEST_EQUAL(fmc.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId),1) } END_SECTION START_SECTION((AnnotationStatistics getAnnotationStatistics() const)) FeatureMap fm; AnnotationStatistics stats, res; stats = fm.getAnnotationStatistics(); TEST_TRUE(stats == res) fm.push_back(feature1); // single hit stats = fm.getAnnotationStatistics(); ++res.states[static_cast<size_t>(BaseFeature::AnnotationState::FEATURE_ID_SINGLE)]; std::cout << res; TEST_TRUE(stats == res) fm.push_back(feature4); // single hit + no hit stats = fm.getAnnotationStatistics(); ++res.states[static_cast<size_t>(BaseFeature::AnnotationState::FEATURE_ID_NONE)]; std::cout << res; TEST_TRUE(stats == res) fm.push_back(feature4); // single hit + 2x no hit stats = fm.getAnnotationStatistics(); ++res.states[static_cast<size_t>(BaseFeature::AnnotationState::FEATURE_ID_NONE)]; std::cout << res; TEST_TRUE(stats == res) fm.push_back(feature2); // single hit + 2x no hit + multi-hit (same) stats = fm.getAnnotationStatistics(); ++res.states[static_cast<size_t>(BaseFeature::AnnotationState::FEATURE_ID_MULTIPLE_SAME)]; std::cout << res; TEST_TRUE(stats == res) fm.push_back(feature3); // single hit + 2x no hit + multi-hit (same) + multi (divergent) stats = fm.getAnnotationStatistics(); ++res.states[static_cast<size_t>(BaseFeature::AnnotationState::FEATURE_ID_MULTIPLE_DIVERGENT)]; std::cout << res; std::cout << stats; TEST_TRUE(stats == res) END_SECTION START_SECTION([EXTRA] ExposedVector Ctor) FeatureMap fm(10); TEST_EQUAL(fm.size(), 10); Feature f4; f4.getPosition()[0] = 5.25; FeatureMap fm2(10, f4); TEST_EQUAL(fm2.size(), 10) TEST_EQUAL(fm2[6].getPosition()[0], 5.25) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeptideIdentification_test.cpp
.cpp
19,635
594
// 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 <unordered_map> #include <OpenMS/FORMAT/ConsensusXMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/FORMAT/MascotXMLFile.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/CONCEPT/Constants.h> #include <OpenMS/DATASTRUCTURES/String.h> /////////////////////////// START_TEST(PeptideIdentification, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; double peptide_significance_threshold = 42.3; std::vector<PeptideHit> peptide_hits; PeptideHit peptide_hit; ProteinIdentification protein_identification; vector<PeptideIdentification> identifications; MascotXMLFile xml_file; peptide_hits.push_back(peptide_hit); PeptideIdentification* ptr = nullptr; PeptideIdentification* nullPointer = nullptr; START_SECTION((PeptideIdentification())) ptr = new PeptideIdentification(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~PeptideIdentification())) PeptideIdentification hits; delete ptr; END_SECTION // Copy Constructor START_SECTION((PeptideIdentification(const PeptideIdentification& source))) { PeptideIdentification hits; hits.setSignificanceThreshold(peptide_significance_threshold); hits.setHits(peptide_hits); hits.setMetaValue("label",17); hits.setIdentifier("id"); hits.setScoreType("score_type"); hits.setHigherScoreBetter(false); PeptideIdentification hits2(hits); TEST_EQUAL(hits.getSignificanceThreshold(), hits2.getSignificanceThreshold()) TEST_TRUE(hits.getHits().size() == 1) TEST_TRUE(*(hits.getHits().begin()) == peptide_hit) TEST_EQUAL((UInt)hits.getMetaValue("label"),17) TEST_EQUAL(hits.getIdentifier(),"id") TEST_EQUAL(hits.getScoreType(),"score_type") TEST_FALSE(hits.isHigherScoreBetter()) } END_SECTION // Move Constructor START_SECTION((PeptideIdentification(PeptideIdentification&& source) noexcept)) { // Ensure that PeptideIdentification has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_TRUE(noexcept(PeptideIdentification(std::declval<PeptideIdentification&&>()))) PeptideIdentification hits; hits.setSignificanceThreshold(peptide_significance_threshold); hits.setHits(peptide_hits); hits.setMetaValue("label",17); hits.setIdentifier("id"); hits.setScoreType("score_type"); hits.setHigherScoreBetter(false); PeptideIdentification example(hits); PeptideIdentification hits2(std::move(example)); TEST_EQUAL(hits.getSignificanceThreshold(), hits2.getSignificanceThreshold()) TEST_TRUE(hits.getHits().size() == 1) TEST_TRUE(*(hits.getHits().begin()) == peptide_hit) TEST_EQUAL((UInt)hits.getMetaValue("label"),17) TEST_EQUAL(hits.getIdentifier(),"id") TEST_EQUAL(hits.getScoreType(),"score_type") TEST_FALSE(hits.isHigherScoreBetter()) // the move source should be empty TEST_TRUE(example.getHits().empty()) TEST_TRUE(example.isMetaEmpty()) TEST_TRUE(example.getIdentifier().empty()) TEST_TRUE(example.getScoreType().empty()) } END_SECTION START_SECTION((PeptideIdentification& operator=(const PeptideIdentification& source))) PeptideIdentification hits; hits.setSignificanceThreshold(peptide_significance_threshold); hits.setHits(peptide_hits); hits.setMetaValue("label",17); hits.setIdentifier("id"); hits.setScoreType("score_type"); hits.setHigherScoreBetter(false); PeptideIdentification hits2; hits2 = hits; TEST_EQUAL(hits.getSignificanceThreshold(), hits2.getSignificanceThreshold()) TEST_TRUE(hits.getHits().size() == 1) TEST_TRUE(*(hits.getHits().begin()) == peptide_hit) TEST_EQUAL((UInt)hits.getMetaValue("label"),17) TEST_EQUAL(hits.getIdentifier(),"id") TEST_EQUAL(hits.getScoreType(),"score_type") TEST_FALSE(hits.isHigherScoreBetter()) END_SECTION START_SECTION((bool operator == (const PeptideIdentification& rhs) const)) PeptideIdentification search1, search2; TEST_TRUE(search1 == search2) search1.setSignificanceThreshold(peptide_significance_threshold); TEST_FALSE(search1 == search2) search1 = search2; search2.setMetaValue("label",17); TEST_FALSE(search1 == search2) search1 = search2; search2.setIdentifier("id"); TEST_FALSE(search1 == search2) search1 = search2; search2.setScoreType("score_type"); TEST_FALSE(search1 == search2) search1 = search2; search2.setHigherScoreBetter(false); TEST_FALSE(search1 == search2) search1 = search2; END_SECTION START_SECTION((bool operator != (const PeptideIdentification& rhs) const)) PeptideIdentification search1, search2; TEST_FALSE(search1 != search2) search1.setSignificanceThreshold(peptide_significance_threshold); TEST_FALSE(search1 == search2) search1 = search2; //rest does not need to be tested, as it is tested in the operator== test implicitly! END_SECTION START_SECTION((double getRT() const)) PeptideIdentification pi; TEST_FALSE(pi.hasRT()); pi.setRT(1024.0); TEST_EQUAL(pi.getRT(), 1024.0); END_SECTION START_SECTION(void setRT(double mz)) NOT_TESTABLE // tested above END_SECTION START_SECTION(bool hasRT()) NOT_TESTABLE // tested above END_SECTION START_SECTION((double getMZ() const)) PeptideIdentification pi; TEST_FALSE(pi.hasMZ()); pi.setMZ(1024.0); TEST_EQUAL(pi.getMZ(), 1024.0); END_SECTION START_SECTION(bool hasMZ()) NOT_TESTABLE // tested above END_SECTION START_SECTION((double getSignificanceThreshold() const)) PeptideIdentification hits; hits.setSignificanceThreshold(peptide_significance_threshold); TEST_EQUAL(hits.getSignificanceThreshold(), peptide_significance_threshold) END_SECTION START_SECTION((const std::vector<PeptideHit>& getHits() const)) PeptideIdentification hits; hits.insertHit(peptide_hit); TEST_TRUE(hits.getHits().size() == 1) TEST_TRUE(hits.getHits()[0] == peptide_hit) END_SECTION START_SECTION((void insertHit(const PeptideHit &hit))) PeptideIdentification hits; hits.insertHit(peptide_hit); TEST_TRUE(hits.getHits().size() == 1) TEST_TRUE(*(hits.getHits().begin()) == peptide_hit) END_SECTION START_SECTION((void setHits(const std::vector< PeptideHit > &hits))) PeptideIdentification hits; hits.setHits(peptide_hits); TEST_TRUE(hits.getHits() == peptide_hits) END_SECTION START_SECTION((void setSignificanceThreshold(double value))) PeptideIdentification hits; hits.setSignificanceThreshold(peptide_significance_threshold); TEST_EQUAL(hits.getSignificanceThreshold(), peptide_significance_threshold) END_SECTION START_SECTION((void testSignificanceThresholdMetaValue())) { PeptideIdentification id; // Test default value TEST_EQUAL(id.getSignificanceThreshold(), 0.0); TEST_EQUAL(id.metaValueExists(Constants::UserParam::SIGNIFICANCE_THRESHOLD), false); // Test setting a new value id.setSignificanceThreshold(42.0); TEST_EQUAL(id.getSignificanceThreshold(), 42.0); TEST_EQUAL(id.getMetaValue(Constants::UserParam::SIGNIFICANCE_THRESHOLD), 42.0); // Test that the meta value is copied PeptideIdentification id2(id); TEST_EQUAL(id2.getSignificanceThreshold(), 42.0); TEST_EQUAL(id2.getMetaValue(Constants::UserParam::SIGNIFICANCE_THRESHOLD), 42.0); // Test assignment operator PeptideIdentification id3; id3 = id; TEST_EQUAL(id3.getSignificanceThreshold(), 42.0); TEST_EQUAL(id3.getMetaValue(Constants::UserParam::SIGNIFICANCE_THRESHOLD), 42.0); } END_SECTION START_SECTION((String& getScoreType() const)) PeptideIdentification hits; TEST_EQUAL(hits.getScoreType(), "") END_SECTION START_SECTION((void setScoreType(const String& type))) PeptideIdentification hits; hits.setScoreType("bla"); TEST_EQUAL(hits.getScoreType(), "bla") END_SECTION START_SECTION((bool isHigherScoreBetter() const)) PeptideIdentification hits; TEST_TRUE(hits.isHigherScoreBetter()) END_SECTION START_SECTION((void setHigherScoreBetter(bool value))) PeptideIdentification hits; hits.setHigherScoreBetter(false); TEST_FALSE(hits.isHigherScoreBetter()) END_SECTION START_SECTION((const String& getIdentifier() const)) PeptideIdentification hits; TEST_EQUAL(hits.getIdentifier(),"") END_SECTION START_SECTION((void setIdentifier(const String& id))) PeptideIdentification hits; hits.setIdentifier("bla"); TEST_EQUAL(hits.getIdentifier(),"bla") END_SECTION START_SECTION((bool empty() const)) PeptideIdentification hits; TEST_TRUE(hits.empty()) hits.setSignificanceThreshold(1); TEST_FALSE(hits.empty()) hits.setSignificanceThreshold(0); TEST_TRUE(hits.empty()) hits.setBaseName("basename"); TEST_FALSE(hits.empty()) hits.setBaseName(""); TEST_TRUE(hits.empty()) hits.insertHit(peptide_hit); TEST_FALSE(hits.empty()) END_SECTION START_SECTION((void sort())) PeptideIdentification id; PeptideHit hit; hit.setScore(23); hit.setSequence(AASequence::fromString("SECONDPROTEIN")); id.insertHit(hit); hit.setScore(45); hit.setSequence(AASequence::fromString("FIRSTPROTEIN")); id.insertHit(hit); hit.setScore(7); hit.setSequence(AASequence::fromString("THIRDPROTEIN")); id.insertHit(hit); //higher score is better id.sort(); TEST_EQUAL(id.getHits()[0].getSequence(), AASequence::fromString("FIRSTPROTEIN")) TEST_EQUAL(id.getHits()[1].getSequence(), AASequence::fromString("SECONDPROTEIN")) TEST_EQUAL(id.getHits()[2].getSequence(), AASequence::fromString("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].getSequence(), AASequence::fromString("THIRDPROTEIN")) TEST_EQUAL(id.getHits()[1].getSequence(), AASequence::fromString("SECONDPROTEIN")) TEST_EQUAL(id.getHits()[2].getSequence(), AASequence::fromString("FIRSTPROTEIN")) TEST_EQUAL(id.getHits()[0].getScore(), 7) TEST_EQUAL(id.getHits()[1].getScore(), 23) TEST_EQUAL(id.getHits()[2].getScore(), 45) END_SECTION START_SECTION(static std::vector<PeptideHit> getReferencingHits(const std::vector<PeptideHit> & , const std::set<String> & accession)) { PeptideIdentification id; PeptideHit hit; vector< PeptideHit > peptide_hits; hit.setScore(23); hit.setSequence(AASequence::fromString("FIRSTPROTEIN")); PeptideEvidence pe; pe.setProteinAccession("TEST_PROTEIN1"); hit.addPeptideEvidence(pe); id.insertHit(hit); hit = PeptideHit(); hit.setScore(10); hit.setSequence(AASequence::fromString("SECONDPROTEIN")); pe.setProteinAccession("TEST_PROTEIN2"); hit.addPeptideEvidence(pe); id.insertHit(hit); hit = PeptideHit(); hit.setScore(11); hit.setSequence(AASequence::fromString("THIRDPROTEIN")); pe.setProteinAccession("TEST_PROTEIN2"); hit.addPeptideEvidence(pe); id.insertHit(hit); set<String> query_accession; query_accession.insert("TEST_PROTEIN2"); peptide_hits = PeptideIdentification::getReferencingHits(id.getHits(), query_accession); TEST_EQUAL(peptide_hits.size(), 2) TEST_EQUAL(peptide_hits[0].getSequence(), AASequence::fromString("SECONDPROTEIN")) TEST_EQUAL(peptide_hits[1].getSequence(), AASequence::fromString("THIRDPROTEIN")) query_accession.insert("TEST_PROTEIN3"); peptide_hits = PeptideIdentification::getReferencingHits(id.getHits(), query_accession); TEST_EQUAL(peptide_hits.size(), 2) TEST_EQUAL(peptide_hits[0].getSequence(), AASequence::fromString("SECONDPROTEIN")) TEST_EQUAL(peptide_hits[1].getSequence(), AASequence::fromString("THIRDPROTEIN")) } { PeptideIdentification id; PeptideHit hit; vector< PeptideHit > peptide_hits; hit.setScore(23); hit.setSequence(AASequence::fromString("FIRSTPROTEIN")); PeptideEvidence pe; pe.setProteinAccession("TEST_PROTEIN1"); hit.addPeptideEvidence(pe); id.insertHit(hit); hit = PeptideHit(); hit.setScore(10); hit.setSequence(AASequence::fromString("SECONDPROTEIN")); pe.setProteinAccession("TEST_PROTEIN2"); hit.addPeptideEvidence(pe); id.insertHit(hit); hit = PeptideHit(); hit.setScore(11); hit.setSequence(AASequence::fromString("THIRDPROTEIN")); pe.setProteinAccession("TEST_PROTEIN3"); hit.addPeptideEvidence(pe); id.insertHit(hit); set<String> query_accession; query_accession.insert("TEST_PROTEIN2"); query_accession.insert("TEST_PROTEIN3"); peptide_hits = PeptideIdentification::getReferencingHits(id.getHits(), query_accession); TEST_EQUAL(peptide_hits.size(), 2) TEST_EQUAL(peptide_hits[0].getSequence(), AASequence::fromString("SECONDPROTEIN")) TEST_EQUAL(peptide_hits[1].getSequence(), AASequence::fromString("THIRDPROTEIN")) } END_SECTION START_SECTION((static std::multimap<String, std::pair<Size, Size>> buildUIDsFromAllPepIDs(const ConsensusMap &cmap))) { ConsensusMap cmap; ConsensusXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_2.consensusXML"), cmap); std::multimap<String, std::pair<Size, Size>> map_of_UIDs = PeptideIdentification::buildUIDsFromAllPepIDs(cmap); auto b = map_of_UIDs.begin(); TEST_EQUAL(b->first, "file:///C:/Users/bielow/AppData/Local/Temp/20190911_110348_8204_1/Untitled_workflow/002_FileFilter/out/ES-0014b_2.mzML|spectrum=112") TEST_EQUAL(b->second.first, Size(-1)) TEST_EQUAL(b->second.second, 4) ++b; TEST_EQUAL(b->first, "file:///C:/Users/bielow/AppData/Local/Temp/20190911_110348_8204_1/Untitled_workflow/002_FileFilter/out/ES-0014b_2.mzML|spectrum=113") TEST_EQUAL(b->second.first, 11) TEST_EQUAL(b->second.second, 0) ++b; TEST_EQUAL(b->first, "file:///C:/Users/bielow/AppData/Local/Temp/20190911_110348_8204_1/Untitled_workflow/002_FileFilter/out/ES-0014b_2.mzML|spectrum=118") TEST_EQUAL(b->second.first, 4) TEST_EQUAL(b->second.second, 0) FeatureMap fmap; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_1.featureXML"), fmap); ProteinIdentification::Mapping mp_c(cmap.getProteinIdentifications()); const map<String, StringList>& identifier_to_msrunpath = mp_c.identifier_to_msrunpath; String uid_zero = PeptideIdentification::buildUIDFromPepID(cmap[0].getPeptideIdentifications()[0], identifier_to_msrunpath); String uid_one = PeptideIdentification::buildUIDFromPepID(cmap[0].getPeptideIdentifications()[1], identifier_to_msrunpath); String uid_two = PeptideIdentification::buildUIDFromPepID(cmap[0].getPeptideIdentifications()[2], identifier_to_msrunpath); TEST_EQUAL(uid_zero,"file:///C:/Users/bielow/AppData/Local/Temp/20190911_110348_8204_1/Untitled_workflow/002_FileFilter/out/ES-0014b_2.mzML|spectrum=219") TEST_EQUAL(uid_one, "file:///C:/Users/bielow/AppData/Local/Temp/20190911_110348_8204_1/Untitled_workflow/002_FileFilter/out/ES-0016_1.mzML|spectrum=33") TEST_EQUAL(uid_two, "file:///C:/Users/bielow/AppData/Local/Temp/20190911_110348_8204_1/Untitled_workflow/002_FileFilter/out/ES-0016_2_.mzML|spectrum=133") } END_SECTION START_SECTION((static String buildUIDFromPepID(const PeptideIdentification& pep_id,const std::map<String, StringList>& fidentifier_to_msrunpath))) { NOT_TESTABLE //Tested above } END_SECTION START_SECTION((const String& getBaseName() const)) PeptideIdentification id; TEST_EQUAL(id.getBaseName(), "") id.setBaseName("test_base_name"); TEST_EQUAL(id.getBaseName(), "test_base_name") // Test that it's stored as a MetaValue TEST_TRUE(id.metaValueExists(Constants::UserParam::BASE_NAME)) TEST_EQUAL(id.getMetaValue(Constants::UserParam::BASE_NAME), "test_base_name") END_SECTION START_SECTION((void setBaseName(const String& base_name))) PeptideIdentification id; // Test setting a non-empty base name id.setBaseName("test_base_name"); TEST_EQUAL(id.getBaseName(), "test_base_name") TEST_TRUE(id.metaValueExists(Constants::UserParam::BASE_NAME)) // Test setting an empty base name (should remove the meta value) id.setBaseName(""); TEST_EQUAL(id.getBaseName(), "") TEST_FALSE(id.metaValueExists(Constants::UserParam::BASE_NAME)) // Test that empty() method works correctly with base name as meta value TEST_TRUE(id.empty()) id.setBaseName("test_base_name"); TEST_FALSE(id.empty()) id.setBaseName(""); TEST_TRUE(id.empty()) END_SECTION START_SECTION((std::hash<PeptideIdentification>)) { // Test 1: Equal objects have equal hashes PeptideIdentification id1, id2; id1.setRT(123.456); id1.setMZ(789.012); id1.setIdentifier("test_id"); id1.setScoreType("Mascot"); id1.setHigherScoreBetter(true); id1.setSignificanceThreshold(0.05); id2.setRT(123.456); id2.setMZ(789.012); id2.setIdentifier("test_id"); id2.setScoreType("Mascot"); id2.setHigherScoreBetter(true); id2.setSignificanceThreshold(0.05); TEST_EQUAL(id1 == id2, true) TEST_EQUAL(std::hash<PeptideIdentification>{}(id1), std::hash<PeptideIdentification>{}(id2)) // Test 2: Different objects have different hashes (most likely) PeptideIdentification id3; id3.setRT(999.999); id3.setMZ(111.111); id3.setIdentifier("different_id"); TEST_EQUAL(id1 == id3, false) TEST_NOT_EQUAL(std::hash<PeptideIdentification>{}(id1), std::hash<PeptideIdentification>{}(id3)) // Test 3: Can use in unordered_set std::unordered_set<PeptideIdentification> id_set; id_set.insert(id1); id_set.insert(id2); // Should not increase size (equal to id1) id_set.insert(id3); TEST_EQUAL(id_set.size(), 2) // Test 4: Can use in unordered_map std::unordered_map<PeptideIdentification, std::string> id_map; id_map[id1] = "first"; id_map[id3] = "third"; TEST_EQUAL(id_map[id1], "first") TEST_EQUAL(id_map[id2], "first") // id2 == id1 TEST_EQUAL(id_map[id3], "third") // Test 5: PeptideIdentification with peptide hits PeptideIdentification id4, id5; PeptideHit hit1; hit1.setScore(50.0); hit1.setSequence(AASequence::fromString("PEPTIDE")); hit1.setCharge(2); PeptideHit hit2; hit2.setScore(50.0); hit2.setSequence(AASequence::fromString("PEPTIDE")); hit2.setCharge(2); id4.insertHit(hit1); id5.insertHit(hit2); TEST_EQUAL(id4 == id5, true) TEST_EQUAL(std::hash<PeptideIdentification>{}(id4), std::hash<PeptideIdentification>{}(id5)) // Test 6: Different peptide hits produce different hashes PeptideIdentification id6; PeptideHit hit3; hit3.setScore(99.0); hit3.setSequence(AASequence::fromString("DIFFERENT")); hit3.setCharge(3); id6.insertHit(hit3); TEST_EQUAL(id4 == id6, false) TEST_NOT_EQUAL(std::hash<PeptideIdentification>{}(id4), std::hash<PeptideIdentification>{}(id6)) // Test 7: NaN handling - both NaN should be equal and have same hash PeptideIdentification id7, id8; // RT and MZ are NaN by default TEST_EQUAL(id7.hasRT(), false) TEST_EQUAL(id7.hasMZ(), false) TEST_EQUAL(id7 == id8, true) TEST_EQUAL(std::hash<PeptideIdentification>{}(id7), std::hash<PeptideIdentification>{}(id8)) } END_SECTION END_TEST ///////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MSDataStoringConsumer_test.cpp
.cpp
3,814
125
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/DATAACCESS/MSDataStoringConsumer.h> #include <OpenMS/INTERFACES/IMSDataConsumer.h> /////////////////////////// #include <OpenMS/FORMAT/MzMLFile.h> START_TEST(MSDataStoringConsumer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; MSDataStoringConsumer* storing_consumer_ptr = nullptr; MSDataStoringConsumer* storing_consumer_nullPointer = nullptr; START_SECTION((MSDataStoringConsumer())) storing_consumer_ptr = new MSDataStoringConsumer(); TEST_NOT_EQUAL(storing_consumer_ptr, storing_consumer_nullPointer) END_SECTION START_SECTION((~MSDataStoringConsumer())) delete storing_consumer_ptr; END_SECTION START_SECTION((void consumeSpectrum(SpectrumType & s))) { MSDataStoringConsumer * storing_consumer = new MSDataStoringConsumer(); MSSpectrum s; s.setName("spec1"); s.setComment("comm1"); s.setRT(5); storing_consumer->consumeSpectrum(s); s.setName("spec2"); s.setComment("comm2"); s.setRT(15); storing_consumer->consumeSpectrum(s); s.setName("spec3"); s.setComment("comm3"); s.setRT(25); storing_consumer->consumeSpectrum(s); TEST_EQUAL(storing_consumer->getData().getNrSpectra(), 3); TEST_EQUAL(storing_consumer->getData().getNrChromatograms(), 0) TEST_EQUAL(storing_consumer->getData().getSpectra()[0].getName(), "spec1") TEST_EQUAL(storing_consumer->getData().getSpectra()[1].getName(), "spec2") TEST_EQUAL(storing_consumer->getData().getSpectra()[2].getName(), "spec3") TEST_EQUAL(storing_consumer->getData().getSpectra()[0].getComment(), "comm1") TEST_EQUAL(storing_consumer->getData().getSpectra()[1].getComment(), "comm2") TEST_EQUAL(storing_consumer->getData().getSpectra()[2].getComment(), "comm3") delete storing_consumer; } END_SECTION START_SECTION((void consumeChromatogram(ChromatogramType & c))) { MSDataStoringConsumer * storing_consumer = new MSDataStoringConsumer(); MSChromatogram c; c.setNativeID("testid"); storing_consumer->consumeChromatogram(c); TEST_EQUAL(storing_consumer->getData().getNrSpectra(), 0) TEST_EQUAL(storing_consumer->getData().getNrChromatograms(), 1) TEST_EQUAL(storing_consumer->getData().getChromatograms()[0].getNativeID(), "testid") delete storing_consumer; } END_SECTION START_SECTION((void setExpectedSize(Size, Size))) NOT_TESTABLE // tested above END_SECTION START_SECTION((void setExperimentalSettings(const ExperimentalSettings&))) { MSDataStoringConsumer * storing_consumer = new MSDataStoringConsumer(); storing_consumer->setExpectedSize(1,1); MSChromatogram c; c.setNativeID("testid"); storing_consumer->consumeChromatogram(c); MSSpectrum spec; spec.setName("spec1"); spec.setRT(5); storing_consumer->consumeSpectrum(spec); ExperimentalSettings s; s.setComment("mySettings"); storing_consumer->setExperimentalSettings(s); TEST_NOT_EQUAL(storing_consumer, storing_consumer_nullPointer) TEST_EQUAL(storing_consumer->getData().getNrSpectra(), 1) TEST_EQUAL(storing_consumer->getData().getNrChromatograms(), 1) TEST_EQUAL(storing_consumer->getData().getComment(), "mySettings") delete storing_consumer; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MSDataWritingConsumer_test.cpp
.cpp
1,933
99
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MSDataWritingConsumer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MSDataWritingConsumer* ptr = 0; MSDataWritingConsumer* null_ptr = 0; START_SECTION(MSDataWritingConsumer()) { ptr = new MSDataWritingConsumer(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~MSDataWritingConsumer()) { delete ptr; } END_SECTION START_SECTION((virtual void setExperimentalSettings(const ExperimentalSettings &exp))) { // TODO } END_SECTION START_SECTION((virtual void setExpectedSize(Size expectedSpectra, Size expectedChromatograms))) { // TODO } END_SECTION START_SECTION((virtual void consumeSpectrum(SpectrumType &s))) { // TODO } END_SECTION START_SECTION((virtual void consumeChromatogram(ChromatogramType &c))) { // TODO } END_SECTION START_SECTION((MSDataWritingConsumer(String filename))) { // TODO } END_SECTION START_SECTION((virtual ~MSDataWritingConsumer())) { // TODO } END_SECTION START_SECTION((virtual void addDataProcessing(DataProcessing d))) { // TODO } END_SECTION START_SECTION((virtual Size getNrSpectraWritten())) { // TODO } END_SECTION START_SECTION((virtual Size getNrChromatogramsWritten())) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FASTAFile_test.cpp
.cpp
12,227
310
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Nico Pfeifer, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <string> #include <fstream> // Required for temporary file creation #include <OpenMS/FORMAT/FASTAFile.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/CHEMISTRY/ModificationsDB.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <vector> /////////////////////////// START_TEST(FASTAFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; FASTAFile *ptr = nullptr; START_SECTION((FASTAFile())) ptr = new FASTAFile(); TEST_EQUAL(ptr == nullptr, false) END_SECTION START_SECTION((~FASTAFile())) delete (ptr); END_SECTION START_SECTION([FASTAFile::FASTAEntry] FASTAEntry()) FASTAFile::FASTAEntry *ptr_e; ptr_e = new FASTAFile::FASTAEntry(); TEST_EQUAL(ptr_e == nullptr, false) delete ptr_e; END_SECTION START_SECTION([FASTAFile::FASTAEntry] FASTAEntry(String id, String desc, String seq)) FASTAFile::FASTAEntry entry("ID", "DESC", "DAVLDELNER"); TEST_EQUAL(entry.identifier, "ID") TEST_EQUAL(entry.description, "DESC") TEST_EQUAL(entry.sequence, "DAVLDELNER") END_SECTION START_SECTION([FASTAFile::FASTAEntry] bool operator==(const FASTAEntry &rhs) const) FASTAFile::FASTAEntry entry1("ID", "DESC", "DAV*LDELNER"); FASTAFile::FASTAEntry entry2("ID", "DESC", "DAV*LDELNER"); FASTAFile::FASTAEntry entry3("ID2", "DESC", "DAV*LDELNER"); TEST_TRUE(entry1 == entry2) TEST_EQUAL(entry1 == entry3, false) END_SECTION START_SECTION((void load(const String &filename, std::vector<FASTAEntry> &data))) vector<FASTAFile::FASTAEntry> data; FASTAFile file; TEST_EXCEPTION(Exception::FileNotFound, file.load("FASTAFile_test_this_file_does_not_exist", data)) file.load(OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta"), data); vector<FASTAFile::FASTAEntry>::const_iterator sequences_iterator = data.begin(); TEST_EQUAL(data.size(), 5) TEST_EQUAL(sequences_iterator->identifier, String("P68509|1433F_BOVIN")) TEST_EQUAL(sequences_iterator->description, String("This is the description of the first protein")) TEST_EQUAL(sequences_iterator->sequence, String("GDREQLLQRARLAEQAERYDDMASAMKAVTEL") + String("NEPLSNEDRNLLSVAYKNVVGARRSSWRVISSIEQKTMADGNEKKLEKVKAYREKIEKELETVC") + String("NDVLALLDKFLIKNCNDFQYESKVFYLKMKGDYYRYLAEVASGEKKNSVVEASEAAYKEAFEIS") + String("KEHMQPTHPIRLGLALNFSVFYYEIQNAPEQACLLAKQAFDDAIAELDTLNEDSYKDSTLIMQL") + String("LRDNLTLWTSDQQDEEAGEGN")) sequences_iterator++; TEST_EQUAL(sequences_iterator->identifier, "Q9CQV8|1433B_MOUSE") TEST_EQUAL(sequences_iterator->sequence, String("TMDKSELVQKAKLAEQAERYDDMAAAMKAVTE") + String("QGHELSNEERNLLSVAYKNVVGARRSSWRVISSIEQKTERNEKKQQMGKEYREKIEAELQDICND") + String("VLELLDKYLILNATQAESKVFYLKMKGDYFRYLSEVASGENKQTTVSNSQQAYQEAFEISKKEMQ") + String("PTHPIRLGLALNFSVFYYEILNSPEKACSLAKTAFDEAIAELDTLNEESYKDSTLIMQLLRDNLT") + String("LWTSENQGDEGDAGEGEN")) sequences_iterator++; TEST_EQUAL(sequences_iterator->identifier, "sp|P31946|1433B_HUMAN") TEST_EQUAL(sequences_iterator->description, String("14-3-3 protein beta/alpha OS=Homo sapiens GN=YWHAB PE=1 SV=3")) TEST_EQUAL(sequences_iterator->sequence, String("MTMDKSELVQKAKLAEQAERYDDMAAAMKAVTEQGHELSNEERNLLSVAYKNVVGARRSS") + String("WRVISSIEQKTERNEKKQQMGKEYREKIEAELQDICNDVLELLDKYLIPNATQPESKVFY") + String("LKMKGDYFRYLSEVASGDNKQTTVSNSQQAYQEAFEISKKEMQPTHPIRLGLALNFSVFY") + String("YEILNSPEKACSLAKTAFDEAIAELDTLNEESYKDSTLIMQLLRDNLTLWTSENQGDEGD") + String("AGEGEN")) sequences_iterator++; TEST_EQUAL(sequences_iterator->identifier, "sp|P00000|0000A_UNKNOWN") TEST_EQUAL(sequences_iterator->description, String("Artificially modified version of sp|P31946|1433B_HUMAN")) TEST_EQUAL(sequences_iterator->sequence, String("(ICPL:13C(6))MTMDKSELVQKAKLAEQAERYDDMAAAMKAVTEQGHELSNEERNLLSVAYKNVVGARRSS") + String("WRVISSIEQKTERNEKKQQMGKEYREKIEAELQDICNDVLELLDKYLIPNATQPESKVFY") + String("LKMKGDYFRYLSEVASGDNKQTTVSNSQQAYQEAFEISKKEMQPTHPIRLGLALNFSVFY") + String("YEILNSPEKACSLAKTAFDEAIAELDTLNEESYKDSTLIMQLLRDNLTLWTSENQGDEGD") + String("AGEGEN")) // Test modified sequence conversion AASequence aa = AASequence::fromString(sequences_iterator->sequence); TEST_EQUAL(aa.toUnmodifiedString(), String("MTMDKSELVQKAKLAEQAERYDDMAAAMKAVTEQGHELSNEERNLLSVAYKNVVGARRSS") + String("WRVISSIEQKTERNEKKQQMGKEYREKIEAELQDICNDVLELLDKYLIPNATQPESKVFY") + String("LKMKGDYFRYLSEVASGDNKQTTVSNSQQAYQEAFEISKKEMQPTHPIRLGLALNFSVFY") + String("YEILNSPEKACSLAKTAFDEAIAELDTLNEESYKDSTLIMQLLRDNLTLWTSENQGDEGD") + String("AGEGEN")) TEST_EQUAL(aa.isModified(), true) String expectedModification = ModificationsDB::getInstance()->getModification("ICPL:13C(6)", "", ResidueModification::N_TERM)->getId(); TEST_EQUAL(aa.getNTerminalModificationName(), expectedModification) sequences_iterator++; TEST_EQUAL(sequences_iterator->identifier, "test") TEST_EQUAL(sequences_iterator->description, String(" ##0")) TEST_EQUAL(sequences_iterator->sequence, String("GSMTVDMQEIGSTEMPYEVPTQPNATSASAGRGWFDGPSFKVPSVPTRPSGIFRRPSRIKPEFSFKEKVSELVS") + String("PAVYTFGLFVQNASESLTSDDPSDVPTQRTFKSDFQSVGSMTVDMQEIGSTEMPYEVPTQ") + String("PNATSASAGRGWFDGPSFKVPSVPTRPSGIFRRPSRIKPEFSFKEKVSELVSPAVYTFGL") + String("FVQNASESLTSDDPSDVPTQRTFKSDFQSVAXXSTFDFYQRRLVTLAESPRAPSPGSMTV") + String("DMQEIGSTEMPYEVPTQPNATSASAGRGWFDGPSFKVPSVPTRPSGIFRRPSRIKPEFSF") + String("KEKVSELVSPAVYTFGLFVQNASESLTSDDPSDVPTQRTFKSDFQSV")) END_SECTION START_SECTION((void store(const String &filename, const std::vector<FASTAEntry> &data) const)) vector<FASTAFile::FASTAEntry> data, data2; String tmp_filename; NEW_TMP_FILE(tmp_filename); FASTAFile file; file.load(OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta"), data); TEST_EXCEPTION(Exception::UnableToCreateFile, file.store("/bla/bluff/blblb/sdfhsdjf/test.txt", data)) file.store(tmp_filename, data); file.load(tmp_filename, data2); TEST_TRUE(data == data2); END_SECTION START_SECTION(test_leading_whitespace_and_peff) { String tmp_filename; NEW_TMP_FILE(tmp_filename); // Create test file with leading whitespace and PEFF headers { ofstream f(tmp_filename.c_str()); f << "\n"; // Empty line f << " \n"; // Whitespace line f << "# PEFF header 1\n"; // PEFF comment f << "# PEFF header 2\n"; // PEFF comment f << " \t\n"; // Whitespace line f << ">TEST_HEADER Test description\n"; f << "SEQ\n"; } vector<FASTAFile::FASTAEntry> data; FASTAFile file; file.load(tmp_filename, data); TEST_EQUAL(data.size(), 1) if (!data.empty()) // CORRECTED: No semicolon here { TEST_EQUAL(data[0].identifier, "TEST_HEADER") TEST_EQUAL(data[0].description, "Test description") TEST_EQUAL(data[0].sequence, "SEQ") } } END_SECTION START_SECTION(test_empty_lines_between_entries) { String tmp_filename; NEW_TMP_FILE(tmp_filename); // Create test file with empty lines between entries { ofstream f(tmp_filename.c_str()); f << ">Header1\n"; f << "SEQ1\n"; f << "\n\n"; // Multiple empty lines f << ">Header2\n"; f << "SEQ2\n"; } vector<FASTAFile::FASTAEntry> data; FASTAFile file; file.load(tmp_filename, data); TEST_EQUAL(data.size(), 2) if (data.size() == 2) // CORRECTED: No semicolon here { TEST_EQUAL(data[0].identifier, "Header1") TEST_EQUAL(data[0].sequence, "SEQ1") TEST_EQUAL(data[1].identifier, "Header2") TEST_EQUAL(data[1].sequence, "SEQ2") } } END_SECTION START_SECTION([EXTRA] test_strange_symbols_in_sequence) // test if * is read correctly (not changed into something weird like 'X') String tmp_filename; NEW_TMP_FILE(tmp_filename); FASTAFile file; vector<FASTAFile::FASTAEntry> data, data2; FASTAFile::FASTAEntry temp_entry; temp_entry.identifier = String("P68509|1433F_BOVIN"); temp_entry.description = String("This is the description of the first protein"); temp_entry.sequence = String("GDREQLLQRAR*LAEQ*AERYDDMASAMKAVTEL"); data.push_back(temp_entry); data.push_back(temp_entry); // twice file.store(tmp_filename, data); file.load(tmp_filename, data2); ABORT_IF(data2.size() != 2); TEST_EQUAL(data2[0] == temp_entry, true); TEST_EQUAL(data2[1] == temp_entry, true); END_SECTION START_SECTION([EXTRA] test_strange_symbols_in_sequence) // test if * is read correctly (not changed into something weird like 'X') String tmp_filename; NEW_TMP_FILE(tmp_filename); FASTAFile file; vector<FASTAFile::FASTAEntry> data, data2; FASTAFile::FASTAEntry temp_entry; temp_entry.identifier = String("P68509|1433F_BOVIN"); temp_entry.description = String("This is the description of the first protein"); temp_entry.sequence = String("GDREQLLQRAR*LAEQ*AERYDDMASAMKAVTEL"); data.push_back(temp_entry); data.push_back(temp_entry); // twice file.store(tmp_filename, data); file.load(tmp_filename, data2); ABORT_IF(data2.size() != 2); TEST_EQUAL(data2[0] == temp_entry, true); TEST_EQUAL(data2[1] == temp_entry, true); END_SECTION START_SECTION(test_white_spaces) //test if spaces and tabulators are removed correctly String tmp_filename; NEW_TMP_FILE(tmp_filename); FASTAFile file; vector<FASTAFile::FASTAEntry> data, data2; FASTAFile::FASTAEntry temp_entry; temp_entry.identifier = String("P68509|1433F_BOVIN"); temp_entry.description = String("This is the description of the first protein"); temp_entry.sequence = String("GDREQLLQRAR LAEQ\tAERYDDMASAMKAVTEL"); data.push_back(temp_entry); file.store(tmp_filename, data); file.load(tmp_filename, data2); ABORT_IF(data2.size() != 1); TEST_EQUAL(data2[0].sequence == string("GDREQLLQRARLAEQAERYDDMASAMKAVTEL"), true); END_SECTION START_SECTION([EXTRA] test_position) // test if setPosition() works correctly String tmp_filename; NEW_TMP_FILE(tmp_filename); FASTAFile file; vector<pair<streampos, FASTAFile::FASTAEntry>> data1; vector<pair<streampos, FASTAFile::FASTAEntry>> data2; FASTAFile::FASTAEntry temp_entry; file.readStart(OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta")); for (int i = 0; i < 4; i++) { file.readNext(temp_entry); data1.push_back(std::make_pair(file.position(), temp_entry)); } file.setPosition(data1[0].first); for (int i = 0; i < 3; i++) { file.readNext(temp_entry); data2.push_back(std::make_pair(file.position(), temp_entry)); } ABORT_IF(data1.size() != 4 || data2.size() != 3); for (Size i = 1; i < data1.size(); i++) { TEST_EQUAL(data1[i].second.identifier, data2[i - 1].second.identifier); TEST_EQUAL(data1[i].second.description, data2[i - 1].second.description); TEST_EQUAL(data1[i].second.sequence, data2[i - 1].second.sequence); TEST_EQUAL(data1[i].first, data2[i - 1].first); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ILPDCWrapper_test.cpp
.cpp
1,854
74
// 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/ANALYSIS/DECHARGING/ILPDCWrapper.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/ChargePair.h> #include <OpenMS/DATASTRUCTURES/MassExplainer.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> using namespace OpenMS; using namespace std; START_TEST(ILPDCWrapper, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ILPDCWrapper* ptr = nullptr; ILPDCWrapper* null_ptr = nullptr; START_SECTION(ILPDCWrapper()) { ptr = new ILPDCWrapper(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(virtual ~ILPDCWrapper()) { delete ptr; } END_SECTION START_SECTION((double compute(const FeatureMap fm, PairsType &pairs, Size verbose_level) const)) { EmpiricalFormula ef("H1"); Adduct a(+1, 1, ef.getMonoWeight(), "H1", 0.1, 0, ""); MassExplainer::AdductsType potential_adducts_; potential_adducts_.push_back(a); MassExplainer me(potential_adducts_, 1, 3, 2, 0, 0); FeatureMap fm; ILPDCWrapper::PairsType pairs; ILPDCWrapper iw; iw.compute(fm, pairs, 1); // check that it runs without pairs (i.e. all clusters are singletons) TEST_EQUAL(pairs.size(), 0); // real data test } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Acquisition_test.cpp
.cpp
3,052
118
// 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/Acquisition.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(Acquisition, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Acquisition* ptr = nullptr; Acquisition* nullPointer = nullptr; START_SECTION(Acquisition()) ptr = new Acquisition(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~Acquisition()) delete ptr; END_SECTION START_SECTION(const String& getIdentifier() const) Acquisition tmp; TEST_EQUAL(tmp.getIdentifier(), ""); END_SECTION START_SECTION(void setIdentifier(const String& identifier)) Acquisition tmp; tmp.setIdentifier("5"); TEST_EQUAL(tmp.getIdentifier(), "5"); END_SECTION START_SECTION(Acquisition(const Acquisition& source)) Acquisition tmp; tmp.setIdentifier("5"); tmp.setMetaValue("label",String("label")); Acquisition tmp2(tmp); TEST_EQUAL(tmp2.getIdentifier(), "5"); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); END_SECTION START_SECTION(Acquisition(Acquisition&&) = default) Acquisition e, empty; e.setIdentifier("Ident"); Acquisition ef(e); Acquisition ef2(e); TEST_FALSE(ef == empty) // the move target should be equal, while the move source should be empty Acquisition ef_mv(std::move(ef)); TEST_TRUE(ef_mv == ef2) TEST_TRUE(ef == empty) TEST_EQUAL(ef.getIdentifier().empty(), true) END_SECTION START_SECTION(Acquisition& operator= (const Acquisition& source)) Acquisition tmp,tmp2,tmp3; // assignment of a modified object tmp2.setIdentifier("5"); tmp2.setMetaValue("label",String("label")); tmp = tmp2; TEST_EQUAL(tmp.getIdentifier(), "5"); TEST_EQUAL((String)(tmp.getMetaValue("label")), String("label")); // assignment of a default-constructed object tmp = tmp3; TEST_EQUAL(tmp.getIdentifier(), ""); TEST_EQUAL(tmp.isMetaEmpty(), true); END_SECTION START_SECTION(bool operator== (const Acquisition& rhs) const) Acquisition tmp,tmp2; TEST_TRUE(tmp == tmp2); tmp2.setIdentifier("5"); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setMetaValue("label",String("label")); TEST_EQUAL(tmp==tmp2, false); END_SECTION START_SECTION(bool operator!= (const Acquisition& rhs) const) Acquisition tmp,tmp2; TEST_EQUAL(tmp!=tmp2, false); tmp2.setIdentifier("5"); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setMetaValue("label",String("label")); TEST_FALSE(tmp == tmp2); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ExtendedIsotopeFitter1D_test.cpp
.cpp
2,794
95
// 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/ExtendedIsotopeFitter1D.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ExtendedIsotopeFitter1D, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ExtendedIsotopeFitter1D* ptr = nullptr; ExtendedIsotopeFitter1D* nullPointer = nullptr; START_SECTION(ExtendedIsotopeFitter1D()) { ptr = new ExtendedIsotopeFitter1D(); TEST_EQUAL(ptr->getName(), "ExtendedIsotopeFitter1D") TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((ExtendedIsotopeFitter1D(const ExtendedIsotopeFitter1D &source))) ExtendedIsotopeFitter1D eisof1; 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( "charge", 1 ); param.setValue( "isotope:stdev", 0.04 ); param.setValue( "isotope:maximum", 20 ); eisof1.setParameters(param); ExtendedIsotopeFitter1D eisof2(eisof1); ExtendedIsotopeFitter1D eisof3; eisof3.setParameters(param); eisof1 = ExtendedIsotopeFitter1D(); TEST_EQUAL(eisof3.getParameters(), eisof2.getParameters()) END_SECTION START_SECTION((virtual ~ExtendedIsotopeFitter1D())) delete ptr; END_SECTION START_SECTION((virtual ExtendedIsotopeFitter1D& operator=(const ExtendedIsotopeFitter1D &source))) ExtendedIsotopeFitter1D eisof1; 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( "charge", 1 ); param.setValue( "isotope:stdev", 0.04 ); param.setValue( "isotope:maximum", 20 ); eisof1.setParameters(param); ExtendedIsotopeFitter1D eisof2; eisof2 = eisof1; ExtendedIsotopeFitter1D eisof3; eisof3.setParameters(param); eisof1 = ExtendedIsotopeFitter1D(); TEST_EQUAL(eisof3.getParameters(), eisof3.getParameters()) END_SECTION START_SECTION((QualityType fit1d(const RawDataArrayType &range, InterpolationModel *&model))) // dummy subtest TODO TEST_EQUAL(1,1) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MzTab_test.cpp
.cpp
4,299
149
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Timo Sachsenberg$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/MzTab.h> /////////////////////////// START_TEST(MzTab, "$Id$") using namespace OpenMS; using namespace std; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MzTab* ptr = nullptr; MzTab* null_ptr = nullptr; START_SECTION(MzTab()) { ptr = new MzTab(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~MzTab()) { delete ptr; } END_SECTION START_SECTION(std::vector<String> getPSMOptionalColumnNames() const) { MzTab mztab; MzTabPSMSectionRow row; MzTabPSMSectionRows rows; MzTabString s; MzTabOptionalColumnEntry e; // row 1 ////////////////////// row.sequence.fromCellString("NDYKAPPQPAPGK"); row.PSM_ID.fromCellString("38"); row.accession.fromCellString("IPI:B1"); row.unique.fromCellString("1"); row.database.fromCellString("null"); row.database_version.fromCellString("null"); row.search_engine.fromCellString("[, , Percolator, ]"); row.search_engine_score[0].fromCellString("51.9678841193106"); e.first = "Percolator_score"; s.fromCellString("0.359083"); e.second = s; row.opt_.push_back(e); e.first = "Percolator_qvalue"; s.fromCellString("0.00649874"); e.second = s; row.opt_.push_back(e); e.first = "Percolator_PEP"; s.fromCellString("0.0420992"); e.second = s; row.opt_.push_back(e); e.first = "search_engine_sequence"; s.fromCellString("NDYKAPPQPAPGK"); e.second = s; row.opt_.push_back(e); rows.push_back(row); // row 2 ////////////////////// row.sequence.fromCellString("IRRS(Phospho)SFSSK"); row.PSM_ID.fromCellString("39"); row.accession.fromCellString("IPI:IPI00009899.4"); row.unique.fromCellString("0"); row.database.fromCellString("null"); row.database_version.fromCellString("null"); row.search_engine.fromCellString("[, , Percolator, ]"); row.search_engine_score[0].fromCellString("9.55915773892318"); e.first = "Percolator_score"; s.fromCellString("0.157068"); e.second = s; row.opt_.push_back(e); e.first = "Percolator_qvalue"; s.fromCellString("0.00774619"); e.second = s; row.opt_.push_back(e); e.first = "Percolator_PEP"; s.fromCellString("0.0779777"); e.second = s; row.opt_.push_back(e); e.first = "search_engine_sequence"; s.fromCellString("IRRSSFS(Phospho)SK"); e.second = s; row.opt_.push_back(e); e.first = "AScore_1"; s.fromCellString("3.64384830671351"); e.second = s; row.opt_.push_back(e); rows.push_back(row); mztab.setPSMSectionRows(rows); // Tests /////////////////////////////// vector<String> optional_columns = mztab.getPSMOptionalColumnNames(); TEST_EQUAL(mztab.getPSMSectionRows().size(),2) TEST_EQUAL(optional_columns.size(),5) } END_SECTION START_SECTION(static void addMetaInfoToOptionalColumns(const std::set<String>& keys, std::vector<MzTabOptionalColumnEntry>& opt, const String& id, const MetaInfoInterface& meta)) { // keys will have spaces replaced with underscore std::set<String> keys{ "FWHM", "with space", "ppm_errors" }; // values should remain as they are MetaInfoInterface meta; meta.setMetaValue("FWHM", 34.5); DataValue dv(DoubleList{ 0.5, 1.4, -2.0, 0.1 }); meta.setMetaValue("ppm_errors", dv); std::vector<MzTabOptionalColumnEntry> opt; MzTab::addMetaInfoToOptionalColumns(keys, opt, "global", meta); TEST_EQUAL(opt.size(), 3) TEST_EQUAL(opt[0].first, "opt_global_FWHM"); TEST_EQUAL(opt[1].first, "opt_global_ppm_errors"); TEST_EQUAL(opt[2].first, "opt_global_with_space"); TEST_EQUAL(opt[0].second.toCellString(), "34.5"); TEST_EQUAL(opt[1].second.toCellString(), "[0.5, 1.4, -2.0, 0.1]"); TEST_EQUAL(opt[2].second.toCellString(), "null"); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DataStructures_test.cpp
.cpp
1,035
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/INTERFACES/DataStructures.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(DataStructures, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// DataStructures* ptr = 0; DataStructures* null_ptr = 0; START_SECTION(DataStructures()) { ptr = new DataStructures(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~DataStructures()) { delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SpectrumAlignmentScore_test.cpp
.cpp
3,150
118
// 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/SpectrumAlignmentScore.h> #include <OpenMS/PROCESSING/SCALING/Normalizer.h> #include <OpenMS/FORMAT/DTAFile.h> /////////////////////////// START_TEST(SpectrumAlignmentScore, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; SpectrumAlignmentScore* ptr = nullptr; SpectrumAlignmentScore* nullPointer = nullptr; START_SECTION(SpectrumAlignmentScore()) ptr = new SpectrumAlignmentScore(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(double operator () (const PeakSpectrum& spec1, const PeakSpectrum& spec2) const) PeakSpectrum s1, s2; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s2); Normalizer normalizer; Param p(normalizer.getParameters()); p.setValue("method", "to_one"); normalizer.setParameters(p); normalizer.filterSpectrum(s1); normalizer.filterSpectrum(s2); TOLERANCE_ABSOLUTE(0.01) double score = (*ptr)(s1, s2); TEST_REAL_SIMILAR(score, 1.48268) s2.resize(100); score = (*ptr)(s1, s2); normalizer.filterSpectrum(s2); TEST_REAL_SIMILAR(score, 3.82472) END_SECTION START_SECTION(virtual ~SpectrumAlignmentScore()) delete ptr; END_SECTION ptr = new SpectrumAlignmentScore(); START_SECTION(SpectrumAlignmentScore(const SpectrumAlignmentScore &source)) SpectrumAlignmentScore sas1; Param p(sas1.getParameters()); p.setValue("tolerance", 0.2); sas1.setParameters(p); SpectrumAlignmentScore sas2(sas1); TEST_EQUAL(sas1.getName(), sas2.getName()) TEST_EQUAL(sas1.getParameters(), sas2.getParameters()) END_SECTION START_SECTION(SpectrumAlignmentScore& operator=(const SpectrumAlignmentScore &source)) SpectrumAlignmentScore sas1; Param p(sas1.getParameters()); p.setValue("tolerance", 0.2); sas1.setParameters(p); SpectrumAlignmentScore sas2; sas2 = sas1; TEST_EQUAL(sas1.getName(), sas2.getName()) TEST_EQUAL(sas1.getParameters(), sas2.getParameters()) END_SECTION START_SECTION(double operator()(const PeakSpectrum &spec) const) PeakSpectrum s1; DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1); Normalizer normalizer; Param p(normalizer.getParameters()); p.setValue("method", "to_one"); normalizer.setParameters(p); normalizer.filterSpectrum(s1); double score = (*ptr)(s1); TEST_REAL_SIMILAR(score, 1.48268); END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConsoleUtils_test.cpp
.cpp
5,440
164
// 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/ConsoleUtils.h> /////////////////////////// using namespace OpenMS; using namespace std; const int TEST_CONSOLE_WIDTH = 9; namespace OpenMS { struct ConsoleWidthTest { ConsoleWidthTest() { auto& t = ConsoleUtils::getInstance(); // make sure the singleton is initialized const_cast<ConsoleUtils&>(t).console_width_ = TEST_CONSOLE_WIDTH; } }; ConsoleWidthTest instance; // set console width! } // namespace OpenMS START_TEST(ConsoleUtils, "$Id$") // test this first, because all the other tests rely on it START_SECTION(int getConsoleWidth() const) { auto& t = ConsoleUtils::getInstance(); TEST_EQUAL(t.getConsoleWidth(), TEST_CONSOLE_WIDTH) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(ConsoleUtils()) { NOT_TESTABLE // private } END_SECTION START_SECTION(~ConsoleUtils()) { NOT_TESTABLE } END_SECTION START_SECTION(static const ConsoleUtils& getInstance()) { NOT_TESTABLE // tested below } END_SECTION const String x20(TEST_CONSOLE_WIDTH * 2 + 1, 'x'); // test string (2 full lines plus one 'x') const String xC(TEST_CONSOLE_WIDTH, 'x'); // full console width of 'x' START_SECTION((static StringList breakStringList(const String& input, const Size indentation, const Size max_lines, const Size first_line_prefill = 0))) { // we actually test the concatenation using breakString() since its easier to write String broken_string; { // test with indent = 0 broken_string = ConsoleUtils::breakString(x20, 0, 10); TEST_EQUAL(broken_string, xC + '\n' + xC + '\n' + "x") } { // try again ... broken_string = ConsoleUtils::breakString(x20, 0, 10); TEST_EQUAL(broken_string, xC + '\n' + xC + '\n' + "x") } { // test with indent = 3 int indent = 3; String shortX(TEST_CONSOLE_WIDTH - indent, 'x'); String s_indent(indent, ' '); broken_string = ConsoleUtils::breakString(x20, indent, 10); TEST_EQUAL(broken_string, xC + '\n' + s_indent + shortX + '\n' + s_indent + "xxxx") } { // test with prefilled first line int indent = 3; int prefill = 5; String firstX(TEST_CONSOLE_WIDTH - prefill, 'x'); String shortX(TEST_CONSOLE_WIDTH - indent, 'x'); String s_indent(indent, ' '); broken_string = ConsoleUtils::breakString(x20, indent, 10, prefill); TEST_EQUAL(broken_string, firstX + '\n' // 4x + s_indent + shortX + '\n' //+6x + s_indent + shortX + '\n' //+6x + s_indent + "xxx") //+3x } { // test with manual linebreaks in between { // just a linebreak int indent = 0; int prefill = 0; broken_string = ConsoleUtils::breakString("\n", indent, 10, prefill); TEST_EQUAL(broken_string, '\n') } { // just a linebreak with indent int indent = 3; int prefill = 0; broken_string = ConsoleUtils::breakString("\n", indent, 10, prefill); TEST_EQUAL(broken_string, '\n' + String(indent, ' ')) } { // prefilled linebreak with indent (should not make a difference) int indent = 3; int prefill = 5; broken_string = ConsoleUtils::breakString("\n", indent, 10, prefill); TEST_EQUAL(broken_string, '\n' + String(indent, ' ')) } { // text with a linebreak with indent and prefill int indent = 3; int prefill = TEST_CONSOLE_WIDTH - 1; // one char left on first line broken_string = ConsoleUtils::breakString("xxx\n", indent, 10, prefill); TEST_EQUAL(broken_string, "x\n" + String(indent, ' ') + "xx\n" + String(indent, ' ')) } { // some corner cases (only one char per line) int indent = TEST_CONSOLE_WIDTH - 1; int prefill = indent; // one char left on first line broken_string = ConsoleUtils::breakString("xxx\n", indent, 10, prefill); TEST_EQUAL(broken_string, "x\n" + String(indent, ' ') + "x\n" + String(indent, ' ') + "x\n" + String(indent, ' ') + "\n" // manual linebreak right after breakString()'s linebreak -- you get two lines ... + String(indent, ' ')) } } { // test max_lines int indent = TEST_CONSOLE_WIDTH - 2; int prefill = indent; // two chars per EVERY line broken_string = ConsoleUtils::breakString(String(99, 'x'), indent, 3, prefill); TEST_EQUAL(broken_string, "xx\n" + String(indent, ' ') + "...\n" + String(indent, ' ') + 'x') } } END_SECTION START_SECTION(static String breakString(const String& input, const Size indentation, const Size max_lines, const Size first_line_prefill = 0)) { NOT_TESTABLE // tested above } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FileHandler_test.cpp
.cpp
16,939
284
// 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/FileHandler.h> #include <OpenMS/FORMAT/FileTypes.h> /////////////////////////// #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> START_TEST(FileHandler, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; START_SECTION((static FileTypes::Type getTypeByFileName(const String &filename))) FileHandler tmp; TEST_EQUAL(tmp.getTypeByFileName("test.bla"), FileTypes::UNKNOWN) TEST_EQUAL(tmp.getTypeByFileName("test.dta"), FileTypes::DTA) TEST_EQUAL(tmp.getTypeByFileName("test.DTA2D"), FileTypes::DTA2D) TEST_EQUAL(tmp.getTypeByFileName("test.MzData"), FileTypes::MZDATA) TEST_EQUAL(tmp.getTypeByFileName("test.MZXML"), FileTypes::MZXML) TEST_EQUAL(tmp.getTypeByFileName("test.featureXML"), FileTypes::FEATUREXML) TEST_EQUAL(tmp.getTypeByFileName("test.idXML"), FileTypes::IDXML) TEST_EQUAL(tmp.getTypeByFileName("test.consensusXML"), FileTypes::CONSENSUSXML) TEST_EQUAL(tmp.getTypeByFileName("test.mGf"), FileTypes::MGF) TEST_EQUAL(tmp.getTypeByFileName("test.ini"), FileTypes::INI) TEST_EQUAL(tmp.getTypeByFileName("test.toPPas"), FileTypes::TOPPAS) TEST_EQUAL(tmp.getTypeByFileName("test.TraFoXML"), FileTypes::TRANSFORMATIONXML) TEST_EQUAL(tmp.getTypeByFileName("test.MzML"), FileTypes::MZML) TEST_EQUAL(tmp.getTypeByFileName(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompressed.mzML.bz2")), FileTypes::MZML) TEST_EQUAL(tmp.getTypeByFileName(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompressed.mzML.gz")), FileTypes::MZML) TEST_EQUAL(tmp.getTypeByFileName("test.mS2"), FileTypes::MS2) TEST_EQUAL(tmp.getTypeByFileName("test.pepXML"), FileTypes::PEPXML) TEST_EQUAL(tmp.getTypeByFileName("test.pep.xml"), FileTypes::PEPXML) TEST_EQUAL(tmp.getTypeByFileName("test.protXML"), FileTypes::PROTXML) TEST_EQUAL(tmp.getTypeByFileName("test.prot.xml"), FileTypes::PROTXML) TEST_EQUAL(tmp.getTypeByFileName("test.mzid"), FileTypes::MZIDENTML) TEST_EQUAL(tmp.getTypeByFileName("test.GELML"), FileTypes::GELML) TEST_EQUAL(tmp.getTypeByFileName("test.TRAML"), FileTypes::TRAML) TEST_EQUAL(tmp.getTypeByFileName("test.MSP"), FileTypes::MSP) TEST_EQUAL(tmp.getTypeByFileName("test.OMSSAXML"), FileTypes::OMSSAXML) TEST_EQUAL(tmp.getTypeByFileName("test.png"), FileTypes::PNG) TEST_EQUAL(tmp.getTypeByFileName("./foo.bar/XMass/fid"), FileTypes::XMASS); TEST_EQUAL(tmp.getTypeByFileName("test.TSV"), FileTypes::TSV) TEST_EQUAL(tmp.getTypeByFileName("test.PEPLIST"), FileTypes::PEPLIST) TEST_EQUAL(tmp.getTypeByFileName("test.HARDKLOER"), FileTypes::HARDKLOER) TEST_EQUAL(tmp.getTypeByFileName("test.fasta"), FileTypes::FASTA) TEST_EQUAL(tmp.getTypeByFileName("test.EDTA"), FileTypes::EDTA) TEST_EQUAL(tmp.getTypeByFileName("test.csv"), FileTypes::CSV) TEST_EQUAL(tmp.getTypeByFileName("test.txt"), FileTypes::TXT) END_SECTION START_SECTION((static bool hasValidExtension(const String& filename, const FileTypes::Type type))) TEST_EQUAL(FileHandler::hasValidExtension("test.bla", FileTypes::UNKNOWN), true) TEST_EQUAL(FileHandler::hasValidExtension("test.idXML", FileTypes::IDXML), true) TEST_EQUAL(FileHandler::hasValidExtension("test.consensusXML", FileTypes::CONSENSUSXML), true) // tmp (UNKNOWN) TEST_EQUAL(FileHandler::hasValidExtension("test.tmp", FileTypes::UNKNOWN), true) TEST_EQUAL(FileHandler::hasValidExtension("test.tmp", FileTypes::IDXML), true) TEST_EQUAL(FileHandler::hasValidExtension("test.tmp", FileTypes::CONSENSUSXML), true) // known other file type TEST_EQUAL(FileHandler::hasValidExtension("test.consensusXML", FileTypes::IDXML), false) TEST_EQUAL(FileHandler::hasValidExtension("test.idXML", FileTypes::CONSENSUSXML), false) END_SECTION START_SECTION((static FileTypes::Type getTypeByContent(const String &filename))) FileHandler tmp; TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData")), FileTypes::MZDATA) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML")), FileTypes::MZXML) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML")), FileTypes::MZML) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompressed.mzML.bz2")), FileTypes::MZML) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompressed.mzML.gz")), FileTypes::MZML) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("MzIdentML_3runs.mzid")), FileTypes::MZIDENTML) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_1.featureXML")), FileTypes::FEATUREXML) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_1.consensusXML")), FileTypes::CONSENSUSXML) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("IdXMLFile_whole.idXML")), FileTypes::IDXML) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("DTAFile_test.dta")), FileTypes::DTA) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d")), FileTypes::DTA2D) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_2.dta2d")), FileTypes::DTA2D) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("class_test_infile.txt")), FileTypes::UNKNOWN) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("TransformationXMLFile_1.trafoXML")), FileTypes::TRANSFORMATIONXML) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta")), FileTypes::FASTA) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("FileHandler_toppas.toppas")), FileTypes::TOPPAS) TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("FileHandler_MGFbyContent1.mgf")), FileTypes::MGF) // detect via 'FORMAT=Mascot generic\n' TEST_EQUAL(tmp.getTypeByContent(OPENMS_GET_TEST_DATA_PATH("FileHandler_MGFbyContent2.mgf")), FileTypes::MGF) // detect via 'BEGIN IONS\n' TEST_EXCEPTION(Exception::FileNotFound, tmp.getTypeByContent("/bli/bla/bluff")) END_SECTION START_SECTION((static FileTypes::Type getType(const String &filename))) FileHandler tmp; TEST_EQUAL(tmp.getType(OPENMS_GET_TEST_DATA_PATH("header_file.h")), FileTypes::UNKNOWN) TEST_EQUAL(tmp.getType(OPENMS_GET_TEST_DATA_PATH("class_test_infile.txt")), FileTypes::TXT) TEST_EQUAL(tmp.getType(OPENMS_GET_TEST_DATA_PATH("IdXMLFile_whole.idXML")), FileTypes::IDXML) TEST_EQUAL(tmp.getType(OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile.consensusXML")), FileTypes::CONSENSUSXML) TEST_EQUAL(tmp.getType(OPENMS_GET_TEST_DATA_PATH("TransformationXMLFile_1.trafoXML")), FileTypes::TRANSFORMATIONXML) TEST_EQUAL(tmp.getType(OPENMS_GET_TEST_DATA_PATH("FileHandler_toppas.toppas")), FileTypes::TOPPAS) TEST_EQUAL(tmp.getType(OPENMS_GET_TEST_DATA_PATH("pepnovo.txt")), FileTypes::TXT) TEST_EXCEPTION(Exception::FileNotFound, tmp.getType("/bli/bla/bluff")) END_SECTION START_SECTION((static String stripExtension(const String& file))) TEST_STRING_EQUAL(FileHandler::stripExtension(""), "") TEST_STRING_EQUAL(FileHandler::stripExtension(".unknown"), "") TEST_STRING_EQUAL(FileHandler::stripExtension(".idXML"), "") TEST_STRING_EQUAL(FileHandler::stripExtension("/home/doe/file"), "/home/doe/file") TEST_STRING_EQUAL(FileHandler::stripExtension("/home/doe/file.txt"), "/home/doe/file") TEST_STRING_EQUAL(FileHandler::stripExtension("/home/doe/file.mzML.gz"), "/home/doe/file") // special extension, known to OpenMS TEST_STRING_EQUAL(FileHandler::stripExtension("/home/doe/file.txt.tgz"), "/home/doe/file.txt") // not special to us... just strip the last one TEST_STRING_EQUAL(FileHandler::stripExtension("/home/doe/file.unknown"), "/home/doe/file") TEST_STRING_EQUAL(FileHandler::stripExtension("/home.with.dot/file"), "/home.with.dot/file") TEST_STRING_EQUAL(FileHandler::stripExtension("c:\\home.with.dot\\file"), "c:\\home.with.dot\\file") TEST_STRING_EQUAL(FileHandler::stripExtension("./filename"), "./filename") END_SECTION START_SECTION((static String swapExtension(const String& filename, const FileTypes::Type new_type))) TEST_STRING_EQUAL(FileHandler::swapExtension("", FileTypes::UNKNOWN), ".unknown") TEST_STRING_EQUAL(FileHandler::swapExtension(".unknown", FileTypes::UNKNOWN), ".unknown") TEST_STRING_EQUAL(FileHandler::swapExtension(".idXML", FileTypes::UNKNOWN), ".unknown") TEST_STRING_EQUAL(FileHandler::swapExtension("/home/doe/file", FileTypes::UNKNOWN), "/home/doe/file.unknown") TEST_STRING_EQUAL(FileHandler::swapExtension("/home/doe/file.txt", FileTypes::FEATUREXML), "/home/doe/file.featureXML") TEST_STRING_EQUAL(FileHandler::swapExtension("/home/doe/file.mzML.gz", FileTypes::IDXML), "/home/doe/file.idXML") // special extension, known to OpenMS TEST_STRING_EQUAL(FileHandler::swapExtension("/home/doe/file.txt.tgz", FileTypes::UNKNOWN), "/home/doe/file.txt.unknown") // not special to us... just strip the last one TEST_STRING_EQUAL(FileHandler::swapExtension("/home/doe/file.unknown", FileTypes::UNKNOWN), "/home/doe/file.unknown") TEST_STRING_EQUAL(FileHandler::swapExtension("/home.with.dot/file", FileTypes::UNKNOWN), "/home.with.dot/file.unknown") TEST_STRING_EQUAL(FileHandler::swapExtension("c:\\home.with.dot\\file", FileTypes::UNKNOWN), "c:\\home.with.dot\\file.unknown") TEST_STRING_EQUAL(FileHandler::swapExtension("./filename", FileTypes::UNKNOWN), "./filename.unknown") END_SECTION START_SECTION((FileTypes::Type FileHandler::getConsistentOutputfileType(const String& output_filename, const String& requested_type))) TEST_EQUAL(FileHandler::getConsistentOutputfileType("", ""), FileTypes::UNKNOWN) TEST_EQUAL(FileHandler::getConsistentOutputfileType("a.unknown", "weird"), FileTypes::UNKNOWN) TEST_EQUAL(FileHandler::getConsistentOutputfileType("a.idXML", ""), FileTypes::IDXML) TEST_EQUAL(FileHandler::getConsistentOutputfileType("/home/doe/file.txt", ""), FileTypes::TXT) TEST_EQUAL(FileHandler::getConsistentOutputfileType("/home/doe/file.txt", "featureXML"), FileTypes::UNKNOWN) TEST_EQUAL(FileHandler::getConsistentOutputfileType("/home/doe/file.mzML.gz", ""), FileTypes::MZML) // special extension, known to OpenMS TEST_EQUAL(FileHandler::getConsistentOutputfileType("/home/doe/file.mzML.gz", "mzML"), FileTypes::MZML) // special extension, known to OpenMS TEST_EQUAL(FileHandler::getConsistentOutputfileType("/home/doe/file.txt.tgz", ""), FileTypes::UNKNOWN) // not special to us... TEST_EQUAL(FileHandler::getConsistentOutputfileType("/home/doe/file.unknown", "idxml"), FileTypes::IDXML) TEST_EQUAL(FileHandler::getConsistentOutputfileType("/home.with.dot/file", "mzML"), FileTypes::MZML) TEST_EQUAL(FileHandler::getConsistentOutputfileType("c:\\home.with.dot\\file", "mzML"), FileTypes::MZML) END_SECTION START_SECTION((template < class PeakType > bool loadExperiment(const String &filename, MSExperiment< PeakType > &exp, FileTypes::Type force_type=FileTypes::UNKNOWN, ProgressLogger::LogType log=ProgressLogger::NONE, const bool compute_hash=true))) FileHandler tmp; PeakMap exp; TEST_EXCEPTION(Exception::FileNotFound, tmp.loadExperiment("test.bla", exp)) tmp.loadExperiment(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), exp); TEST_REAL_SIMILAR(exp[1][0].getPosition()[0], 110) TEST_REAL_SIMILAR(exp[1][1].getPosition()[0], 120) TEST_REAL_SIMILAR(exp[1][2].getPosition()[0], 130) // starts with 110, so this one should skip the first tmp.getOptions().setMZRange(DRange<1>(115, 1000)); tmp.loadExperiment(OPENMS_GET_TEST_DATA_PATH("MzDataFile_1.mzData"), exp); TEST_REAL_SIMILAR(exp[1][0].getPosition()[0], 120) TEST_REAL_SIMILAR(exp[1][1].getPosition()[0], 130) tmp.getOptions() = PeakFileOptions(); tmp.loadExperiment(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"), exp); TEST_REAL_SIMILAR(exp[2][0].getPosition()[0], 100) TEST_REAL_SIMILAR(exp[2][1].getPosition()[0], 110) TEST_REAL_SIMILAR(exp[2][2].getPosition()[0], 120) tmp.getOptions().setMZRange(DRange<1>(115, 1000)); tmp.loadExperiment(OPENMS_GET_TEST_DATA_PATH("MzXMLFile_1.mzXML"), exp); TEST_REAL_SIMILAR(exp[2][0].getPosition()[0], 120) TEST_REAL_SIMILAR(exp[2][1].getPosition()[0], 130) TEST_REAL_SIMILAR(exp[2][2].getPosition()[0], 140) tmp.getOptions() = PeakFileOptions(); tmp.loadExperiment(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp, {FileTypes::MZML}, OpenMS::ProgressLogger::NONE, true, true); TEST_EQUAL(exp.size(), 4) TEST_STRING_EQUAL(exp.getSourceFiles()[0].getChecksum(), "36007593dbca0ba59a1f4fc32fb970f0e8991fa6") TEST_EQUAL(exp.getSourceFiles()[0].getChecksumType(), SourceFile::ChecksumType::SHA1) tmp.getOptions() = PeakFileOptions(); tmp.loadExperiment(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"), exp); TEST_REAL_SIMILAR(exp[0][0].getPosition()[0], 230.02) TEST_REAL_SIMILAR(exp[0][1].getPosition()[0], 430.02) TEST_REAL_SIMILAR(exp[0][2].getPosition()[0], 630.02) tmp.getOptions().setMZRange(DRange<1>(300, 1000)); tmp.loadExperiment(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"), exp, {FileTypes::DTA2D}, OpenMS::ProgressLogger::NONE, true, true); TEST_REAL_SIMILAR(exp[0][0].getPosition()[0], 430.02) TEST_REAL_SIMILAR(exp[0][1].getPosition()[0], 630.02) TEST_STRING_EQUAL(exp.getSourceFiles()[0].getChecksum(), "d50d5144cc3805749b9e8d16f3bc8994979d8142") TEST_EQUAL(exp.getSourceFiles()[0].getChecksumType(), SourceFile::ChecksumType::SHA1) // disable hash computation tmp.loadExperiment(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"), exp, {}, ProgressLogger::NONE, true, false); TEST_STRING_EQUAL(exp.getSourceFiles()[0].getChecksum(), "") TEST_EQUAL(exp.getSourceFiles()[0].getChecksumType(), SourceFile::ChecksumType::UNKNOWN_CHECKSUM) // Test that we fail if given a known bogus type restriction TEST_EXCEPTION(Exception::ParseError, tmp.loadExperiment(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"), exp, {FileTypes::SIZE_OF_TYPE}, ProgressLogger::NONE, true, false)) END_SECTION START_SECTION((static String computeFileHash(const String& filename))) PeakMap exp; FileHandler tmp; // Test that we load with the correct file type restriction tmp.loadExperiment(OPENMS_GET_TEST_DATA_PATH("DTA2DFile_test_1.dta2d"), exp, {FileTypes::DTA2D}, ProgressLogger::NONE, true, true); // compute hash TEST_STRING_EQUAL(exp.getSourceFiles()[0].getChecksum(), "d50d5144cc3805749b9e8d16f3bc8994979d8142") END_SECTION START_SECTION((static bool isSupported(FileTypes::Type type))) FileHandler tmp; TEST_EQUAL(false, tmp.isSupported(FileTypes::UNKNOWN)); TEST_EQUAL(true, tmp.isSupported(FileTypes::DTA)); TEST_EQUAL(true, tmp.isSupported(FileTypes::DTA2D)); TEST_EQUAL(true, tmp.isSupported(FileTypes::MZDATA)); TEST_EQUAL(true, tmp.isSupported(FileTypes::MZML)); TEST_EQUAL(true, tmp.isSupported(FileTypes::MZXML)); TEST_EQUAL(true, tmp.isSupported(FileTypes::XMASS)); TEST_EQUAL(true, tmp.isSupported(FileTypes::FEATUREXML)); END_SECTION START_SECTION((const PeakFileOptions &getOptions() const)) FileHandler a; TEST_EQUAL(a.getOptions().hasMSLevels(), false) END_SECTION START_SECTION((PeakFileOptions & getOptions())) FileHandler a; a.getOptions().addMSLevel(1); TEST_EQUAL(a.getOptions().hasMSLevels(), true); END_SECTION START_SECTION((template <class FeatureType> bool loadFeatures(const String &filename, FeatureMap<FeatureType>&map, FileTypes::Type force_type = FileTypes::UNKNOWN))) FileHandler tmp; FeatureMap map; TEST_EXCEPTION(Exception::FileNotFound, tmp.loadFeatures("test.bla", map)) tmp.loadFeatures(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), map); TEST_EQUAL(map.size(), 7); tmp.loadFeatures(OPENMS_GET_TEST_DATA_PATH("FeatureXMLFile_2_options.featureXML"), map); TEST_EQUAL(map.size(), 7); END_SECTION START_SECTION((void storeExperiment(const String &filename, const MSExperiment<>&exp, ProgressLogger::LogType log = ProgressLogger::NONE))) FileHandler fh; PeakMap exp; fh.loadExperiment(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp); //test mzML String filename, filename2; NEW_TMP_FILE_EXT(filename, ".mzML"); fh.storeExperiment(filename, exp, {FileTypes::MZML}, ProgressLogger::NONE); TEST_EQUAL(fh.getTypeByContent(filename), FileTypes::MZML) //Test that we throw an exception when given a bogus type restriction TEST_EXCEPTION(Exception::InvalidFileType, fh.storeExperiment(filename, exp, {FileTypes::SIZE_OF_TYPE})) //other types cannot be tested, because the NEW_TMP_FILE template does not support file extensions... END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++