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/GridBasedCluster_test.cpp | .cpp | 3,110 | 95 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/ML/CLUSTERING/GridBasedCluster.h>
#include <OpenMS/DATASTRUCTURES/DRange.h>
#include <OpenMS/KERNEL/StandardTypes.h>
using namespace OpenMS;
START_TEST(GridBasedCluster, "$Id$")
GridBasedCluster::Point position(4.5, 5.5);
GridBasedCluster::Rectangle box(position,position);
std::vector<int> points;
points.push_back(1);
points.push_back(6);
points.push_back(2);
int propA = 1;
std::vector<int> propB;
propB.push_back(1);
propB.push_back(2);
propB.push_back(3);
GridBasedCluster* nullPointer = nullptr;
GridBasedCluster* ptr;
START_SECTION(GridBasedCluster(const Point ¢re, const Rectangle &bounding_box, const std::vector<int> &point_indices, const int &property_A, const std::vector<int> &properties_B))
GridBasedCluster cluster(position, box, points, propA, propB);
TEST_EQUAL(cluster.getCentre().getX(), 4.5);
ptr = new GridBasedCluster(position, box, points, propA, propB);
TEST_NOT_EQUAL(ptr, nullPointer);
delete ptr;
END_SECTION
START_SECTION(GridBasedCluster(const Point ¢re, const Rectangle &bounding_box, const std::vector<int> &point_indices))
GridBasedCluster cluster(position, box, points);
TEST_EQUAL(cluster.getCentre().getX(), 4.5);
ptr = new GridBasedCluster(position, box, points);
TEST_NOT_EQUAL(ptr, nullPointer);
delete ptr;
END_SECTION
GridBasedCluster cluster(position, box, points, propA, propB);
START_SECTION(Point getCentre() const)
TEST_EQUAL(cluster.getCentre().getX(), 4.5);
TEST_EQUAL(cluster.getCentre().getY(), 5.5);
END_SECTION
START_SECTION(Rectangle getBoundingBox() const)
TEST_EQUAL(cluster.getBoundingBox().minX(), 4.5);
TEST_EQUAL(cluster.getBoundingBox().maxY(), 5.5);
END_SECTION
START_SECTION(std::vector<int> getPoints() const)
TEST_EQUAL(cluster.getPoints()[0], 1);
TEST_EQUAL(cluster.getPoints()[2], 2);
END_SECTION
START_SECTION(int getPropertyA() const)
TEST_EQUAL(cluster.getPropertyA(), 1);
END_SECTION
START_SECTION(std::vector<int> getPropertiesB() const)
TEST_EQUAL(cluster.getPropertiesB()[0], 1);
TEST_EQUAL(cluster.getPropertiesB()[2], 3);
END_SECTION
GridBasedCluster::Point position1(4.5, 5.5);
GridBasedCluster::Point position2(4.5, 6.5);
GridBasedCluster cluster1(position1, box, points, propA, propB);
GridBasedCluster cluster2(position2, box, points, propA, propB);
START_SECTION(bool operator<(GridBasedCluster other) const)
TEST_EQUAL(cluster1 < cluster2, true);
END_SECTION
START_SECTION(bool operator>(GridBasedCluster other) const)
TEST_EQUAL(cluster2 > cluster1, true);
END_SECTION
START_SECTION(bool operator==(GridBasedCluster other) const)
TEST_TRUE(cluster1 == cluster1);
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IMTypes_test.cpp | .cpp | 4,945 | 159 | // 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/IONMOBILITY/IMTypes.h>
#include <OpenMS/IONMOBILITY/IMDataConverter.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FORMAT/MzMLFile.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(MSRunIMSplitter, "$Id$")
/////////////////////////////////////////////////////////////
IMTypes* e_ptr = nullptr;
IMTypes* e_nullPointer = nullptr;
START_SECTION((IMTypes()))
e_ptr = new IMTypes;
TEST_NOT_EQUAL(e_ptr, e_nullPointer)
END_SECTION
START_SECTION((~IMTypes()))
delete e_ptr;
END_SECTION
START_SECTION((DriftTimeUnit toDriftTimeUnit(const String& dtu_string)))
TEST_EQUAL(toDriftTimeUnit("<NONE>") == DriftTimeUnit::NONE, true)
for (size_t i = 0; i < (size_t)DriftTimeUnit::SIZE_OF_DRIFTTIMEUNIT; ++i)
{
TEST_EQUAL((size_t)toDriftTimeUnit(NamesOfDriftTimeUnit[i]), i)
}
TEST_EXCEPTION(Exception::InvalidValue, toDriftTimeUnit("haha"));
END_SECTION
START_SECTION(const String& driftTimeUnitToString(const DriftTimeUnit value))
TEST_EQUAL(driftTimeUnitToString(DriftTimeUnit::NONE), "<NONE>")
for (size_t i = 0; i < (size_t)DriftTimeUnit::SIZE_OF_DRIFTTIMEUNIT; ++i)
{
TEST_EQUAL(driftTimeUnitToString(DriftTimeUnit(i)), NamesOfDriftTimeUnit[i])
}
TEST_EXCEPTION(Exception::InvalidValue, driftTimeUnitToString(DriftTimeUnit::SIZE_OF_DRIFTTIMEUNIT));
END_SECTION
START_SECTION((IMFormat toIMFormat(const String& IM_format)))
TEST_EQUAL(toIMFormat("none") == IMFormat::NONE, true)
for (size_t i = 0; i < (size_t) IMFormat::SIZE_OF_IMFORMAT; ++i)
{
TEST_EQUAL((size_t) toIMFormat(NamesOfIMFormat[i]), i)
}
TEST_EXCEPTION(Exception::InvalidValue, toIMFormat("haha"));
END_SECTION
START_SECTION(const String& imFormatToString(const IMFormat value))
TEST_EQUAL(imFormatToString(IMFormat::NONE), "none")
for (size_t i = 0; i < (size_t)IMFormat::SIZE_OF_IMFORMAT; ++i)
{
TEST_EQUAL(imFormatToString(IMFormat(i)), NamesOfIMFormat[i])
}
TEST_EXCEPTION(Exception::InvalidValue, imFormatToString(IMFormat::SIZE_OF_IMFORMAT));
END_SECTION
// single IM value for whole spec
const MSSpectrum IMwithDrift = [&]() {
MSSpectrum spec;
spec.setDriftTime(123.4);
spec.setDriftTimeUnit(DriftTimeUnit::VSSC);
return spec;
}();
// convert to IM-Frame with float meta-data array
const MSSpectrum IMwithFDA = [&]() {
MSExperiment exp;
exp.addSpectrum(IMwithDrift);
auto single = IMDataConverter::reshapeIMFrameToSingle(exp);
return single[0];
}();
START_SECTION(static IMFormat determineIMFormat(const MSExperiment& exp))
TEST_EQUAL(IMTypes::determineIMFormat(MSExperiment()) == IMFormat::NONE, true)
{
MSExperiment exp;
exp.addSpectrum(MSSpectrum());
exp.addSpectrum(MSSpectrum());
TEST_EQUAL(IMTypes::determineIMFormat(exp) == IMFormat::NONE, true)
}
{
MSExperiment exp;
exp.addSpectrum(MSSpectrum());
exp.addSpectrum(IMwithDrift);
TEST_EQUAL(IMTypes::determineIMFormat(exp) == IMFormat::MULTIPLE_SPECTRA, true)
}
{
MSExperiment exp;
exp.addSpectrum(MSSpectrum());
exp.addSpectrum(IMwithFDA);
TEST_EQUAL(IMTypes::determineIMFormat(exp) == IMFormat::CONCATENATED, true)
}
{
MSExperiment exp;
exp.addSpectrum(IMwithDrift);
exp.addSpectrum(IMwithFDA);
TEST_EQUAL(IMTypes::determineIMFormat(exp) == IMFormat::MIXED, true)
}
{
// set both ... is valid (typically concatenated + some average value)
auto IMwithFDA2 = IMwithFDA;
IMwithFDA2.setDriftTime(123.4);
MSExperiment exp;
exp.addSpectrum(IMwithDrift);
exp.addSpectrum(IMwithFDA);
exp.addSpectrum(IMwithFDA2);
TEST_EQUAL(IMTypes::determineIMFormat(exp) == IMFormat::MIXED, true)
}
END_SECTION
START_SECTION(static IMFormat determineIMFormat(const MSSpectrum& spec))
TEST_EQUAL(IMTypes::determineIMFormat(MSSpectrum()) == IMFormat::NONE, true)
// single IM value for whole spec
TEST_EQUAL(IMTypes::determineIMFormat(IMwithDrift) == IMFormat::MULTIPLE_SPECTRA, true)
// convert to IM-Frame with float meta-data array
TEST_EQUAL(IMTypes::determineIMFormat(IMwithFDA) == IMFormat::CONCATENATED, true)
// set both ... is valid (typically concatenated + some average value)
auto IMwithFDA2 = IMwithFDA;
IMwithFDA2.setDriftTime(123.4);
TEST_EQUAL(IMTypes::determineIMFormat(IMwithFDA2) == IMFormat::CONCATENATED, true)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/BinnedSpectrumCompareFunctor_test.cpp | .cpp | 1,949 | 80 | // 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/BinnedSpectrumCompareFunctor.h>
using namespace OpenMS;
using namespace std;
START_TEST(BinnedSpectrumCompareFunctor, "$Id$")
/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
START_SECTION(BinnedSpectrumCompareFunctor())
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(~BinnedSpectrumCompareFunctor())
{
NOT_TESTABLE
}
END_SECTION
//interface class is not testable
START_SECTION((BinnedSpectrumCompareFunctor(const BinnedSpectrumCompareFunctor &source)))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((BinnedSpectrumCompareFunctor& operator=(const BinnedSpectrumCompareFunctor &source)))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((virtual double operator()(const BinnedSpectrum &spec1, const BinnedSpectrum &spec2) const =0))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((virtual double operator()(const BinnedSpectrum &spec) const =0))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([BinnedSpectrumCompareFunctor::IncompatibleBinning] IncompatibleBinning(const char *file, int line, const char *function, const char *message="compared spectra have different settings in binsize and/or binspread")))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([BinnedSpectrumCompareFunctor::IncompatibleBinning] virtual ~IncompatibleBinning()))
{
NOT_TESTABLE
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/CsvFile_test.cpp | .cpp | 4,208 | 140 | // 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/CsvFile.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/DATASTRUCTURES/ListUtilsIO.h>
#include <OpenMS/SYSTEM/File.h>
///////////////////////////
START_TEST(DTAFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
CsvFile* ptr = nullptr;
CsvFile* nullPointer = nullptr;
START_SECTION(CsvFile())
ptr = new CsvFile;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~CsvFile())
delete ptr;
END_SECTION
#if 0
// Something is terribly wrong here ... looks like an unintentional commit?
START_SECTION(CsvFile(const String& filename, char is = ',',bool ie = false, Int first_n = -1))
//tested in getRow
TEST_EXCEPTION(Exception::FileNotFound, CsvFile("CsvFile_1.csv"))
END_SECTION
START_SECTION(void load(const String& filename, char is = ',', bool ie = false, Int first_n = -1))
//tested in getRow
TEST_EXCEPTION(Exception::FileNotFound, f1.load("CsvFile_1.csv"))
END_SECTION
#endif
START_SECTION(bool getRow(Size row,StringList &list))
TOLERANCE_ABSOLUTE(0.01)
CsvFile f1,f3,f4;
CsvFile f2(OPENMS_GET_TEST_DATA_PATH("CsvFile_1.csv"), '\t');
StringList list;
f2.getRow(0,list);
TEST_EQUAL(list,ListUtils::create<String>("hello,world"))
f2.getRow(1,list);
TEST_EQUAL(list,ListUtils::create<String>("the,dude"))
f2.getRow(2,list);
TEST_EQUAL(list,ListUtils::create<String>("spectral,search"))
f3.load(OPENMS_GET_TEST_DATA_PATH("CsvFile_1.csv"),'\t');
f3.getRow(0,list);
TEST_EQUAL(list,ListUtils::create<String>("hello,world"))
f3.getRow(1,list);
TEST_EQUAL(list,ListUtils::create<String>("the,dude"))
f3.getRow(2,list);
TEST_EQUAL(list,ListUtils::create<String>("spectral,search"))
f4.load(OPENMS_GET_TEST_DATA_PATH("CsvFile_2.csv"),'\t',true);
f4.getRow(0,list);
TEST_EQUAL(list,ListUtils::create<String>("hello,world"))
f4.getRow(1,list);
TEST_EQUAL(list,ListUtils::create<String>("the,dude"))
f4.getRow(2,list);
TEST_EQUAL(list,ListUtils::create<String>("spectral,search"))
END_SECTION
START_SECTION(void store(const String& filename))
CsvFile f1,f2;
StringList list;
f1.load(OPENMS_GET_TEST_DATA_PATH("CsvFile_2.csv"), '\t', true); // load from a file
String tmpfile = File::getTemporaryFile();
f1.store(tmpfile); // store into a new one
f2.load(tmpfile, '\t', true); // load the new one
f2.getRow(0,list);
TEST_EQUAL(list,ListUtils::create<String>("hello,world"))
f2.getRow(1,list);
TEST_EQUAL(list,ListUtils::create<String>("the,dude"))
f2.getRow(2,list);
TEST_EQUAL(list,ListUtils::create<String>("spectral,search"))
END_SECTION
START_SECTION(void addRow(const StringList& list))
CsvFile f1, f2;
StringList list;
f1.addRow(ListUtils::create<String>("first,second,third"));
f1.addRow(ListUtils::create<String>("4,5,6"));
String tmpfile = File::getTemporaryFile();
f1.store(tmpfile);
f2.load(tmpfile, ',', false);
f2.getRow(0,list);
TEST_EQUAL(list, ListUtils::create<String>("first,second,third"))
f2.getRow(1,list);
TEST_EQUAL(list, ListUtils::create<String>("4,5,6"))
END_SECTION
START_SECTION(void clear())
CsvFile f1;
StringList list;
f1.addRow(ListUtils::create<String>("hello,world"));
f1.getRow(0, list);
TEST_EQUAL(list, ListUtils::create<String>("hello,world"))
f1.clear();
TEST_EXCEPTION(Exception::InvalidIterator, f1.getRow(0, list))
END_SECTION
START_SECTION(std::vector<String>::size_type CsvFile::rowCount())
CsvFile f1(OPENMS_GET_TEST_DATA_PATH("CsvFile_1.csv"), '\t');
// file has 5 lines, 2 of them comments
TEST_EQUAL(f1.rowCount(),3)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MzTabM_test.cpp | .cpp | 14,383 | 343 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Oliver Alka$
// $Authors: Oliver Alka$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/MzTabM.h>
#include <OpenMS/FORMAT/OMSFile.h>
#include <OpenMS/METADATA/ID/IdentificationDataConverter.h>
///////////////////////////
START_TEST(MzTabM, "$Id$")
using namespace OpenMS;
using namespace std;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MzTabM* ptr = nullptr;
MzTabM* null_ptr = nullptr;
START_SECTION(MzTabM())
{
ptr = new MzTabM();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~MzTabM())
{
delete ptr;
}
END_SECTION
START_SECTION(Fill data structure)
{
MzTabM mztabm;
// SML Small molecule section row
MzTabMSmallMoleculeSectionRows sml_rows;
MzTabMSmallMoleculeSectionRow sml_row;
sml_row.sml_identifier.fromCellString(1);
sml_row.smf_id_refs.fromCellString("1,2");
sml_row.database_identifier.fromCellString("[HMDB:HMDB0001847]");
sml_row.chemical_formula.fromCellString("[C17H20N4O2]");
sml_row.smiles.fromCellString("[C1=CC=C(C=C1)CCNC(=O)CCNNC(=O)C2=CC=NC=C2]");
sml_row.inchi.fromCellString("[InChI=1S/C17H20N4O2/c22-16(19-12-6-14-4-2-1-3-5-14)9-13-20-21-17(23)15-7-10-18-11-8-15/h1-5,7-8,10-11,20H,6,9,12-13H2,(H,19,22)(H,21,23)]");
sml_row.chemical_name.fromCellString("[N-(2-phenylethyl)-3-[2-(pyridine-4-carbonyl)hydrazinyl]propanamide]");
sml_row.uri.fromCellString("[http://www.hmdb.ca/metabolites/HMDB0001847]");
vector<MzTabDouble> tnm = {MzTabDouble(312.17)};
sml_row.theoretical_neutral_mass.set(tnm);
sml_row.adducts.fromCellString("[[M+H]1+]");
sml_row.reliability.set("3");
sml_row.best_id_confidence_measure.fromCellString("[MS, MS:1000752, TOPP Software,]");
sml_row.best_id_confidence_value.set(0.4);
MzTabOptionalColumnEntry e;
MzTabString s;
e.first = "SIRIUS_TREE_score";
s.fromCellString("-10.59083");
e.second = s;
sml_row.opt_.emplace_back(e);
e.first = "SIRIUS_explained_intensity_score";
s.fromCellString("96.67");
e.second = s;
sml_row.opt_.emplace_back(e);
e.first = "SIRIUS_ISO_score";
s.fromCellString("0.0649874");
e.second = s;
sml_row.opt_.emplace_back(e);
sml_rows.emplace_back(sml_row);
// SMF Small molecule feature section
MzTabMSmallMoleculeFeatureSectionRows smf_rows;
MzTabMSmallMoleculeFeatureSectionRow smf_row;
smf_row.smf_identifier.fromCellString(1);
smf_row.sme_id_refs.fromCellString("1");
smf_row.sme_id_ref_ambiguity_code.fromCellString("null");
smf_row.adduct.fromCellString("[M+H]1+");
smf_row.isotopomer.setNull(true);
smf_row.exp_mass_to_charge.set(313.1689);
smf_row.charge.set(1);
smf_row.retention_time.set(156.0); // is always in seconds
smf_row.rt_start.set(152.2);
smf_row.rt_end.set(163.4);
smf_rows.emplace_back(smf_row);
// SME Small molecule evidence section
MzTabMSmallMoleculeEvidenceSectionRows sme_rows;
MzTabMSmallMoleculeEvidenceSectionRow sme_row;
sme_row.sme_identifier.set(1);
sme_row.evidence_input_id.set("1234.5_156.0");
sme_row.database_identifier.set("HMDB:HMDB0001847");
sme_row.chemical_formula.set("C17H20N4O2");
sme_row.smiles.set("C1=CC=C(C=C1)CCNC(=O)CCNNC(=O)C2=CC=NC=C2");
sme_row.inchi.set("InChI=1S/C17H20N4O2/c22-16(19-12-6-14-4-2-1-3-5-14)9-13-20-21-17(23)15-7-10-18-11-8-15/h1-5,7-8,10-11,20H,6,9,12-13H2,(H,19,22)(H,21,23)");
sme_row.chemical_name.set("N-(2-phenylethyl)-3-[2-(pyridine-4-carbonyl)hydrazinyl]propanamide");
sme_row.uri.set("http://www.hmdb.ca/metabolites/HMDB0001847");
sme_row.derivatized_form.isNull();
sme_row.adduct.set("[M+H]1+");
sme_row.exp_mass_to_charge.set(313.1689);
sme_row.charge.set(1);
sme_row.calc_mass_to_charge.set(313.1665);
MzTabSpectraRef sp_ref;
sp_ref.setMSFile(1);
sp_ref.setSpecRef("index=5");
sme_row.spectra_ref = sp_ref;
sme_row.identification_method.fromCellString("[MS, MS:1000752, TOPP Software,]");
sme_row.ms_level.fromCellString("[MS, MS:1000511, ms level, 1]");
sme_row.id_confidence_measure[0] = MzTabDouble(123);
sme_row.rank.set(1);
e.first = "SIRIUS_TREE_score";
s.fromCellString("-10.59083");
e.second = s;
sme_row.opt_.emplace_back(e);
e.first = "SIRIUS_explained_intensity_score";
s.fromCellString("96.67");
e.second = s;
sme_row.opt_.emplace_back(e);
e.first = "SIRIUS_ISO_score";
s.fromCellString("0.0649874");
e.second = s;
sme_row.opt_.emplace_back(e);
sme_rows.emplace_back(sme_row);
// Metadata for MzTab-M
MzTabMMetaData mztabm_meta;
mztabm_meta.mz_tab_id.set("local_identifier");
mztabm_meta.title.set("SML_ROW_TEST");
mztabm_meta.description.set("small_molecule_section_row_test");
// sample proceessing
MzTabParameterList sp;
sp.fromCellString("[MS, MS:1000544, Conversion to mzML, ]|[MS, MS:1000035, Peak picking, ]|[MS, MS:1000594, Low intensity data point removal, ]");
mztabm_meta.sample_processing[0] = sp;
// instrument
MzTabInstrumentMetaData meta_instrument;
meta_instrument.name.fromCellString("[MS, MS:1000483, Thermo Fisher Scientific instrument model, LTQ Orbitrap Velos]");
meta_instrument.source.fromCellString("[MS, MS:1000008, Ionization Type, ESI]");
MzTabParameter ana;
ana.fromCellString("[MS, MS:1000443, Mass Analyzer Type, Orbitrap]");
meta_instrument.analyzer[0] = ana;
meta_instrument.detector.fromCellString("[MS, MS:1000453, Detector, Dynode Detector]");
mztabm_meta.instrument[0] = meta_instrument;
// software
MzTabSoftwareMetaData meta_software;
MzTabParameter p_software;
p_software.fromCellString("[MS, MS:1002205, ProteoWizard msconvert, ]");
meta_software.software = p_software;
meta_software.setting[0] = MzTabString("Peak Picking MS1");
mztabm_meta.software[0] = meta_software;
mztabm_meta.publication[0] = MzTabString("pubmed:21063943|doi:10.1007/978-1-60761-987-1_6");
// contact
MzTabContactMetaData meta_contact;
meta_contact.name = MzTabString("Max MusterMann");
meta_contact.affiliation = MzTabString("University of Musterhausen");
meta_contact.email = MzTabString("MMM@please_do_not_try_to_write_an_email.com");
mztabm_meta.contact[0] = meta_contact;
mztabm_meta.uri[0] = MzTabString("https://www.ebi.ac.uk/metabolights/MTBLS");
mztabm_meta.external_study_uri[0] = MzTabString("https://www.ebi.ac.uk/metabolights/MTBLS/files/i_Investigation.txt");
mztabm_meta.quantification_method.fromCellString("[MS, MS:1001834, LC-MS label-free quantitation analysis, ]");
// sample
MzTabSampleMetaData meta_sample;
meta_sample.description = MzTabString("Nice Sample");
mztabm_meta.sample[0] = meta_sample;
// ms-run
MzTabMMSRunMetaData meta_msrun;
meta_msrun.location = MzTabString("ftp://ftp.ebi.ac.uk/path/to/file");
meta_msrun.instrument_ref = MzTabInteger(0); // only if different instruments are used.
MzTabParameter p_format;
p_format.fromCellString("[MS, MS:1000584, mzML file, ]");
meta_msrun.format = p_format;
MzTabParameter p_id_format;
p_id_format.fromCellString("[MS, MS:1000584, mzML file, ]");
meta_msrun.id_format = p_id_format;
std::map<Size, MzTabParameter> pl_fragmentation_method;
pl_fragmentation_method[0].fromCellString("[MS, MS:1000133, CID, ]");
pl_fragmentation_method[1].fromCellString("[MS, MS:1000422, HCD, ]");
meta_msrun.fragmentation_method = pl_fragmentation_method;
std::map<Size, MzTabParameter> pl_scan_polarity;
pl_scan_polarity[0].fromCellString("[MS, MS:1000130, positive scan, ]");
pl_scan_polarity[1].fromCellString("[MS, MS:1000130, positive scan, ]");
meta_msrun.scan_polarity = pl_scan_polarity;
meta_msrun.hash = MzTabString("de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3");
MzTabParameter p_hash_method;
p_hash_method.fromCellString("[MS, MS:1000569, SHA-1, ]");
meta_msrun.hash_method = p_hash_method;
mztabm_meta.ms_run[0] = meta_msrun;
// assay
MzTabMAssayMetaData meta_assay;
MzTabParameter p_custom;
p_custom.fromCellString("[MS, , Assay operator, Blogs]");
meta_assay.custom[0] = p_custom;
meta_assay.external_uri = MzTabString("https://www.ebi.ac.uk/metabolights/MTBLS/files/i_Investigation.txt?STUDYASSAY=a_8pos.txt");
meta_assay.sample_ref = MzTabInteger(1);
meta_assay.ms_run_ref = MzTabInteger(1);
mztabm_meta.assay[0] = meta_assay;
// study variable
MzTabMStudyVariableMetaData meta_study;
std::vector<int> assay_refs{1};
meta_study.assay_refs = assay_refs;
MzTabParameter p_average_function;
p_average_function.fromCellString("[MS, MS:1002883, median, ]");
meta_study.average_function = p_average_function;
MzTabParameter p_variation_function;
p_variation_function.fromCellString("[MS, MS:1002885, standard error, ]"); // usually we will not average!
meta_study.variation_function = p_variation_function;
meta_study.description = MzTabString("control");
MzTabParameterList pl_factors;
pl_factors.fromCellString("[MS, MS:1000130, positive scan, ]");
meta_study.factors = pl_factors;
mztabm_meta.study_variable[0] = meta_study;
// controlled vocabulary metadata
MzTabCVMetaData meta_cv;
meta_cv.label = MzTabString("MS");
meta_cv.full_name = MzTabString("PSI-MS controlled vocabulary");
meta_cv.version = MzTabString("4.1.155");
meta_cv.url = MzTabString("share/OpenMS/CV/psi-ms.obo");
mztabm_meta.cv[0] = meta_cv;
// database
MzTabMDatabaseMetaData meta_db;
MzTabParameter p_db;
p_db.fromCellString("[MIRIAM, MIR:00100079, HMDB, ]");
meta_db.database = p_db;
meta_db.prefix = MzTabString("HMDB");
meta_db.version = MzTabString("4.0");
meta_db.uri = MzTabString("null");
mztabm_meta.database[0] = meta_db;
MzTabParameter p_qunit;
p_qunit.fromCellString("[MS, MS:1000042, peak intensity, ]");
mztabm_meta.small_molecule_quantification_unit = p_qunit;
MzTabParameter p_fqunit;
p_fqunit.fromCellString("[MS, MS:1000042, peak intensity, ]");
mztabm_meta.small_molecule_feature_quantification_unit = p_fqunit;
MzTabParameter p_idre;
p_idre.fromCellString("[MS, MS:1002955, hr-ms compound identification confidence level, ]");
mztabm_meta.small_molecule_identification_reliability = p_idre;
MzTabParameter p_confidence;
p_confidence.fromCellString("[MS,MS:1002890,fragmentation score,]");
mztabm_meta.id_confidence_measure[0] = p_confidence;
// Fill mztab-m datastructure
mztabm.setMetaData(mztabm_meta);
mztabm.setMSmallMoleculeSectionRows(sml_rows);
mztabm.setMSmallMoleculeFeatureSectionRows(smf_rows);
mztabm.setMSmallMoleculeEvidenceSectionRows(sme_rows);
// Tests ///////////////////////////////
MzTabMSmallMoleculeSectionRow sml_test;
sml_test = mztabm.getMSmallMoleculeSectionRows()[0];
TEST_EQUAL(sml_test.smf_id_refs.toCellString(), "1,2")
TEST_EQUAL(sml_test.adducts.toCellString(), "[[M+H]1+]")
MzTabMSmallMoleculeFeatureSectionRow smf_test;
smf_test = mztabm.getMSmallMoleculeFeatureSectionRows()[0];
TEST_EQUAL(smf_test.exp_mass_to_charge.toCellString(), "313.168900000000008")
TEST_EQUAL(smf_test.retention_time.toCellString(), "156.0")
MzTabMSmallMoleculeEvidenceSectionRow sme_test;
sme_test = mztabm.getMSmallMoleculeEvidenceSectionRows()[0];
TEST_EQUAL(sme_test.database_identifier.toCellString(), "HMDB:HMDB0001847")
TEST_EQUAL(sme_test.identification_method.toCellString(), "[MS, MS:1000752, TOPP Software, ]")
MzTabMMetaData mtest;
mtest = mztabm.getMetaData();
TEST_EQUAL(mtest.mz_tab_version.toCellString(),"2.0.0-M") // set by constructor
TEST_EQUAL(mtest.sample_processing[0].toCellString(), "[MS, MS:1000544, Conversion to mzML, ]|[MS, MS:1000035, Peak picking, ]|[MS, MS:1000594, Low intensity data point removal, ]")
TEST_EQUAL(mtest.instrument[0].analyzer[0].toCellString(), "[MS, MS:1000443, Mass Analyzer Type, Orbitrap]")
// meta_software.setting[0] = MzTabString("Peak Picking MS1");
TEST_EQUAL(mtest.software[0].setting[0].toCellString(), "Peak Picking MS1")
// meta_contact.affiliation = MzTabString("University of Musterhausen");
TEST_EQUAL(mtest.contact[0].affiliation.toCellString(), "University of Musterhausen")
// meta_sample.description = MzTabString("Nice Sample");
TEST_EQUAL(mtest.sample[0].description.toCellString(), "Nice Sample")
// p_format.fromCellString("[MS, MS:1000584, mzML file, ]");
TEST_EQUAL(mtest.ms_run[0].format.toCellString(), "[MS, MS:1000584, mzML file, ]")
// meta_study.description = MzTabString("control");
TEST_EQUAL(mtest.study_variable[0].description.toCellString(), "control")
// meta_db.prefix = MzTabString("HMDB");
TEST_EQUAL(mtest.database[0].prefix.toCellString(), "HMDB")
// p_qunit.fromCellString("[MS, MS:1000042, peak intensity, ]");
TEST_EQUAL(mtest.small_molecule_quantification_unit.toCellString(), "[MS, MS:1000042, peak intensity, ]")
vector<String> optional_sml_columns = mztabm.getMSmallMoleculeOptionalColumnNames();
vector<String> optional_sme_columns = mztabm.getMSmallMoleculeEvidenceOptionalColumnNames();
TEST_EQUAL(mztabm.getMSmallMoleculeSectionRows().size(),1)
TEST_EQUAL(mztabm.getMSmallMoleculeFeatureSectionRows().size(), 1)
TEST_EQUAL(mztabm.getMSmallMoleculeFeatureSectionRows().size(), 1)
TEST_EQUAL(optional_sml_columns.size(), 3)
TEST_EQUAL(optional_sme_columns.size(), 3)
}
END_SECTION
START_SECTION(MzTabM::exportFeatureMapToMzTabM(const FeatureMap& feature_map))
{
FeatureMap feature_map;
MzTabM mztabm;
OMSFile().load(OPENMS_GET_TEST_DATA_PATH("MzTabMFile_input_1.oms"), feature_map);
mztabm = mztabm.exportFeatureMapToMzTabM(feature_map);
TEST_EQUAL(mztabm.getMSmallMoleculeSectionRows().size(), 83)
TEST_EQUAL(mztabm.getMSmallMoleculeFeatureSectionRows().size(), 83)
TEST_EQUAL(mztabm.getMSmallMoleculeEvidenceSectionRows().size(), 312)
TEST_EQUAL(mztabm.getMSmallMoleculeOptionalColumnNames().size(), 0)
TEST_EQUAL(mztabm.getMSmallMoleculeFeatureOptionalColumnNames().size(), 18)
TEST_EQUAL(mztabm.getMSmallMoleculeEvidenceOptionalColumnNames().size(), 6)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/StablePairFinder_test.cpp | .cpp | 6,815 | 247 | // 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/ConsensusMap.h>
#include <OpenMS/KERNEL/Feature.h>
///////////////////////////
#include <OpenMS/ANALYSIS/MAPMATCHING/StablePairFinder.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
typedef DPosition<2> PositionType;
START_TEST(StablePairFinder, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
StablePairFinder* ptr = nullptr;
StablePairFinder* nullPointer = nullptr;
START_SECTION((StablePairFinder()))
ptr = new StablePairFinder();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~StablePairFinder()))
delete ptr;
END_SECTION
START_SECTION((void run(const std::vector<ConsensusMap>& input_maps, ConsensusMap &result_map)))
{
std::vector<ConsensusMap> input(2);
Feature feat1;
Feature feat2;
Feature feat3;
PositionType pos1(0,0);
PositionType pos2(200,300);
PositionType pos3(400,500);
feat1.setPosition(pos1);
feat1.setIntensity(100.0f);
feat1.setUniqueId(0);
feat2.setPosition(pos2);
feat2.setIntensity(300.0f);
feat2.setUniqueId(1);
feat3.setPosition(pos3);
feat3.setIntensity(400.0f);
feat3.setUniqueId(2);
ConsensusFeature cons1(0,feat1);
ConsensusFeature cons2(0,feat2);
ConsensusFeature cons3(0,feat3);
input[0].push_back(cons1);
input[0].push_back(cons2);
input[0].push_back(cons3);
Feature feat4;
Feature feat5;
Feature feat6;
PositionType pos4(4,0.04);
PositionType pos5(204,300.04);
PositionType pos6(404,500.04);
feat4.setPosition(pos4);
feat4.setIntensity(100.0f);
feat4.setUniqueId(0);
feat5.setPosition(pos5);
feat5.setIntensity(300.0f);
feat5.setUniqueId(1);
feat6.setPosition(pos6);
feat6.setIntensity(400.0f);
feat6.setUniqueId(2);
ConsensusFeature cons4(1,feat4);
ConsensusFeature cons5(1,feat5);
ConsensusFeature cons6(1,feat6);
input[1].push_back(cons4);
input[1].push_back(cons5);
input[1].push_back(cons6);
input[0].updateRanges();
input[1].updateRanges();
StablePairFinder spf;
Param param = spf.getDefaults();
spf.setParameters(param);
ConsensusMap result;
spf.run(input,result);
TEST_EQUAL(result.size(),3);
ABORT_IF(result.size()!=3);
ConsensusFeature::HandleSetType group1 = result[0].getFeatures();
ConsensusFeature::HandleSetType group2 = result[1].getFeatures();
ConsensusFeature::HandleSetType group3 = result[2].getFeatures();
FeatureHandle ind1(0,feat1);
FeatureHandle ind2(0,feat2);
FeatureHandle ind3(0,feat3);
FeatureHandle ind4(1,feat4);
FeatureHandle ind5(1,feat5);
FeatureHandle ind6(1,feat6);
ConsensusFeature::HandleSetType::const_iterator it;
it = group1.begin();
STATUS(*it);
STATUS(ind1);
TEST_EQUAL(*(it) == ind1, true)
++it;
STATUS(*it);
STATUS(ind4);
TEST_EQUAL(*(it) == ind4, true)
it = group2.begin();
STATUS(*it);
STATUS(ind2);
TEST_EQUAL(*(it) == ind2, true)
++it;
STATUS(*it);
STATUS(ind5);
TEST_EQUAL(*(it) == ind5, true)
it = group3.begin();
STATUS(*it);
STATUS(ind3);
TEST_EQUAL(*(it) == ind3, true)
++it;
STATUS(*it);
STATUS(ind6);
TEST_EQUAL(*(it) == ind6, true)
}
END_SECTION
START_SECTION(([EXTRA] void run(const std::vector<ConsensusMap>& input_maps, ConsensusMap &result_map)))
{
// test quality calculation:
std::vector<ConsensusMap> input(2);
Feature feat1, feat2, feat3;
PositionType pos1(100, 100);
PositionType pos2(200, 200);
PositionType pos3(300, 300);
feat1.setPosition(pos1);
feat1.setIntensity(100.0);
feat1.setUniqueId(0);
feat2.setPosition(pos2);
feat2.setIntensity(200.0);
feat2.setUniqueId(1);
feat3.setPosition(pos3);
feat3.setIntensity(300.0);
feat3.setUniqueId(2);
// ConsensusFeature cons1(feat1);
// ConsensusFeature cons2(feat2);
// ConsensusFeature cons3(feat3);
StablePairFinder spf;
Param param = spf.getDefaults();
param.setValue("distance_RT:max_difference", 1000.0);
param.setValue("distance_MZ:max_difference", 1000.0);
param.setValue("second_nearest_gap", 2.0);
spf.setParameters(param);
ConsensusMap result;
// best case:
input[0].push_back(ConsensusFeature(0, feat1));
input[1].push_back(ConsensusFeature(1, feat1));
input[0].updateRanges();
input[1].updateRanges();
spf.run(input, result);
TEST_EQUAL(result.size(), 1);
TEST_EQUAL(result[0].size(), 2);
TEST_EQUAL(result[0].getQuality(), 1.0);
input[0] = result;
input[1][0] = ConsensusFeature(2, feat1);
input[0].updateRanges();
input[1].updateRanges();
spf.run(input, result);
TEST_EQUAL(result.size(), 1);
TEST_EQUAL(result[0].size(), 3);
TEST_EQUAL(result[0].getQuality(), 1.0);
// worst case:
input[0].clear();
spf.run(input, result);
TEST_EQUAL(result.size(), 1);
TEST_EQUAL(result[0].size(), 1);
TEST_EQUAL(result[0].getQuality(), 0.0);
// intermediate cases:
// basis: feat1 < feat2 < feat3
input[1].clear();
input[0].push_back(ConsensusFeature(0, feat1));
input[1].push_back(ConsensusFeature(1, feat2));
input[0].updateRanges();
input[1].updateRanges();
spf.run(input, result);
ConsensusFeature cons1 = result[0];
TEST_EQUAL(cons1.size(), 2);
input[0] = result;
input[1][0] = ConsensusFeature(2, feat3);
input[0].updateRanges();
input[1].updateRanges();
spf.run(input, result);
ConsensusFeature cons2 = result[0];
TEST_EQUAL(cons2.size(), 3);
TEST_EQUAL(cons1.getQuality() > 0.0, true);
TEST_EQUAL(cons2.getQuality() > 0.0, true);
TEST_EQUAL(cons1.getQuality() < 1.0, true);
TEST_EQUAL(cons2.getQuality() < 1.0, true);
// quality(feat1, feat2) > quality((feat1, feat2), feat3):
TEST_EQUAL(cons1.getQuality() > cons2.getQuality(), true);
input[0].clear();
input[0].push_back(ConsensusFeature(1, feat2));
input[0].updateRanges();
input[1].updateRanges();
spf.run(input, result);
ConsensusFeature cons3 = result[0];
// quality(feat2, feat3) > quality(feat1, feat2), feat3):
TEST_EQUAL(cons3.getQuality() > cons2.getQuality(), true);
input[0][0] = ConsensusFeature(0, feat1);
input[0].updateRanges();
input[1].updateRanges();
spf.run(input, result);
ConsensusFeature cons4 = result[0];
// quality(feat1, feat3) < quality(feat1, feat2), feat3):
TEST_EQUAL(cons4.getQuality() < cons2.getQuality(), true);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ElementDB_test.cpp | .cpp | 4,376 | 123 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
//
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CHEMISTRY/Element.h>
#include <OpenMS/CHEMISTRY/ElementDB.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(ElementDB, "$Id$")
/////////////////////////////////////////////////////////////
ElementDB* e_ptr = nullptr;
ElementDB* e_nullPointer = nullptr;
const Element * elem_nullPointer = nullptr;
START_SECTION([EXTRA] multithreaded example)
{
int nr_iterations (100);
int test = 0;
#pragma omp parallel for reduction(+: test)
for (int k = 1; k < nr_iterations + 1; k++)
{
auto edb = ElementDB::getInstance();
const Element * e1 = edb->getElement("Carbon");
test += e1->getAtomicNumber();
}
TEST_EQUAL(test, 6 * 100)
}
END_SECTION
START_SECTION(static const ElementDB* getInstance())
e_ptr = ElementDB::getInstance();
TEST_NOT_EQUAL(e_ptr, e_nullPointer)
END_SECTION
START_SECTION((const unordered_map<string, const Element*>& getNames() const))
unordered_map<string, const Element*> names = e_ptr->getNames();
const Element * e = e_ptr->getElement("Carbon");
TEST_EQUAL(e, names["Carbon"])
TEST_NOT_EQUAL(e, elem_nullPointer)
END_SECTION
START_SECTION((const unordered_map<string, const Element*>& getSymbols() const))
unordered_map<string, const Element*> symbols = e_ptr->getSymbols();
const Element * e = e_ptr->getElement("Carbon");
TEST_EQUAL(e, symbols["C"])
TEST_NOT_EQUAL(e, elem_nullPointer)
END_SECTION
START_SECTION((const unordered_map<unsigned int, const Element*>& getAtomicNumbers() const))
unordered_map<unsigned int, const Element*> atomic_numbers = e_ptr->getAtomicNumbers();
const Element * e = e_ptr->getElement("Carbon");
TEST_EQUAL(e, atomic_numbers[6])
TEST_NOT_EQUAL(e, elem_nullPointer)
END_SECTION
START_SECTION(const Element* getElement(const string& name) const)
const Element * e1 = e_ptr->getElement("Hydrogen");
const Element * e2 = e_ptr->getElement("H");
TEST_EQUAL(e1, e2);
TEST_NOT_EQUAL(e1, elem_nullPointer);
END_SECTION
START_SECTION(const Element* getElement(unsigned int atomic_number) const)
const Element * e1 = e_ptr->getElement("Carbon");
const Element * e2 = e_ptr->getElement(6);
TEST_EQUAL(e1, e2)
TEST_NOT_EQUAL(e1, elem_nullPointer)
END_SECTION
START_SECTION(bool hasElement(const string& name) const)
TEST_EQUAL(e_ptr->hasElement("Carbon"), true)
END_SECTION
START_SECTION(bool hasElement(unsigned int atomic_number) const)
TEST_EQUAL(e_ptr->hasElement(6), true)
END_SECTION
START_SECTION(void addElement(const std::string& name,
const std::string& symbol,
const unsigned int an,
const std::map<unsigned int, double>& abundance,
const std::map<unsigned int, double>& mass,
bool replace_existing))
{
const Element * oxygen = e_ptr->getElement(8);
TEST_REAL_SIMILAR(oxygen->getAverageWeight(), 15.99940532316)
map<unsigned int, double> oxygen_abundance = {{16u, 0.7}, {19u, 0.3}};
map<unsigned int, double> oxygen_mass = {{16u, 15.994915000000001}, {19u, 19.01}};
e_ptr->addElement("Oxygen", "O", 8u, oxygen_abundance, oxygen_mass, true); // true: replace existing
const Element * new_oxygen = e_ptr->getElement(8);
// ptr addresses cannot change, otherwise we are in trouble since EmpiricalFormula uses those
TEST_EQUAL(oxygen, new_oxygen)
TEST_REAL_SIMILAR(oxygen->getAverageWeight(), 16.8994405) // average weight has changed
// cannot add invalid element (name and symbol conflict when compared existing element
// -- this would invalidate the lookup, since e_ptr->getSymbols().at("O")->getSymbol() == 'P'
TEST_EXCEPTION(Exception::InvalidValue, e_ptr->addElement("Oxygen", "P", 8u, oxygen_abundance, oxygen_mass, true)) // true: replace existing
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/XFDRAlgorithm_test.cpp | .cpp | 3,099 | 93 | // 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/ANALYSIS/XLMS/XFDRAlgorithm.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(XFDRAlgorithm, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
XFDRAlgorithm* ptr = 0;
XFDRAlgorithm* null_ptr = 0;
START_SECTION(XFDRAlgorithm())
{
ptr = new XFDRAlgorithm();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(virtual ~XFDRAlgorithm())
{
delete ptr;
}
END_SECTION
START_SECTION(ExitCodes run(PeptideIdentificationList& peptide_ids, ProteinIdentification& protein_id))
PeptideIdentificationList peptide_ids;
std::vector<ProteinIdentification> protein_ids;
ProteinIdentification protein_id;
XQuestResultXMLFile xquest_file;
xquest_file.load(OPENMS_GET_TEST_DATA_PATH("XFDRAlgorithm_input.xquest.xml"), peptide_ids, protein_ids);
protein_id = protein_ids[0];
XFDRAlgorithm fdr_algorithm;
Param algo_param = fdr_algorithm.getParameters();
algo_param.setValue("binsize", 0.1);
fdr_algorithm.setParameters(algo_param);
// run algorithm
XFDRAlgorithm::ExitCodes exit_code = fdr_algorithm.run(peptide_ids, protein_id);
TEST_EQUAL(exit_code, XFDRAlgorithm::ExitCodes::EXECUTION_OK)
TEST_EQUAL(protein_ids.size(), 1)
TEST_EQUAL(peptide_ids.size(), 310)
for (Size i = 0; i < peptide_ids.size(); i += 30)
{
auto pep_hits = peptide_ids[i].getHits();
// the first hit is always the alpha chain
TEST_EQUAL(pep_hits[0].metaValueExists("xl_target_decoy_alpha"), true)
TEST_EQUAL(pep_hits[0].metaValueExists("XFDR:FDR"), true)
TEST_EQUAL(pep_hits[0].metaValueExists("XFDR:used_for_FDR"), true)
TEST_EQUAL(pep_hits[0].metaValueExists("XFDR:fdr_type"), true)
if (pep_hits[0].getMetaValue("xl_type") == "cross-link")
{
TEST_EQUAL(pep_hits[0].metaValueExists("BetaPepEv:pre"), true)
}
}
TEST_EQUAL(peptide_ids[50].getHits()[0].getMetaValue("XFDR:FDR"), -0.025)
TEST_EQUAL(peptide_ids[100].getHits()[0].getMetaValue("XFDR:FDR"), 0.934782608695652)
TEST_EQUAL(peptide_ids[250].getHits()[0].getMetaValue("XFDR:FDR"), 0.934782608695652)
TEST_EQUAL(peptide_ids[300].getHits()[0].getMetaValue("XFDR:FDR"), 0.934782608695652)
TEST_EQUAL(peptide_ids[309].getHits()[0].getMetaValue("XFDR:FDR"), -0.025)
TEST_EQUAL(peptide_ids[25].getHits()[0].getMetaValue("XFDR:FDR"), 0.020618556701031)
TEST_EQUAL(peptide_ids[75].getHits()[0].getMetaValue("XFDR:FDR"), 0.934782608695652)
TEST_EQUAL(peptide_ids[275].getHits()[0].getMetaValue("XFDR:FDR"), 0.01063829787234)
TEST_EQUAL(peptide_ids[276].getHits()[0].getMetaValue("XFDR:FDR"), -0.025)
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/BiGaussFitter1D_test.cpp | .cpp | 2,613 | 99 | // 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/BiGaussFitter1D.h>
#include <OpenMS/FEATUREFINDER/BiGaussModel.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(BiGaussFitter1D, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
BiGaussFitter1D* ptr = nullptr;
BiGaussFitter1D* nullPointer = nullptr;
START_SECTION(BiGaussFitter1D())
{
ptr = new BiGaussFitter1D();
TEST_EQUAL(ptr->getName(), "BiGaussFitter1D")
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION((BiGaussFitter1D(const BiGaussFitter1D &source)))
{
BiGaussFitter1D bgf1;
Param param;
param.setValue( "tolerance_stdev_bounding_box", 1.0);
param.setValue( "statistics:mean", 680.1 );
param.setValue( "statistics:variance", 2.0 );
param.setValue( "statistics:variance1", 2.0 );
param.setValue( "statistics:variance2", 5.0 );
param.setValue( "interpolation_step", 1.0 );
bgf1.setParameters(param);
BiGaussFitter1D bgf2(bgf1);
BiGaussFitter1D bgf3;
bgf3.setParameters(param);
bgf1 = BiGaussFitter1D();
TEST_EQUAL(bgf3.getParameters(), bgf2.getParameters())
}
END_SECTION
START_SECTION((virtual ~BiGaussFitter1D()))
{
delete ptr;
}
END_SECTION
START_SECTION((virtual BiGaussFitter1D& operator=(const BiGaussFitter1D &source)))
{
BiGaussFitter1D bgf1;
Param param;
param.setValue( "tolerance_stdev_bounding_box", 1.0);
param.setValue( "statistics:mean", 680.1 );
param.setValue( "statistics:variance", 2.0 );
param.setValue( "statistics:variance1", 2.0 );
param.setValue( "statistics:variance2", 5.0 );
param.setValue( "interpolation_step", 1.0 );
bgf1.setParameters(param);
BiGaussFitter1D bgf2;
bgf2 = bgf1;
BiGaussFitter1D bgf3;
bgf3.setParameters(param);
bgf1 = BiGaussFitter1D();
TEST_EQUAL(bgf3.getParameters(), bgf2.getParameters())
}
END_SECTION
START_SECTION((QualityType fit1d(const RawDataArrayType &range, InterpolationModel *&model)))
// dummy subtest
TEST_EQUAL(1,1)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IMSDataConsumer_test.cpp | .cpp | 1,042 | 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/IMSDataConsumer.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(IMSDataConsumer, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IMSDataConsumer* ptr = 0;
IMSDataConsumer* null_ptr = 0;
START_SECTION(IMSDataConsumer())
{
ptr = new IMSDataConsumer();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IMSDataConsumer())
{
delete ptr;
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/PepNovoOutfile_test.cpp | .cpp | 7,934 | 173 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Sandro Andreotti, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/PepNovoOutfile.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <iostream>
#include <vector>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(String, "$Id$")
/////////////////////////////////////////////////////////////
PepNovoOutfile* ptr = nullptr;
PepNovoOutfile* nullPointer = nullptr;
START_SECTION(PepNovoOutfile())
ptr = new PepNovoOutfile();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~PepNovoOutfile())
delete ptr;
END_SECTION
START_SECTION((PepNovoOutfile& operator=(const PepNovoOutfile &pepnovo_outfile)))
PepNovoOutfile pepnovo_outfile1;
PepNovoOutfile pepnovo_outfile2;
pepnovo_outfile2 = pepnovo_outfile1;
PepNovoOutfile pepnovo_outfile3;
pepnovo_outfile1 = PepNovoOutfile();
TEST_EQUAL(( pepnovo_outfile2 == pepnovo_outfile3 ), true)
END_SECTION
START_SECTION((PepNovoOutfile(const PepNovoOutfile &pepnovo_outfile)))
PepNovoOutfile pepnovo_outfile1;
PepNovoOutfile pepnovo_outfile2(pepnovo_outfile1);
PepNovoOutfile pepnovo_outfile3;
pepnovo_outfile1 = PepNovoOutfile();
TEST_EQUAL(( pepnovo_outfile2 == pepnovo_outfile3 ), true)
END_SECTION
START_SECTION((bool operator==(const PepNovoOutfile &pepnovo_outfile) const))
PepNovoOutfile pepnovo_outfile1;
PepNovoOutfile pepnovo_outfile2;
TEST_EQUAL(( pepnovo_outfile1 == pepnovo_outfile2 ), true)
END_SECTION
PepNovoOutfile file;
START_SECTION((void load(const std::string &result_filename, std::vector< PeptideIdentification > &peptide_identifications, ProteinIdentification &protein_identification, const double &score_threshold, const IndexPosMappingType &id_rt_mz, const std::map< String, String > &mod_id_map)))
PeptideIdentificationList peptide_identifications;
ProteinIdentification protein_identification;
map< String, double > filenames_and_precursor_retention_times;
// test exceptions
//TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.load("a", peptide_identifications, protein_identification, 0.915f, filenames_and_precursor_retention_times), "the file 'a' could not be found")
//TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.load(OPENMS_GET_TEST_DATA_PATH("PepNovoOutfile.out1"), peptide_identifications, protein_identification, 0.915f, filenames_and_precursor_retention_times), OPENMS_GET_TEST_DATA_PATH_MESSAGE("", "PepNovoOutfile.out1", " in: Not enough columns in file in line 2 (should be 8)!"))
//TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.load(OPENMS_GET_TEST_DATA_PATH("PepNovoOutfile.out2"), peptide_identifications, protein_identification, 0.915f, filenames_and_precursor_retention_times), OPENMS_GET_TEST_DATA_PATH_MESSAGE("", "PepNovoOutfile.out2", " in: Not enough columns in file in line 7 (should be 8)!" ))
peptide_identifications.clear();
protein_identification.setHits(vector< ProteinHit >());
// test the actual program
map<String, String> key_to_mod;
key_to_mod["K+42"]="Acetyl (K)";
key_to_mod["Y+42"]="Acetyl (Y)";
PepNovoOutfile::IndexPosMappingType rt_and_index, rt_and_index2;
rt_and_index[0] = std::make_pair(1510.5732421875, 747.761901855469);
rt_and_index[1] = std::make_pair(1530.11535644531, 549.856262207031);
// check missing index-key ( rt_and_index[2] )
TEST_EXCEPTION(Exception::ParseError, file.load(OPENMS_GET_TEST_DATA_PATH("PepNovoOutfile.out"), peptide_identifications, protein_identification, -2.000f, rt_and_index, key_to_mod));
rt_and_index[2] = std::make_pair(1533.16589355469, 358.174530029297);
rt_and_index[3] = std::make_pair(1111, 2222);
for (Size i=0; i<2; ++i)
{
if (i==0) rt_and_index2 = rt_and_index; // use explicit mapping
else rt_and_index2 = PepNovoOutfile::IndexPosMappingType(); // try to reconstruct from title in pepnovo file
file.load(OPENMS_GET_TEST_DATA_PATH("PepNovoOutfile.out"), peptide_identifications, protein_identification, -2.000f, rt_and_index2, key_to_mod);
TEST_EQUAL(peptide_identifications.size(), 4)
ABORT_IF(peptide_identifications.size() != 4)
TEST_EQUAL(peptide_identifications[0].getHits().size(), 5)
TEST_REAL_SIMILAR(peptide_identifications[0].getSignificanceThreshold(), -2.0)
TEST_REAL_SIMILAR(peptide_identifications[0].getMZ(), 747.761901855469)
TEST_REAL_SIMILAR(peptide_identifications[0].getRT(), 1510.5732421875)
TEST_EQUAL(peptide_identifications[1].getHits().size(), 14)
TEST_REAL_SIMILAR(peptide_identifications[1].getSignificanceThreshold(), -2.0)
TEST_REAL_SIMILAR(peptide_identifications[1].getMZ(), 549.856262207031)
TEST_REAL_SIMILAR(peptide_identifications[1].getRT(), 1530.11535644531)
TEST_EQUAL(peptide_identifications[2].getHits().size(), 20)
TEST_EQUAL(peptide_identifications[3].getHits().size(), 20)
TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[0].getScore(), -1.412)
TEST_EQUAL(peptide_identifications[0].getHits()[0].getSequence(), AASequence::fromString("ADYGVTR"))
TEST_EQUAL(peptide_identifications[0].getHits()[0].getCharge(), 2)
TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[0].getMetaValue("PnvScr"), 21.144)
TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[1].getScore(), -1.483)
TEST_EQUAL(peptide_identifications[0].getHits()[1].getSequence(), AASequence::fromString("SDYGVTR"))
TEST_EQUAL(peptide_identifications[0].getHits()[1].getCharge(), 2)
TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[1].getMetaValue("PnvScr"), 18.239)
file.load(OPENMS_GET_TEST_DATA_PATH("PepNovoOutfile.out"), peptide_identifications, protein_identification, -4.000f, rt_and_index2, key_to_mod);
TEST_EQUAL(peptide_identifications.size(), 4)
ABORT_IF( peptide_identifications.size() != 4 )
TEST_EQUAL(peptide_identifications[3].getHits().size(), 20)
TEST_REAL_SIMILAR(peptide_identifications[3].getSignificanceThreshold(), -4.0)
TEST_REAL_SIMILAR(peptide_identifications[3].getHits()[11].getScore(),8.045)
TEST_EQUAL(peptide_identifications[3].getHits()[11].getSequence(), AASequence::fromString("GK(Acetyl)EAMAPK"))
TEST_EQUAL(peptide_identifications[3].getHits()[0].getCharge(), 2)
}
END_SECTION
START_SECTION(void getSearchEngineAndVersion(const String& pepnovo_output_without_parameters_filename, ProteinIdentification& protein_identification))
ProteinIdentification protein_identification;
// test the actual program
file.getSearchEngineAndVersion(OPENMS_GET_TEST_DATA_PATH("PepNovoOutfile.out"), protein_identification);
TEST_EQUAL(protein_identification.getSearchEngine(), "PepNovo+");
TEST_EQUAL(protein_identification.getSearchEngineVersion(), "Build 20081230");
TEST_EQUAL(protein_identification.getSearchParameters().fragment_mass_tolerance, 0.5);
TEST_REAL_SIMILAR(protein_identification.getSearchParameters().fragment_mass_tolerance, 0.5);
TEST_REAL_SIMILAR(protein_identification.getSearchParameters().precursor_mass_tolerance, 2.5);
TEST_EQUAL(protein_identification.getSearchParameters().variable_modifications.size(), 2);
if(protein_identification.getSearchParameters().variable_modifications.size()== 2)
{
TEST_EQUAL(protein_identification.getSearchParameters().variable_modifications[0], "K+42");
TEST_EQUAL(protein_identification.getSearchParameters().variable_modifications[1], "Y+42");
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/OpenSwathScores_test.cpp | .cpp | 5,818 | 145 | // 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/OpenSwathScores.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(OpenSwathScores, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
OpenSwath_Scores* nullPointer = nullptr;
OpenSwath_Scores* ptr = nullptr;
START_SECTION(OpenSwath_Scores())
{
ptr = new OpenSwath_Scores();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~OpenSwath_Scores())
{
delete ptr;
}
END_SECTION
START_SECTION(EXTRA OpenSwath_Scores())
{
OpenSwath_Scores scores;
TEST_REAL_SIMILAR( scores.ms1_xcorr_coelution_score, -1.0)
TEST_REAL_SIMILAR( scores.ms1_xcorr_shape_score, -1.0)
TEST_REAL_SIMILAR( scores.ms1_mi_score, -1.0)
}
END_SECTION
START_SECTION((double get_quick_lda_score(double library_corr_, double library_norm_manhattan_, double norm_rt_score_, double xcorr_coelution_score_,
double xcorr_shape_score_, double log_sn_score_) const))
{
OpenSwath_Scores scores;
TEST_REAL_SIMILAR( scores.get_quick_lda_score(1.0, 1.0, 1.0, 1.0, 1.0, 1.0),
-0.5319046 +
2.1643962 +
8.0353047 +
0.1458914 +
-1.6901925 +
-0.8002824)
}
END_SECTION
START_SECTION((double calculate_lda_prescore(const OpenSwath_Scores& scores) const))
{
OpenSwath_Scores scores;
TEST_REAL_SIMILAR( scores.calculate_lda_prescore(scores), 0.0)
scores.library_corr = 1.0;
scores.library_norm_manhattan = 1.0;
scores.norm_rt_score = 1.0;
scores.xcorr_coelution_score = 1.0;
scores.xcorr_shape_score = 1.0;
scores.log_sn_score = 1.0;
scores.elution_model_fit_score = 1.0;
TEST_REAL_SIMILAR( scores.calculate_lda_prescore(scores),
-0.34664267 +
2.98700722 +
7.05496384 +
0.09445371 +
-5.71823862 +
-0.72989582 +
1.88443209)
}
END_SECTION
START_SECTION((double calculate_lda_single_transition(const OpenSwath_Scores& scores) const))
{
OpenSwath_Scores scores;
TEST_REAL_SIMILAR( scores.calculate_lda_single_transition(scores), 0.0)
scores.library_corr = 1.0;
scores.library_norm_manhattan = 1.0;
scores.norm_rt_score = 1.0;
scores.xcorr_coelution_score = 1.0;
scores.xcorr_shape_score = 1.0;
scores.log_sn_score = 1.0;
scores.elution_model_fit_score = 1.0;
TEST_REAL_SIMILAR( scores.calculate_lda_single_transition(scores),
7.05496384 +
-0.72989582 +
-1.08443209)
}
END_SECTION
START_SECTION((double calculate_swath_lda_prescore(const OpenSwath_Scores& scores) const))
{
OpenSwath_Scores scores;
TEST_REAL_SIMILAR( scores.calculate_swath_lda_prescore(scores), 0.0)
scores.library_corr = 1.0;
scores.library_norm_manhattan = 1.0;
scores.norm_rt_score = 1.0;
scores.isotope_correlation = 1.0;
scores.isotope_overlap = 1.0;
scores.massdev_score = 1.0;
scores.xcorr_coelution_score = 1.0;
scores.xcorr_shape_score = 1.0;
scores.yseries_score = 1.0;
scores.log_sn_score = 1.0;
TEST_REAL_SIMILAR( scores.calculate_swath_lda_prescore(scores),
-0.19011762 +
2.47298914 +
5.63906731 +
-0.62640133 +
0.36006925 +
0.08814003 +
0.13978311 +
-1.16475032 +
-0.19267813 +
-0.61712054)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ExtendedIsotopeModel_test.cpp | .cpp | 5,016 | 186 | // 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/ExtendedIsotopeModel.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <sstream>
///////////////////////////
START_TEST(ExtendedIsotopeModel, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using std::stringstream;
// default ctor
ExtendedIsotopeModel* ptr = nullptr;
ExtendedIsotopeModel* nullPointer = nullptr;
START_SECTION((ExtendedIsotopeModel()))
ptr = new ExtendedIsotopeModel();
TEST_EQUAL(ptr->getName(), "ExtendedIsotopeModel")
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
// destructor
START_SECTION((virtual ~ExtendedIsotopeModel()))
delete ptr;
END_SECTION
// assignment operator
START_SECTION((virtual ExtendedIsotopeModel& operator=(const ExtendedIsotopeModel &source)))
ExtendedIsotopeModel im1;
Param tmp;
tmp.setValue("charge", 3);
tmp.setValue("isotope:stdev",0.8);
tmp.setValue("isotope:monoisotopic_mz", 670.5);
im1.setParameters(tmp);
ExtendedIsotopeModel im2;
im2 = im1;
ExtendedIsotopeModel im3;
im3.setParameters(tmp);
im1 = ExtendedIsotopeModel();
TEST_EQUAL(im3.getParameters(), im2.getParameters())
END_SECTION
// copy ctor
START_SECTION((ExtendedIsotopeModel(const ExtendedIsotopeModel& source)))
ExtendedIsotopeModel im1;
Param tmp;
tmp.setValue("charge", 3);
tmp.setValue("isotope:stdev",0.8);
tmp.setValue("isotope:monoisotopic_mz", 670.5);
im1.setParameters(tmp);
ExtendedIsotopeModel im2(im1);
ExtendedIsotopeModel im3;
im3.setParameters(tmp);
im1 = ExtendedIsotopeModel();
TEST_EQUAL(im3.getParameters(), im2.getParameters())
END_SECTION
START_SECTION([EXTRA] DefaultParamHandler::setParameters(...))
TOLERANCE_ABSOLUTE(0.001)
ExtendedIsotopeModel im1;
Param tmp;
tmp.setValue("charge", 3);
tmp.setValue("isotope:stdev",0.8);
tmp.setValue("isotope:monoisotopic_mz", 670.5);
im1.setParameters(tmp);
ExtendedIsotopeModel im2;
im2.setParameters(im1.getParameters());
std::vector<Peak1D> dpa1;
std::vector<Peak1D> dpa2;
im1.getSamples(dpa1);
im2.getSamples(dpa2);
TOLERANCE_ABSOLUTE(0.00001)
TEST_EQUAL(dpa1.size(),dpa2.size())
ABORT_IF(dpa1.size()!=dpa2.size());
for (Size i=0; i<dpa1.size(); ++i)
{
TEST_REAL_SIMILAR(dpa1[i].getPosition()[0],dpa2[i].getPosition()[0])
TEST_REAL_SIMILAR(dpa1[i].getIntensity(),dpa2[i].getIntensity())
}
END_SECTION
START_SECTION(UInt getCharge() )
// can only reliably be tested after fitting, only sanity check here
ExtendedIsotopeModel im1;
TEST_EQUAL(im1.getCharge() == 1, true) // default charge is 1
END_SECTION
START_SECTION( CoordinateType getCenter() const )
// can only reliably be tested after fitting, only sanity check here
ExtendedIsotopeModel im1;
TEST_EQUAL(im1.getCenter() == 1, true) // default charge is 1 and hence center mus be 1
END_SECTION
START_SECTION( void setOffset(CoordinateType offset) )
TOLERANCE_ABSOLUTE(0.1)
ExtendedIsotopeModel im1;
Param tmp;
tmp.setValue("charge", 3);
tmp.setValue("isotope:stdev",0.8);
tmp.setValue("isotope:monoisotopic_mz", 670.5);
im1.setParameters(tmp);
im1.setOffset( 673.5 );
ExtendedIsotopeModel im2;
im2.setParameters(im1.getParameters());
im2.setOffset( 673.5 );
std::vector<Peak1D> dpa1;
std::vector<Peak1D> dpa2;
im1.getSamples(dpa1);
im2.getSamples(dpa2);
TEST_EQUAL(dpa1.size(),dpa2.size())
ABORT_IF(dpa1.size()!=dpa2.size());
for (Size i=0; i<dpa1.size(); ++i)
{
TEST_REAL_SIMILAR(dpa1[i].getPosition()[0],dpa2[i].getPosition()[0])
TEST_REAL_SIMILAR(dpa1[i].getIntensity(),dpa2[i].getIntensity())
}
END_SECTION
START_SECTION( CoordinateType getOffset() )
TOLERANCE_ABSOLUTE(0.1)
ExtendedIsotopeModel im1;
Param tmp;
tmp.setValue("charge", 3);
tmp.setValue("isotope:stdev",0.8);
tmp.setValue("isotope:monoisotopic_mz", 670.5);
im1.setParameters(tmp);
im1.setOffset( 673.5 );
ExtendedIsotopeModel im2;
im2.setParameters(im1.getParameters());
im2.setOffset( im1.getOffset() );
std::vector<Peak1D> dpa1;
std::vector<Peak1D> dpa2;
im1.getSamples(dpa1);
im2.getSamples(dpa2);
TEST_EQUAL(dpa1.size(),dpa2.size())
ABORT_IF(dpa1.size()!=dpa2.size());
for (Size i=0; i<dpa1.size(); ++i)
{
TEST_REAL_SIMILAR(dpa1[i].getPosition()[0],dpa2[i].getPosition()[0])
TEST_REAL_SIMILAR(dpa1[i].getIntensity(),dpa2[i].getIntensity())
}
END_SECTION
START_SECTION((void setSamples()))
{
// dummy subtest
TEST_EQUAL(1,1)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/OpenSwathHelper_test.cpp | .cpp | 5,188 | 176 | // 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/OpenSwathHelper.h>
#include <boost/assign/std/vector.hpp>
///////////////////////////
START_TEST(OpenSwathHelper, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace std;
using namespace OpenMS;
using namespace OpenSwath;
OpenSwathHelper* ptr = nullptr;
OpenSwathHelper* nullPointer = nullptr;
START_SECTION(OpenSwathHelper())
{
ptr = new OpenSwathHelper();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~OpenSwathHelper())
{
delete ptr;
}
END_SECTION
START_SECTION(static String computePrecursorId(const String& transition_group_id, int isotope))
{
TEST_EQUAL(OpenSwathHelper::computePrecursorId("tr_gr2", 0), "tr_gr2_Precursor_i0")
TEST_EQUAL(OpenSwathHelper::computePrecursorId("tr_gr2__test", 0), "tr_gr2__test_Precursor_i0")
}
END_SECTION
START_SECTION(static String computeTransitionGroupId(const String& precursor_id))
{
TEST_EQUAL(OpenSwathHelper::computeTransitionGroupId("tr_gr2_Precursor_i0"), "tr_gr2")
TEST_EQUAL(OpenSwathHelper::computeTransitionGroupId("tr_gr2__test_Precursor_i0"), "tr_gr2__test")
}
END_SECTION
START_SECTION(static void selectSwathTransitions(const OpenMS::TargetedExperiment &targeted_exp, OpenMS::TargetedExperiment &transition_exp_used, double min_upper_edge_dist, double lower, double upper))
{
TargetedExperiment exp1;
TargetedExperiment exp2;
ReactionMonitoringTransition tr1;
ReactionMonitoringTransition tr2;
ReactionMonitoringTransition tr3;
tr1.setPrecursorMZ(100.0);
tr2.setPrecursorMZ(200.0);
tr3.setPrecursorMZ(300.0);
std::vector<ReactionMonitoringTransition> transitions;
transitions.push_back(tr1);
transitions.push_back(tr2);
transitions.push_back(tr3);
exp1.setTransitions(transitions);
// select all transitions between 200 and 500
OpenSwathHelper::selectSwathTransitions(exp1, exp2, 1.0, 199.9, 500);
TEST_EQUAL(exp2.getTransitions().size(), 2)
}
END_SECTION
START_SECTION(static void selectSwathTransitions(const OpenSwath::LightTargetedExperiment &targeted_exp, OpenSwath::LightTargetedExperiment &transition_exp_used, double min_upper_edge_dist, double lower, double upper))
{
LightTargetedExperiment exp1;
LightTargetedExperiment exp2;
LightTransition tr1;
LightTransition tr2;
LightTransition tr3;
tr1.precursor_mz = 100.0;
tr2.precursor_mz = 200.0;
tr3.precursor_mz = 300.0;
std::vector<LightTransition> transitions;
transitions.push_back(tr1);
transitions.push_back(tr2);
transitions.push_back(tr3);
exp1.transitions = transitions;
// select all transitions between 200 and 500
OpenSwathHelper::selectSwathTransitions(exp1, exp2, 1.0, 199.9, 500);
TEST_EQUAL(exp2.getTransitions().size(), 2)
}
END_SECTION
START_SECTION( (template < class TargetedExperimentT > static bool checkSwathMapAndSelectTransitions(const OpenMS::PeakMap &exp, const TargetedExperimentT &targeted_exp, TargetedExperimentT &transition_exp_used, double min_upper_edge_dist)))
{
// tested above already
NOT_TESTABLE
}
END_SECTION
START_SECTION(static void checkSwathMap(const OpenMS::PeakMap &swath_map, double &lower, double &upper))
{
OpenMS::PeakMap swath_map;
OpenMS::MSSpectrum spectrum;
OpenMS::Precursor prec;
std::vector<Precursor> precursors;
prec.setMZ(250);
prec.setIsolationWindowLowerOffset(50);
prec.setIsolationWindowUpperOffset(50);
precursors.push_back(prec);
spectrum.setPrecursors(precursors);
swath_map.addSpectrum(spectrum);
double lower, upper, center;
OpenSwathHelper::checkSwathMap(swath_map, lower, upper, center);
TEST_REAL_SIMILAR(lower, 200);
TEST_REAL_SIMILAR(upper, 300);
TEST_REAL_SIMILAR(center, 250);
}
END_SECTION
START_SECTION((static std::pair<double,double> estimateRTRange(OpenSwath::LightTargetedExperiment & exp)))
{
LightTargetedExperiment exp;
LightCompound pep1;
LightCompound pep2;
LightCompound pep3;
pep1.rt = -100.0;
pep2.rt = 900.0;
pep3.rt = 300.0;
std::vector<LightCompound> peptides;
peptides.push_back(pep1);
peptides.push_back(pep2);
peptides.push_back(pep3);
exp.compounds = peptides;
std::pair<double, double> range = OpenSwathHelper::estimateRTRange(exp);
TEST_REAL_SIMILAR(range.first, -100)
TEST_REAL_SIMILAR(range.second, 900)
}
END_SECTION
START_SECTION((static std::map<std::string, double> simple_find_best_feature(OpenMS::MRMFeatureFinderScoring::TransitionGroupMapType & transition_group_map,
bool useQualCutoff = false, double qualCutoff = 0.0)))
{
NOT_TESTABLE
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/OMSSACSVFile_test.cpp | .cpp | 1,908 | 63 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/OMSSACSVFile.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <vector>
///////////////////////////
START_TEST(OMSSACSVFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
OMSSACSVFile xml_file;
OMSSACSVFile* ptr;
OMSSACSVFile* nullPointer = nullptr;
ProteinIdentification protein_identification;
PeptideIdentificationList peptide_identifications;
PeptideIdentificationList peptide_identifications2;
String date_string_1;
String date_string_2;
PeptideHit peptide_hit;
START_SECTION((OMSSACSVFile()))
ptr = new OMSSACSVFile();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~OMSSACSVFile())
delete ptr;
END_SECTION
ptr = new OMSSACSVFile();
START_SECTION(void load(const String &filename, ProteinIdentification &protein_identification, std::vector< PeptideIdentification > &id_data) const)
ptr->load(OPENMS_GET_TEST_DATA_PATH("OMSSACSVFile_test_1.csv"), protein_identification, peptide_identifications);
TEST_EQUAL(protein_identification.getHits().size(), 0)
TEST_EQUAL(peptide_identifications.size(), 1)
END_SECTION
delete ptr;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MSstatsFile_test.cpp | .cpp | 1,580 | 37 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lukas Heumos $
// $Authors: Lukas Heumos $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/FORMAT/MSstatsFile.h>
using namespace OpenMS;
START_TEST(MSstatsFile, "$Id$")
START_SECTION(void OpenMS::MSstatsFile::storeLFQ(const OpenMS::String &filename, ConsensusMap &consensus_map,
const OpenMS::ExperimentalDesign& design, const StringList& reannotate_filenames,
const bool is_isotope_label_type, const String& bioreplicate, const String& condition,
const String& retention_time_summarization_method))
{
// tested via MSstatsConverter tool
}
END_SECTION
START_SECTION(void OpenMS::MSstatsFile::storeISO(const OpenMS::String &filename, ConsensusMap &consensus_map,
const OpenMS::ExperimentalDesign& design, const StringList& reannotate_filenames,
const String& bioreplicate, const String& condition,
const String& mixture, const String& retention_time_summarization_method))
{
// tested via MSstatsConverter tool
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/DigestionEnzymeProtein_test.cpp | .cpp | 8,103 | 280 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Xiao Liang $
// $Authors: Xiao Liang $
// --------------------------------------------------------------------------
//
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CHEMISTRY/DigestionEnzymeProtein.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(DigestionEnzymeProtein, "$Id$")
/////////////////////////////////////////////////////////////
DigestionEnzymeProtein* e_ptr = nullptr;
DigestionEnzymeProtein* e_null = nullptr;
START_SECTION((DigestionEnzymeProtein()))
e_ptr = new DigestionEnzymeProtein();
TEST_NOT_EQUAL(e_ptr, e_null)
END_SECTION
START_SECTION((virtual ~DigestionEnzymeProtein()))
delete e_ptr;
END_SECTION
ProteaseDB* db = ProteaseDB::getInstance();
e_ptr = new DigestionEnzymeProtein(*db->getEnzyme("Trypsin"));
String RKP("(?<=[RKP])(?!P)");
START_SECTION(DigestionEnzymeProtein(const DigestionEnzymeProtein& enzyme))
DigestionEnzymeProtein copy(*e_ptr);
TEST_EQUAL(copy, *e_ptr)
END_SECTION
START_SECTION(DigestionEnzymeProtein(const String& name,
const String& cleavage_regex,
const std::set<String> & synonyms,
String regex_description,
EmpiricalFormula n_term_gain,
EmpiricalFormula c_term_gain,
String psi_id,
String xtandem_id,
Int comet_id,
Int msgf_id,
Int omssa_id))
DigestionEnzymeProtein copy(e_ptr->getName(), e_ptr->getRegEx(), e_ptr->getSynonyms(), e_ptr->getRegExDescription(), e_ptr->getNTermGain(), e_ptr->getCTermGain(), e_ptr->getPSIID(), e_ptr->getXTandemID(), e_ptr->getCometID(), e_ptr->getMSGFID(), e_ptr->getOMSSAID());
TEST_EQUAL(copy.getName(), e_ptr->getName())
TEST_EQUAL(copy.getRegEx(), e_ptr->getRegEx())
TEST_EQUAL(copy.getRegExDescription(), e_ptr->getRegExDescription())
TEST_EQUAL(copy.getNTermGain(), e_ptr->getNTermGain())
TEST_EQUAL(copy.getCTermGain(), e_ptr->getCTermGain())
TEST_EQUAL(copy.getPSIID(), e_ptr->getPSIID())
TEST_EQUAL(copy.getXTandemID(), e_ptr->getXTandemID())
TEST_EQUAL(copy.getCometID(), e_ptr->getCometID())
TEST_EQUAL(copy.getMSGFID(), e_ptr->getMSGFID())
TEST_EQUAL(copy.getOMSSAID(), e_ptr->getOMSSAID())
END_SECTION
START_SECTION(DigestionEnzymeProtein& operator=(const DigestionEnzymeProtein& enzyme))
DigestionEnzymeProtein copy("","");
copy = *e_ptr;
TEST_EQUAL(copy, *e_ptr)
END_SECTION
START_SECTION(void setName(const String& name))
DigestionEnzymeProtein copy(*e_ptr);
e_ptr->setName("PepsinA");
TEST_NOT_EQUAL(copy, *e_ptr)
END_SECTION
START_SECTION(const String& getName() const)
TEST_EQUAL(e_ptr->getName(), "PepsinA")
END_SECTION
START_SECTION(void setSynonyms(const std::set<String>& synonyms))
DigestionEnzymeProtein copy(*e_ptr);
set<String> syn;
syn.insert("BLI");
syn.insert("BLA");
e_ptr->setSynonyms(syn);
TEST_NOT_EQUAL(*e_ptr, copy)
END_SECTION
START_SECTION(void addSynonym(const String& synonym))
DigestionEnzymeProtein copy(*e_ptr);
e_ptr->addSynonym("Tryp");
TEST_NOT_EQUAL(*e_ptr, copy)
END_SECTION
START_SECTION(const std::set<String>& getSynonyms() const)
TEST_EQUAL(e_ptr->getSynonyms().size(), 3)
END_SECTION
START_SECTION(void setRegEx(const String& cleavage_regex))
DigestionEnzymeProtein copy(*e_ptr);
e_ptr->setRegEx(RKP);
TEST_NOT_EQUAL(*e_ptr, copy)
END_SECTION
START_SECTION(const String& getRegEx() const)
TEST_EQUAL(e_ptr->getRegEx(), RKP)
END_SECTION
START_SECTION(void setRegExDescription(String value))
DigestionEnzymeProtein copy(*e_ptr);
e_ptr->setRegExDescription("cutting after R K unless followed by P");
TEST_NOT_EQUAL(*e_ptr, copy)
END_SECTION
START_SECTION(String getRegExDescription() const)
TEST_EQUAL(e_ptr->getRegExDescription(), "cutting after R K unless followed by P")
END_SECTION
START_SECTION(void setNTermGain(EmpiricalFormula value))
DigestionEnzymeProtein copy(*e_ptr);
e_ptr->setNTermGain(EmpiricalFormula("H2"));
TEST_NOT_EQUAL(*e_ptr, copy)
END_SECTION
START_SECTION(EmpiricalFormula getNTermGain() const)
TEST_EQUAL(e_ptr->getNTermGain(), EmpiricalFormula("H2"))
END_SECTION
START_SECTION(void setCTermGain(EmpiricalFormula value))
DigestionEnzymeProtein copy(*e_ptr);
e_ptr->setCTermGain(EmpiricalFormula("OH2"));
TEST_NOT_EQUAL(*e_ptr, copy)
END_SECTION
START_SECTION(EmpiricalFormula getCTermGain() const)
TEST_EQUAL(e_ptr->getCTermGain(), EmpiricalFormula("OH2"))
END_SECTION
START_SECTION(void setPSIID(String value))
DigestionEnzymeProtein copy(*e_ptr);
e_ptr->setPSIID("MS:000");
TEST_NOT_EQUAL(*e_ptr, copy)
END_SECTION
START_SECTION(String getPSIID() const)
TEST_EQUAL(e_ptr->getPSIID(), "MS:000")
END_SECTION
START_SECTION(void setXTandemID(String value))
DigestionEnzymeProtein copy(*e_ptr);
e_ptr->setXTandemID("[]|[]");
TEST_NOT_EQUAL(*e_ptr, copy)
END_SECTION
START_SECTION(String getXTandemID() const)
TEST_EQUAL(e_ptr->getXTandemID(), "[]|[]")
END_SECTION
START_SECTION(void setOMSSAID(UInt value))
DigestionEnzymeProtein copy(*e_ptr);
e_ptr->setOMSSAID(2);
TEST_NOT_EQUAL(*e_ptr, copy)
END_SECTION
START_SECTION(UInt getOMSSAID() const)
TEST_EQUAL(e_ptr->getOMSSAID(), 2)
END_SECTION
START_SECTION(bool operator==(const DigestionEnzymeProtein& enzyme) const)
DigestionEnzymeProtein r("","");
r = *e_ptr;
TEST_EQUAL(r == *e_ptr, true)
r.setName("other_name");
TEST_EQUAL(r == *e_ptr, false)
r = *e_ptr;
TEST_EQUAL(r == *e_ptr, true)
r.setRegEx("?<=[P]");
TEST_EQUAL(r == *e_ptr, false)
r = *e_ptr;
TEST_EQUAL(r == *e_ptr, true)
set<String> syns;
syns.insert("new_syn");
r.setSynonyms(syns);
TEST_EQUAL(r == *e_ptr, false)
r = *e_ptr;
TEST_EQUAL(r == *e_ptr, true)
r.setRegExDescription("new description");
TEST_EQUAL(r == *e_ptr, false)
r = *e_ptr;
TEST_EQUAL(r == *e_ptr, true)
r.setNTermGain(EmpiricalFormula("H2O"));
TEST_EQUAL(r == *e_ptr, false)
r = *e_ptr;
TEST_EQUAL(r == *e_ptr, true)
r.setCTermGain(EmpiricalFormula("H6O"));
TEST_EQUAL(r == *e_ptr, false)
r = *e_ptr;
TEST_EQUAL(r == *e_ptr, true)
r.setPSIID("new id");
TEST_EQUAL(r == *e_ptr, false)
r = *e_ptr;
TEST_EQUAL(r == *e_ptr, true)
r.setOMSSAID(-2);
TEST_EQUAL(r == *e_ptr, false)
END_SECTION
START_SECTION(bool operator!=(const DigestionEnzymeProtein& enzyme) const)
DigestionEnzymeProtein r("","");
r = *e_ptr;
TEST_EQUAL(r != *e_ptr, false)
r.setName("other_name");
TEST_EQUAL(r != *e_ptr, true)
r = *e_ptr;
TEST_EQUAL(r != *e_ptr, false)
r.setRegEx("?<=[P]");
TEST_EQUAL(r != *e_ptr, true)
r = *e_ptr;
TEST_EQUAL(r != *e_ptr, false)
set<String> syns;
syns.insert("new_syn");
r.setSynonyms(syns);
TEST_EQUAL(r != *e_ptr, true)
r = *e_ptr;
TEST_EQUAL(r != *e_ptr, false)
r.setRegExDescription("new description");
TEST_EQUAL(r != *e_ptr, true)
r = *e_ptr;
TEST_EQUAL(r != *e_ptr, false)
r.setNTermGain(EmpiricalFormula("H2O"));
TEST_EQUAL(r != *e_ptr, true)
r = *e_ptr;
TEST_EQUAL(r != *e_ptr, false)
r.setCTermGain(EmpiricalFormula("O"));
TEST_EQUAL(r != *e_ptr, true)
r = *e_ptr;
TEST_EQUAL(r != *e_ptr, false)
r.setPSIID("new id");
TEST_EQUAL(r != *e_ptr, true)
r = *e_ptr;
TEST_EQUAL(r != *e_ptr, false)
r.setOMSSAID(4);
TEST_EQUAL(r != *e_ptr, true)
END_SECTION
START_SECTION(bool operator==(String cleavage_regex) const)
TEST_EQUAL(*e_ptr == RKP, true)
END_SECTION
START_SECTION(bool operator!=(String cleavage_regex) const)
TEST_EQUAL(*e_ptr != "?<=[P]", true)
END_SECTION
delete e_ptr;
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/UniqueIdGenerator_test.cpp | .cpp | 4,593 | 148 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CONCEPT/UniqueIdGenerator.h>
#include <ctime>
#include <algorithm> // for std::sort and std::adjacent_find
// array_wrapper needs to be included before it is used
// only in boost1.64+. See issue #2790
#if OPENMS_BOOST_VERSION_MINOR >= 64
#include <boost/serialization/array_wrapper.hpp>
#endif
#include <boost/accumulators/statistics/covariance.hpp>
#include <boost/typeof/incr_registration_group.hpp>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(UniqueIdGenerator, "$Id$")
unsigned nofIdsToGenerate = 100000;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION((UniqueIdGenerator()))
{
// singleton has private ctor
NOT_TESTABLE;
}
END_SECTION
START_SECTION((~UniqueIdGenerator()))
{
// singleton has private dtor
NOT_TESTABLE;
}
END_SECTION
START_SECTION((static UInt64 getUniqueId()))
{
STATUS("OpenMS::UniqueIdGenerator::getUniqueId(): " << OpenMS::UniqueIdGenerator::getUniqueId());
/* test for collisions, test will be different for every test execution */
OpenMS::UniqueIdGenerator::setSeed(std::time(nullptr));
std::vector<OpenMS::UInt64> ids;
ids.reserve(nofIdsToGenerate);
for (unsigned i=0; i<nofIdsToGenerate; ++i)
{
ids.push_back(OpenMS::UniqueIdGenerator::getUniqueId());
}
std::sort(ids.begin(), ids.end());
// check if the generated ids contain (at least) two equal ones
std::vector<OpenMS::UInt64>::iterator iter = std::adjacent_find(ids.begin(), ids.end());
TEST_EQUAL(iter == ids.end(), true);
}
END_SECTION
START_SECTION((static void setSeed(UInt seed)))
{
UInt one_moment_in_time = 546666321;
// OpenMS::DateTime one_moment_in_time;
// one_moment_in_time.set(5,4,6666,3,2,1);
// OpenMS::UniqueIdGenerator::setSeed(one_moment_in_time);
/* check if the generator changed */
UInt64 large_int = 0;
std::vector<UInt64> unique_ids;
large_int = 4039984684862977299U;
unique_ids.push_back(large_int);
large_int = 11561668883169444769U;
unique_ids.push_back(large_int);
large_int = 8153960635892418594U;
unique_ids.push_back(large_int);
large_int = 12940485248168291983U;
unique_ids.push_back(large_int);
large_int = 11522917731873626020U;
unique_ids.push_back(large_int);
large_int = 4387255872055054320U;
unique_ids.push_back(large_int);
OpenMS::UniqueIdGenerator::setSeed(one_moment_in_time);
for (Size i=0; i<unique_ids.size(); ++i)
{
OpenMS::UInt64 uid = OpenMS::UniqueIdGenerator::getUniqueId();
TEST_EQUAL(uid,unique_ids[i]);
}
/* check if the same sequence is generated form the same seed */
std::vector<OpenMS::UInt64> ids;
ids.reserve(nofIdsToGenerate);
OpenMS::UniqueIdGenerator::setSeed(one_moment_in_time);
for (unsigned i=0; i<nofIdsToGenerate; ++i)
{
ids.push_back(OpenMS::UniqueIdGenerator::getUniqueId());
}
std::vector<OpenMS::UInt64> ids2;
ids2.reserve(nofIdsToGenerate);
OpenMS::UniqueIdGenerator::setSeed(one_moment_in_time);
for (unsigned i=0; i<nofIdsToGenerate; ++i)
{
ids2.push_back(OpenMS::UniqueIdGenerator::getUniqueId());
}
for ( unsigned i = 0; i < nofIdsToGenerate; ++i )
{
if(ids[i] != ids2[i])
{
TEST_EQUAL(ids[i], ids2[i]);
}
}
}
END_SECTION
START_SECTION([EXTRA] multithreaded example)
{
/* test for collisions, test will be different for every test execution */
OpenMS::UniqueIdGenerator::setSeed(std::time(nullptr));
std::vector<OpenMS::UInt64> ids;
ids.reserve(nofIdsToGenerate);
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(nofIdsToGenerate); ++i)
{
OpenMS::UInt64 tmp = OpenMS::UniqueIdGenerator::getUniqueId();
#pragma omp critical (add_test)
{
ids.push_back(tmp);
}
}
std::sort(ids.begin(), ids.end());
// check if the generated ids contain (at least) two equal ones
std::vector<OpenMS::UInt64>::iterator iter = std::adjacent_find(ids.begin(), ids.end());
TEST_EQUAL(iter == ids.end(), true);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MassTraceDetection_test.cpp | .cpp | 7,189 | 224 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Erhan Kenar$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/FORMAT/MzMLFile.h>
///////////////////////////
#include <OpenMS/FEATUREFINDER/MassTraceDetection.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
/// provide access to private functions
class MassTraceDetectionAccess : public OpenMS::MassTraceDetection
{
public:
using OpenMS::MassTraceDetection::updateIterativeWeightedMean_;
};
START_TEST(MassTraceDetection, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MassTraceDetection* ptr = nullptr;
MassTraceDetection* null_ptr = nullptr;
START_SECTION(MassTraceDetection())
{
ptr = new MassTraceDetection();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~MassTraceDetection())
{
delete ptr;
}
END_SECTION
MassTraceDetection test_mtd;
START_SECTION((void updateIterativeWeightedMean_(const double &, const double &, double &, double &, double &)))
{
double centroid_mz(150.22), centroid_int(25000000);
double new_mz1(150.34), new_int1(23043030);
double new_mz2(150.11), new_int2(1932392);
std::vector<double> mzs, ints;
mzs.push_back(centroid_mz);
mzs.push_back(new_mz1);
mzs.push_back(new_mz2);
ints.push_back(centroid_int);
ints.push_back(new_int1);
ints.push_back(new_int2);
double total_weight1(centroid_int + new_int1);
double total_weight2(centroid_int + new_int1 + new_int2);
double wmean1((centroid_mz * centroid_int + new_mz1 * new_int1)/total_weight1);
double wmean2((centroid_mz * centroid_int + new_mz1 * new_int1 + new_mz2 * new_int2)/total_weight2);
double prev_count(centroid_mz * centroid_int);
double prev_denom(centroid_int);
MassTraceDetectionAccess::updateIterativeWeightedMean_(new_mz1, new_int1, centroid_mz, prev_count, prev_denom);
TEST_REAL_SIMILAR(centroid_mz, wmean1);
MassTraceDetectionAccess::updateIterativeWeightedMean_(new_mz2, new_int2, centroid_mz, prev_count, prev_denom);
TEST_REAL_SIMILAR(centroid_mz, wmean2);
}
END_SECTION
// load a mzML file for testing the algorithm
PeakMap input;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MassTraceDetection_input1.mzML"),input);
Size exp_mt_lengths[3] = {86, 31, 16};
double exp_mt_rts[3] = {348.667, 347.107, 346.888}; // centroid RTs should be reasonably similar (isotopic traces)
double exp_mt_mzs[3] = {437.26675, 438.27241, 439.27594};
double exp_mt_ints[3] = {3381.72226139326, 664.763828332733, 109.490108620676};
std::vector<MassTrace> output_mt;
Param p_mtd = MassTraceDetection().getDefaults();
p_mtd.setValue("min_trace_length", 3.0);
START_SECTION((void run(const PeakMap &, std::vector< MassTrace > &)))
{
test_mtd.run(input, output_mt);
// with default parameters, only 2 of 3 traces will be found
TEST_EQUAL(output_mt.size(), 2);
// if min_trace_length is set to 3 seconds, another mass trace is detected
test_mtd.setParameters(p_mtd);
output_mt.clear();
test_mtd.run(input, output_mt);
TEST_EQUAL(output_mt.size(), 3);
for (Size i = 0; i < output_mt.size(); ++i)
{
TEST_EQUAL(output_mt[i].getSize(), exp_mt_lengths[i]);
TEST_REAL_SIMILAR(output_mt[i].getCentroidRT(), exp_mt_rts[i]);
TEST_REAL_SIMILAR(output_mt[i].getCentroidMZ(), exp_mt_mzs[i]);
TEST_REAL_SIMILAR(output_mt[i].computePeakArea(), exp_mt_ints[i]);
}
// Regression test for bug #1633
// Test by adding MS2 spectra to the input
{
PeakMap input_new;
MSSpectrum s;
s.setMSLevel(2);
{
Peak1D p;
p.setMZ( 500 );
p.setIntensity( 6000 );
s.push_back(p);
}
// add a few additional MS2 spectra in front
for (Size i = 0; i < input.size(); ++i)
{
input_new.addSpectrum(s);
}
// now add the "real" spectra at the end
for (Size i = 0; i < input.size(); ++i)
{
input_new.addSpectrum(input[i]);
}
output_mt.clear();
test_mtd.run(input_new, output_mt);
TEST_EQUAL(output_mt.size(), 3);
for (Size i = 0; i < output_mt.size(); ++i)
{
TEST_EQUAL(output_mt[i].getSize(), exp_mt_lengths[i]);
TEST_REAL_SIMILAR(output_mt[i].getCentroidRT(), exp_mt_rts[i]);
TEST_REAL_SIMILAR(output_mt[i].getCentroidMZ(), exp_mt_mzs[i]);
TEST_REAL_SIMILAR(output_mt[i].computePeakArea(), exp_mt_ints[i]);
}
}
}
END_SECTION
std::vector<MassTrace> filt;
//START_SECTION((void filterByPeakWidth(std::vector< MassTrace > &, std::vector< MassTrace > &)))
//{
// test_mtd.filterByPeakWidth(output_mt, filt);
// TEST_EQUAL(output_mt.size(), filt.size());
//// for (Size i = 0; i < output_mt.size(); ++i)
//// {
//// TEST_EQUAL(output_mt[i].getFWHMScansNum(), filt[i].getFWHMScansNum());
//// }
//}
//END_SECTION
PeakMap::ConstAreaIterator mt_it1 = input.areaBeginConst(335.0, 385.0, 437.1, 437.4);
PeakMap::ConstAreaIterator mt_it2 = input.areaBeginConst(335.0, 385.0, 438.2, 438.4);
PeakMap::ConstAreaIterator mt_it3 = input.areaBeginConst(335.0, 385.0, 439.2, 439.4);
std::vector<MassTrace> found_mtraces;
PeakMap::ConstAreaIterator mt_end = input.areaEndConst();
START_SECTION((void run(PeakMap::ConstAreaIterator &begin, PeakMap::ConstAreaIterator &end, std::vector< MassTrace > &found_masstraces)))
{
NOT_TESTABLE
// test_mtd.run(mt_it1, mt_end, found_mtraces);
// TEST_EQUAL(found_mtraces.size(), 1);
// TEST_EQUAL(found_mtraces[0].getSize(), exp_mt_lengths[0]);
// TEST_REAL_SIMILAR(found_mtraces[0].getCentroidRT(), exp_mt_rts[0]);
// TEST_REAL_SIMILAR(found_mtraces[0].getCentroidMZ(), exp_mt_mzs[0]);
// TEST_REAL_SIMILAR(found_mtraces[0].computePeakArea(), exp_mt_ints[0]);
// found_mtraces.clear();
// test_mtd.run(mt_it2, mt_end, found_mtraces);
// TEST_EQUAL(found_mtraces.size(), 1);
// TEST_EQUAL(found_mtraces[0].getSize(), exp_mt_lengths[1]);
// TEST_REAL_SIMILAR(found_mtraces[0].getCentroidRT(), exp_mt_rts[1]);
// TEST_REAL_SIMILAR(found_mtraces[0].getCentroidMZ(), exp_mt_mzs[1]);
// TEST_REAL_SIMILAR(found_mtraces[0].computePeakArea(), exp_mt_ints[1]);
// found_mtraces.clear();
// test_mtd.run(mt_it3, mt_end, found_mtraces);
// TEST_EQUAL(found_mtraces.size(), 1);
// TEST_EQUAL(found_mtraces[0].getSize(), exp_mt_lengths[0]);
// TEST_REAL_SIMILAR(found_mtraces[0].getCentroidRT(), exp_mt_rts[2]);
// TEST_REAL_SIMILAR(found_mtraces[0].getCentroidMZ(), exp_mt_mzs[2]);
// TEST_REAL_SIMILAR(found_mtraces[0].computePeakArea(), exp_mt_ints[2]);
// found_mtraces.clear();
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IndexedMzMLFile_test.cpp | .cpp | 11,361 | 312 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/HANDLERS/IndexedMzMLHandler.h>
///////////////////////////
#include <OpenMS/FORMAT/FileTypes.h>
// for comparison
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FORMAT/MzMLFile.h>
using namespace OpenMS;
using namespace OpenMS::Internal;
using namespace std;
///////////////////////////
START_TEST(IndexedMzMLHandler, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IndexedMzMLHandler* ptr = nullptr;
IndexedMzMLHandler* nullPointer = nullptr;
START_SECTION((IndexedMzMLHandler(String filename) ))
ptr = new IndexedMzMLHandler(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~IndexedMzMLHandler()))
delete ptr;
END_SECTION
START_SECTION((IndexedMzMLHandler() ))
ptr = new IndexedMzMLHandler();
TEST_NOT_EQUAL(ptr, nullPointer)
delete ptr;
END_SECTION
START_SECTION((IndexedMzMLHandler(const IndexedMzMLHandler &source)))
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
IndexedMzMLHandler file2(file);
TEST_EQUAL(file.getParsingSuccess(), file2.getParsingSuccess())
TEST_EQUAL(file.getNrSpectra(), file2.getNrSpectra())
TEST_EQUAL(file.getNrChromatograms(), file2.getNrChromatograms())
ABORT_IF(file.getNrSpectra() != 2)
TEST_EQUAL(file.getSpectrumById(0)->getMZArray()->data == file2.getSpectrumById(0)->getMZArray()->data, true)
TEST_EQUAL(file.getSpectrumById(0)->getIntensityArray()->data == file2.getSpectrumById(0)->getIntensityArray()->data, true)
TEST_EQUAL(file.getSpectrumById(1)->getMZArray()->data == file2.getSpectrumById(1)->getMZArray()->data, true)
TEST_EQUAL(file.getSpectrumById(1)->getIntensityArray()->data == file2.getSpectrumById(1)->getIntensityArray()->data, true)
ABORT_IF(file.getNrChromatograms() != 1)
TEST_EQUAL(file.getChromatogramById(0)->getTimeArray()->data == file2.getChromatogramById(0)->getTimeArray()->data, true)
TEST_EQUAL(file.getChromatogramById(0)->getIntensityArray()->data == file2.getChromatogramById(0)->getIntensityArray()->data, true)
/*
TEST_EQUAL(file.getChromatogramById(0) == file2.getChromatogramById(0), true)
TEST_EQUAL(file.getSpectrumById(1), file2.getSpectrumById(1))
*/
}
END_SECTION
START_SECTION(( bool getParsingSuccess() const))
{
{
IndexedMzMLHandler file;
TEST_EQUAL(file.getParsingSuccess(), false)
TEST_EXCEPTION(Exception::FileNotFound, file.openFile(OPENMS_GET_TEST_DATA_PATH("fileDoesNotExist")));
TEST_EQUAL(file.getParsingSuccess(), false)
file.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML") );
TEST_EQUAL(file.getParsingSuccess(), true)
}
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"));
TEST_EQUAL(file.getParsingSuccess(), false)
}
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
TEST_EQUAL(file.getParsingSuccess(), true)
}
}
END_SECTION
START_SECTION(( void openFile(String filename) ))
{
IndexedMzMLHandler file;
TEST_EXCEPTION(Exception::FileNotFound, file.openFile(OPENMS_GET_TEST_DATA_PATH("fileDoesNotExist")))
TEST_EQUAL(file.getParsingSuccess(), false)
file.openFile(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"));
TEST_EQUAL(file.getParsingSuccess(), false)
file.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
TEST_EQUAL(file.getParsingSuccess(), true)
}
END_SECTION
START_SECTION(( size_t getNrSpectra() const ))
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
TEST_EQUAL(file.getNrSpectra(), 2)
}
END_SECTION
START_SECTION(( size_t getNrChromatograms() const ))
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
TEST_EQUAL(file.getNrChromatograms(), 1)
}
END_SECTION
START_SECTION(( OpenMS::Interfaces::SpectrumPtr getSpectrumById(int id) ))
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp);
TEST_EQUAL(file.getNrSpectra(), exp.getSpectra().size())
OpenMS::Interfaces::SpectrumPtr spec = file.getSpectrumById(0);
TEST_EQUAL(spec->getMZArray()->data.size(), exp.getSpectra()[0].size() )
TEST_EQUAL(spec->getIntensityArray()->data.size(), exp.getSpectra()[0].size() )
// Test Exceptions
TEST_EXCEPTION(Exception::IllegalArgument,file.getSpectrumById(-1));
TEST_EXCEPTION(Exception::IllegalArgument,file.getSpectrumById( file.getNrSpectra()+1));
{
IndexedMzMLHandler file;
TEST_EXCEPTION(Exception::FileNotFound, file.openFile(OPENMS_GET_TEST_DATA_PATH("fileDoesNotExist")));
TEST_EQUAL(file.getParsingSuccess(), false)
TEST_EXCEPTION(Exception::ParseError,file.getSpectrumById( 0 ));
}
}
END_SECTION
START_SECTION(( OpenMS::MSSpectrum getMSSpectrumById(int id) ))
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp);
TEST_EQUAL(file.getNrSpectra(), exp.getSpectra().size())
OpenMS::MSSpectrum spec = file.getMSSpectrumById(0);
TEST_EQUAL(spec.size(), exp.getSpectra()[0].size() )
// TEST_EQUAL(spec.getNativeID(), exp.getSpectra()[0].getNativeID() )
// Test Exceptions
TEST_EXCEPTION(Exception::IllegalArgument,file.getMSSpectrumById(-1));
TEST_EXCEPTION(Exception::IllegalArgument,file.getMSSpectrumById( file.getNrSpectra()+1));
{
IndexedMzMLHandler file;
TEST_EXCEPTION(Exception::FileNotFound, file.openFile(OPENMS_GET_TEST_DATA_PATH("fileDoesNotExist")));
TEST_EQUAL(file.getParsingSuccess(), false)
TEST_EXCEPTION(Exception::ParseError,file.getMSSpectrumById( 0 ));
}
}
END_SECTION
START_SECTION(( void getMSSpectrumByNativeId(std::string id, OpenMS::MSSpectrum& s) ))
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp);
TEST_EQUAL(file.getNrSpectra(), exp.getSpectra().size())
OpenMS::MSSpectrum spec;
file.getMSSpectrumByNativeId("controllerType=0 controllerNumber=1 scan=1", spec);
TEST_EQUAL(spec.size(), exp.getSpectra()[0].size() )
TEST_EQUAL(spec.getNativeID(), exp.getSpectra()[0].getNativeID() )
// Test Exceptions
TEST_EXCEPTION(Exception::IllegalArgument,file.getMSSpectrumByNativeId("TEST", spec));
{
IndexedMzMLHandler file;
TEST_EXCEPTION(Exception::FileNotFound, file.openFile(OPENMS_GET_TEST_DATA_PATH("fileDoesNotExist")));
TEST_EQUAL(file.getParsingSuccess(), false)
TEST_EXCEPTION(Exception::IllegalArgument, file.getMSSpectrumByNativeId( "TEST", spec ));
}
}
END_SECTION
START_SECTION(( OpenMS::Interfaces::ChromatogramPtr getChromatogramById(int id) ))
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp);
TEST_EQUAL(file.getNrChromatograms(), exp.getChromatograms().size())
OpenMS::Interfaces::ChromatogramPtr chrom = file.getChromatogramById(0);
TEST_EQUAL(chrom->getTimeArray()->data.size(), exp.getChromatograms()[0].size() )
TEST_EQUAL(chrom->getIntensityArray()->data.size(), exp.getChromatograms()[0].size() )
}
END_SECTION
START_SECTION(( OpenMS::MSChromatogram getMSChromatogramById(int id) ))
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp);
TEST_EQUAL(file.getNrChromatograms(), exp.getChromatograms().size())
OpenMS::MSChromatogram chrom = file.getMSChromatogramById(0);
TEST_EQUAL(chrom.size(), exp.getChromatograms()[0].size() )
TEST_EQUAL(chrom.getNativeID(), exp.getChromatograms()[0].getNativeID() )
}
END_SECTION
START_SECTION(( void getMSChromatogramByNativeId(std::string id, OpenMS::MSChromatogram& c) ))
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp);
TEST_EQUAL(file.getNrChromatograms(), exp.getChromatograms().size())
OpenMS::MSChromatogram chrom;
file.getMSChromatogramByNativeId("TIC", chrom);
TEST_EQUAL(chrom.size(), exp.getChromatograms()[0].size() )
TEST_EQUAL(chrom.getNativeID(), exp.getChromatograms()[0].getNativeID() )
TEST_EXCEPTION(Exception::IllegalArgument,file.getMSChromatogramByNativeId("TEST", chrom));
{
IndexedMzMLHandler file;
TEST_EXCEPTION(Exception::FileNotFound, file.openFile(OPENMS_GET_TEST_DATA_PATH("fileDoesNotExist")));
TEST_EQUAL(file.getParsingSuccess(), false)
TEST_EXCEPTION(Exception::IllegalArgument, file.getMSChromatogramByNativeId( "TEST", chrom ));
}
}
END_SECTION
START_SECTION(([EXTRA] load broken file))
{
// Contains an unparseable value (2^64) in the indexListOffset field that
// will not fit into a long long.
// NOTE: this will not be true on all systems, if long long is larger than 64
// bits it will fit, however parsing will fail since the file is not actually
// 2^64 bit long...
if ( sizeof(long long)*8 <= 64 )
{
TEST_EXCEPTION(Exception::ConversionError, new IndexedMzMLHandler(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_2_broken.mzML")))
}
else
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_2_broken.mzML"));
TEST_EQUAL(file.getParsingSuccess(), false)
}
}
END_SECTION
START_SECTION(([EXTRA] load broken file))
{
// Contains an value (2^63-1) in the indexListOffset field that should not
// trigger an exception - however parsing will fail since the file is
// actually shorter.
if (sizeof(std::streampos)*8 > 32 )
{
IndexedMzMLHandler file(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_3_broken.mzML"));
TEST_EQUAL(file.getParsingSuccess(), false)
}
else
{
//
// On systems that use 32 bit or less to represent std::streampos, we
// cannot fit our value in the indexListOffset (2^63-1) into std::streampos
// -> this should throw an exception in the constructor which can test here
// instead when loading the file.
//
// This code path is hard to test on most machines since almost all modern
// compilers and filesystems support file access for files > 2 GB
// Manually, one can cast the indexoffset variable to int to trigger this
// behavior in IndexedMzMLDecoder.cpp
//
TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError,
new IndexedMzMLHandler(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_3_broken.mzML")),
"Could not convert string '9223372036854775807' to an integer on your system." )
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/TransformationModelLowess_test.cpp | .cpp | 10,325 | 190 | // 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/MAPMATCHING/TransformationModel.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h>
///////////////////////////
START_TEST(TransformationModelLowess, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
TransformationModelLowess* 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));
Param params_default;
TransformationModelLowess::getDefaultParameters(params_default);
START_SECTION((TransformationModelLowess(const DataPoints&, const Param&)))
{
TEST_EXCEPTION(Exception::IllegalArgument, TransformationModelLowess tm(empty, params_default)); // need data
ptr = new TransformationModelLowess(data, params_default);
TEST_NOT_EQUAL(ptr, 0)
}
END_SECTION
START_SECTION((~TransformationModelLowess()))
{
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_spl[] = {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};
double pred_low[] = {0.81549, 0.62377, 0.432051, 0.240331, 0.0486111, -0.142406, -0.326079, -0.505898, -0.656341, -0.774182, -0.879421, -0.948104, -0.973173, -0.977378, -0.919574, -0.829349, -0.716313, -0.546735, -0.398708, -0.236083, -0.0312524, 0.171936, 0.376142, 0.553262, 0.711474, 0.825752, 0.868956, 0.873851, 0.881359, 0.905248, 0.888206, 0.814595, 0.694699, 0.538594, 0.356359, 0.158072, -0.0192127, -0.157386, -0.295559, -0.433733, -0.571906};
/* R code:
*
* Note that compared to the spline, the lowess contains a linear model and
* is thus less suited for highly non-linear data such as a sine. However, it
* performs quite well on the data.
*
x = c(-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)
y = c(-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)
pred_spl = c(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)
pred_low = c(0.81549, 0.62377, 0.432051, 0.240331, 0.0486111, -0.142406, -0.326079, -0.505898, -0.656341, -0.774182, -0.879421, -0.948104, -0.973173, -0.977378, -0.919574, -0.829349, -0.716313, -0.546735, -0.398708, -0.236083, -0.0312524, 0.171936, 0.376142, 0.553262, 0.711474, 0.825752, 0.868956, 0.873851, 0.881359, 0.905248, 0.888206, 0.814595, 0.694699, 0.538594, 0.356359, 0.158072, -0.0192127, -0.157386, -0.295559, -0.433733, -0.571906)
plot(x, y, xlim=c(-4,4))
lines( seq(-4, 4.1, 0.2), pred_spl, col="blue")
lines( seq(-4, 4.1, 0.2), pred_low, col="red")
*/
data.resize(31);
for (Size i = 0; i < 31; ++i)
{
data[i] = make_pair(x[i], y[i]);
}
Param params;
params.setValue("span", 0.3); // use a very low span value for non-linear data (only use 30 % of all points at a time ...)
params.setValue("num_iterations", 3);
params.setValue("delta", -1.0);
params.setValue("interpolation_type", "cspline");
params.setValue("extrapolation_type", "four-point-linear");
TransformationModelLowess tm(data, params);
vector<double> results;
Size index = 0;
for (double v = -4; v < 4.1; v += 0.2, index++)
{
TEST_REAL_SIMILAR(tm.evaluate(v), pred_low[index]);
}
// test extrapolation:
params.setValue("extrapolation_type", "four-point-linear");
TransformationModelLowess tm_lin(data, params);
TEST_REAL_SIMILAR(tm_lin.evaluate(-4.0), 0.815490292172986);
TEST_REAL_SIMILAR(tm_lin.evaluate(4.0), -0.571905836956494);
params.setValue("extrapolation_type", "two-point-linear");
TransformationModelLowess tm_const(data, params);
TEST_REAL_SIMILAR(tm_const.evaluate(-4.0), -0.04240732863);
TEST_REAL_SIMILAR(tm_const.evaluate(4.0), 0.046870277);
params.setValue("extrapolation_type", "global-linear");
TransformationModelLowess tm_global(data, params);
TEST_REAL_SIMILAR(tm_global.evaluate(-4.0), -0.9501004);
TEST_REAL_SIMILAR(tm_global.evaluate(4.0), 1.08486397);
}
END_SECTION
START_SECTION((void getParameters(Param& params) const))
{
Param p_in;
p_in.setValue("span", 0.3);
p_in.setValue("num_iterations", 8);
p_in.setValue("delta", 1.0);
p_in.setValue("extrapolate", "b_spline");
p_in.setValue("interpolation_type", "cspline");
p_in.setValue("extrapolation_type", "four-point-linear");
TransformationModelLowess tm(data, p_in);
TEST_EQUAL(tm.getParameters().getValue("num_iterations"),
p_in.getValue("num_iterations"));
}
END_SECTION
// auto-span selection via CV test
START_SECTION((auto span selection chooses larger span on tie and persists params))
{
using OpenMS::TransformationModel;
using OpenMS::TransformationModelLowess;
using OpenMS::Param;
// Create perfectly linear anchors: y = 2x + 1 (deterministic; LOO CV with n=11)
TransformationModel::DataPoints data;
for (int i = 0; i <= 10; ++i)
{
const double x = static_cast<double>(i);
data.push_back(std::make_pair(x, 2.0 * x + 1.0));
}
// Params: enable auto-span, provide a small grid, keep everything deterministic
Param p;
TransformationModelLowess::getDefaultParameters(p);
p.setValue("span", 0.0); // trigger auto when auto_span=true
p.setValue("auto_span", "true");
p.setValue("auto_span_grid", "0.3,0.8"); // two candidates
p.setValue("auto_metric", "mae"); // MAE on a perfect line → tie
p.setValue("num_iterations", 0); // deterministic LOWESS (no robust loops)
p.setValue("delta", -1.0); // auto delta
p.setValue("interpolation_type", "cspline");
p.setValue("extrapolation_type", "four-point-linear");
TransformationModelLowess tm(data, p);
// 1) The selected span should be the larger one (tie broken by preferring larger span)
Param used = tm.getParameters();
TEST_EQUAL(used.getValue("auto_span").toString(), "false"); // auto turned off after selection
const double chosen_span = static_cast<double>(used.getValue("span"));
TEST_REAL_SIMILAR(chosen_span, 0.8);
// 2) The fitted model should reproduce the linear mapping (LOWESS reproduces degree-1 exactly)
TEST_REAL_SIMILAR(tm.evaluate(0.0), 1.0);
TEST_REAL_SIMILAR(tm.evaluate(5.0), 11.0);
TEST_REAL_SIMILAR(tm.evaluate(10.0), 21.0);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SignalToNoiseEstimatorMedianRapid_test.cpp | .cpp | 5,458 | 130 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMedianRapid.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(SignalToNoiseEstimatorMedianRapid, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
SignalToNoiseEstimatorMedianRapid* ptr = nullptr;
SignalToNoiseEstimatorMedianRapid* nullPointer = nullptr;
START_SECTION((SignalToNoiseEstimatorMedianRapid()))
ptr = new SignalToNoiseEstimatorMedianRapid(200);
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~SignalToNoiseEstimatorMedianRapid()))
delete ptr;
END_SECTION
/*
* Python code:
*
import random
mz = [200 + 10*i for i in range(40)]
int = [ random.random() * 10 for i in range(40)]
int = [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]
import numpy
numpy.median( int[0:21] )
numpy.median( int[21:40] )
*/
START_SECTION( (NoiseEstimator estimateNoise(std::vector<double>& mz_array, std::vector<double>& int_array)))
{
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]) );
// Large window (200)
{
SignalToNoiseEstimatorMedianRapid sne(200);
SignalToNoiseEstimatorMedianRapid::NoiseEstimator e = sne.estimateNoise(mz, intensity);
TEST_REAL_SIMILAR(e.get_noise_even(200), 5.71395) // numpy.median(int[:20])
TEST_REAL_SIMILAR(e.get_noise_even(500), 4.98395) // numpy.median(int[20:])
TEST_REAL_SIMILAR(e.get_noise_odd(200), 5.71395) // numpy.median(int[:10])
TEST_REAL_SIMILAR(e.get_noise_odd(400), 5.26325) // numpy.median(int[10:30])
TEST_REAL_SIMILAR(e.get_noise_odd(500), 4.98395) // numpy.median(int[30:])
TEST_REAL_SIMILAR(e.get_noise_value(200), 5.71395) // numpy.median(int[:20])
TEST_REAL_SIMILAR(e.get_noise_value(410), (5.26325+4.98395)/2 ) // (numpy.median(int[10:30])+numpy.median(int[30:])) /2
TEST_REAL_SIMILAR(e.get_noise_value(500), 4.98395) // numpy.median(int[30:])
}
// Smaller window (100)
{
SignalToNoiseEstimatorMedianRapid sne(100);
SignalToNoiseEstimatorMedianRapid::NoiseEstimator e = sne.estimateNoise(mz, intensity);
TEST_REAL_SIMILAR(e.get_noise_even(250), 5.71395) // numpy.median( int[:10] )
TEST_REAL_SIMILAR(e.get_noise_even(350), 5.62315 ) // numpy.median( int[10:20] )
TEST_REAL_SIMILAR(e.get_noise_even(450), 4.97975 ) // numpy.median( int[20:30] )
TEST_REAL_SIMILAR(e.get_noise_even(550), 4.98395) // numpy.median( int[30:] )
TEST_REAL_SIMILAR(e.get_noise_odd(200), 5.4332) // numpy.median( int[:5] )
TEST_REAL_SIMILAR(e.get_noise_odd(300), 7.2765) // numpy.median( int[5:15] )
TEST_REAL_SIMILAR(e.get_noise_odd(400), 4.97975) // numpy.median( int[15:25] )
TEST_REAL_SIMILAR(e.get_noise_odd(500), 5.49885) // numpy.median( int[25:35] )
TEST_REAL_SIMILAR(e.get_noise_value(510), (5.49885+4.98395)/2) // (numpy.median( int[25:35] ) + numpy.median( int[30:] ) )/2
}
// Uneven window size (50)
{
SignalToNoiseEstimatorMedianRapid sne(50);
SignalToNoiseEstimatorMedianRapid::NoiseEstimator e = sne.estimateNoise(mz, intensity);
TEST_REAL_SIMILAR(e.get_noise_even(220), 5.4332 ) // numpy.median( int[:5] )
TEST_REAL_SIMILAR(e.get_noise_even(420), 5.1042 ) // numpy.median(int[20:25])
TEST_REAL_SIMILAR(e.get_noise_even(460), 4.2377 ) // numpy.median(int[25:30])
}
// Uneven window size (110)
{
SignalToNoiseEstimatorMedianRapid sne(110);
SignalToNoiseEstimatorMedianRapid::NoiseEstimator e = sne.estimateNoise(mz, intensity);
TEST_REAL_SIMILAR(e.get_noise_even(250), 5.809 ) // numpy.median( int[:11] )
TEST_REAL_SIMILAR(e.get_noise_even(350), 5.139 ) // numpy.median( int[11:22] )
TEST_REAL_SIMILAR(e.get_noise_even(450), 5.05890) // numpy.median( int[22:33] )
TEST_REAL_SIMILAR(e.get_noise_even(550), 4.909 ) // numpy.median( int[33:] )
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ClassTest_test.cpp | .cpp | 31,969 | 933 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Clemens Groepl $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/PrecisionWrapper.h>
#include <fstream>
using namespace OpenMS;
bool intentionally_failed_tests_okay = true;
/* This macro turns a previous failure into success. This is used for
testing the test macros. It should follow the subtest immediately; preferably
on the same line of code. */
#define FAILURE_IS_SUCCESS \
if ( !TEST::this_test ) \
{ \
TEST::this_test = true; \
TEST::test = intentionally_failed_tests_okay; \
if (TEST::verbose > 1) \
{ \
TEST::initialNewline(); \
stdcout << __FILE__ ":" << __LINE__ << \
": note: The preceeding test was supposed to fail intentionally. => SUCCESS" << \
std::endl; \
} \
} \
else \
{ \
TEST::this_test = false; \
intentionally_failed_tests_okay = false; \
TEST::test = intentionally_failed_tests_okay; \
if (TEST::verbose > 1) \
{ \
TEST::initialNewline(); \
stdcout << __FILE__ ":" << __LINE__ << \
" error: The preceeding test was supposed to fail, but it did not. => FAILURE" << \
std::endl; \
} \
}
// the only error here is that we do not follow the coding convention ;-)
void
throw_a_Precondition_Exception()
{
throw OpenMS::Exception::Precondition(__FILE__,__LINE__, OPENMS_PRETTY_FUNCTION,
"intentional Exception::Preconditon raised by throw_a_Precondition_Exception()");
}
// the only error here is that we do not follow the coding convention ;-)
void
throw_a_Postcondition_Exception()
{
throw OpenMS::Exception::Postcondition(__FILE__,__LINE__, OPENMS_PRETTY_FUNCTION,
"intentional Exception::Postconditon raised by throw_a_Postcondition_Exception()");
}
START_TEST(ClassTest, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION("empty section without NOT_TESTABLE")
{
STATUS("This test should complain about no subtests being performed.");
}
END_SECTION
START_SECTION("empty section with NOT_TESTABLE")
{
STATUS("This test should NOT complain about no subtests being performed.");
NOT_TESTABLE;
}
END_SECTION
START_SECTION("TOLERANCE_ABSOLUTE()")
{
TOLERANCE_ABSOLUTE(0.55);
TEST_EQUAL(Internal::ClassTest::absdiff_max_allowed, 0.55);
}
END_SECTION
START_SECTION("TOLERANCE_RELATIVE()")
{
TOLERANCE_RELATIVE(0.66);
TEST_EQUAL(Internal::ClassTest::ratio_max_allowed, 0.66);
}
END_SECTION
START_SECTION("NEW_TMP_FILE()")
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
TEST::this_test = (!tmp_filename.empty());
TEST_EQUAL(!tmp_filename.empty(), true);
END_SECTION
START_SECTION("TEST_EQUAL()")
{
TEST_EQUAL(2, 3); FAILURE_IS_SUCCESS;
TEST_EQUAL(2, 2);
TEST_EQUAL(2, 3.0); FAILURE_IS_SUCCESS;
TEST_EQUAL(2, 2.0);
TEST_EQUAL(2, 2.0f);
TEST_EQUAL(2.0, 2);
TEST_EQUAL(2.0, 2.0f);
TEST_EQUAL(2.0f, 2);
TEST_EQUAL(2.0f, 2.0);
enum Enum1 { A, B, C };
enum Enum2 { AA, BB, CC };
TEST_EQUAL(Enum1::A, Enum1::A);
TEST_EQUAL(Enum1::A, Enum1::B); FAILURE_IS_SUCCESS;
TEST_EQUAL(Enum1::A, Enum2::AA);
TEST_EQUAL(Enum1::A, Enum2::BB); FAILURE_IS_SUCCESS;
enum class Enum3 { A, B, C };
enum class Enum4 { A, B, C };
TEST_EQUAL(Enum3::A, Enum4::A);
TEST_EQUAL(Enum3::A, Enum3::B); FAILURE_IS_SUCCESS;
TEST_EQUAL(Enum3::B, Enum3::B);
TEST_EQUAL(Enum3::C, Enum3::A); FAILURE_IS_SUCCESS;
}
END_SECTION
START_SECTION("TEST_TRUE()")
{
TEST_TRUE(2==3); FAILURE_IS_SUCCESS;
TEST_TRUE(2==2);
}
END_SECTION
START_SECTION("TEST_FALSE()")
{
TEST_FALSE(2 == 2); FAILURE_IS_SUCCESS;
TEST_FALSE(2 == 3);
}
END_SECTION
START_SECTION("TEST_REAL_SIMILAR()")
{
const double b0 = 0.0;
const double bn = -5.0;
const double bp = +5.0;
const double e0 = 0.0; // zero eps
const double en = -0.1; // negative eps
const double ep = +0.1; // positive eps
double e;
double f;
std::string tmp_file_name;
NEW_TMP_FILE(tmp_file_name);
std::ofstream tmp_file(tmp_file_name.c_str());
STATUS('\n' << tmp_file_name << ":0: output of TEST_REAL_SIMILAR() elementary tests starts here");
#undef stdcout
#define stdcout tmp_file
// The many {} are intended for code folding. Do not mess them up.
{
{
f = e0;
{
TOLERANCE_ABSOLUTE(0.0);
TOLERANCE_RELATIVE(1.0);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f); FAILURE_IS_SUCCESS;
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f); FAILURE_IS_SUCCESS;
}
}
}
{
TOLERANCE_ABSOLUTE(0.25);
TOLERANCE_RELATIVE(1.0);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
}
}
{
TOLERANCE_ABSOLUTE(0.0);
TOLERANCE_RELATIVE(1.1);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
}
}
{
TOLERANCE_ABSOLUTE(0.25);
TOLERANCE_RELATIVE(1.1);
// we need to get rid of some preprocessor macros, as the Microsoft VC++ compiler will crash with a stack overflow during
// compilation of this test otherwise - the stack size is not fixable apparently
#ifndef OPENMS_WINDOWSPLATFORM
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
}
#endif
}
}
{
f = en;
{
TOLERANCE_ABSOLUTE(0.0);
TOLERANCE_RELATIVE(1.0);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f); FAILURE_IS_SUCCESS;
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
}
}
{
TOLERANCE_ABSOLUTE(0.25);
TOLERANCE_RELATIVE(1.0);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
}
}
{
TOLERANCE_ABSOLUTE(0.0);
TOLERANCE_RELATIVE(1.1);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
}
}
{
TOLERANCE_ABSOLUTE(0.25);
TOLERANCE_RELATIVE(1.1);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
}
}
}
{
f = ep;
{
TOLERANCE_ABSOLUTE(0.0);
TOLERANCE_RELATIVE(1.0);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f); FAILURE_IS_SUCCESS;
}
}
}
{
TOLERANCE_ABSOLUTE(0.25);
TOLERANCE_RELATIVE(1.0);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
}
}
{
TOLERANCE_ABSOLUTE(0.0);
TOLERANCE_RELATIVE(1.1);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
}
}
{
TOLERANCE_ABSOLUTE(0.25);
TOLERANCE_RELATIVE(1.1);
{
{
e = e0;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = ep;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
{
e = en;
TEST_REAL_SIMILAR(b0+e,b0+f);
TEST_REAL_SIMILAR(b0+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(b0+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bn+e,bn+f);
TEST_REAL_SIMILAR(bn+e,bp+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,b0+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bn+f); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR(bp+e,bp+f);
}
}
}
}
}
#undef stdcout
#define stdcout std::cout
}
END_SECTION
#if 1
START_SECTION("TEST_STRING_SIMILAR")
{
const char lhs[] = "a bcd ef 10.0 ghi jk l\n l 101.125mno p \nqrs";
const char rhs[] = "a \t bcd ef 12.0 ghi jk l\n l 124.125mno p \nqrs";
TOLERANCE_ABSOLUTE(1.);
TOLERANCE_RELATIVE(1.3);
TEST_STRING_SIMILAR(lhs,rhs);
TOLERANCE_ABSOLUTE(30.);
TOLERANCE_RELATIVE(1.1);
TEST_STRING_SIMILAR(lhs,rhs);
//--------------------------------------------------------
const double numbers[] = { -5.1, -5.0, -4.9, -0.1, 0.0, 0.1, 4.9, 5.0, 5.1 };
UInt number_of_numbers = sizeof(numbers)/sizeof(*numbers);
std::vector<OpenMS::String> number_strings;
for ( UInt i = 0; i < number_of_numbers; ++i )
{
number_strings.push_back(OpenMS::String("ABC") + numbers[i] + "XYZ");
}
const double tolerance_absolute[2] = { 0.0, 0.25 };
const double tolerance_relative[2] = { 1.0, 1.1 };
// Debugging. If you really want to know it. Output is > 10000 lines.
const bool compare_always = false;
for ( UInt ta = 0; ta < 2; ++ta )
{
TOLERANCE_ABSOLUTE(tolerance_absolute[ta]);
for ( UInt tr = 0; tr < 2; ++tr )
{
TOLERANCE_RELATIVE(tolerance_relative[tr]);
for ( UInt i = 0; i < number_of_numbers; ++i )
{
const double ni = numbers[i];
const OpenMS::String& si = number_strings[i];
for ( UInt j = 0; j < number_of_numbers; ++j )
{
const double nj = numbers[j];
const OpenMS::String& sj = number_strings[j];
// Bypass the macros to avoid lengthy output. These functions do the real job.
bool save = TEST::test;
const bool ne = TEST::isRealSimilar(ni,nj);
TEST::testStringSimilar(__FILE__,__LINE__,si,"si",sj,"sj");
const bool se = TEST::this_test;
TEST::this_test = true;
TEST::test = save;
if ( se != ne || compare_always )
{
// We have an issue. Get the message.
STATUS(" ni:" << ni << " nj:" << nj << " si:" << si << " sj:" << sj);
// The real question.
TEST_EQUAL(se,ne);
// The next two TEST_.. should produce the same decision and similar messages.
bool save = TEST::test;
TEST_REAL_SIMILAR(ni,nj); // should be equal to ne
TEST_STRING_SIMILAR(si,sj); // should be equal to se
TEST::test = save;
}
}
}
}
}
}
END_SECTION
#endif
#if 1
START_SECTION("TEST_FILE_SIMILAR")
{
std::string filename1, filename2;
NEW_TMP_FILE(filename1);
NEW_TMP_FILE(filename2);
{
std::ofstream file1(filename1.c_str());
std::ofstream file2(filename2.c_str());
file1 << "1 \n xx\n 2.008 \n 3" << std::flush;
file2 << "1.08 \n xx\n \n\n 0002.04000 \n 3" << std::flush;
file1.close();
file2.close();
}
TOLERANCE_ABSOLUTE(0.01);
TOLERANCE_RELATIVE(1.1);
TEST_FILE_SIMILAR(filename1,filename2);
}
END_SECTION
START_SECTION("TEST_EQUAL")
TEST_EQUAL(1.0, 1.0)
TEST_EQUAL('A', 'A')
END_SECTION
START_SECTION("TEST_NOT_EQUAL")
TEST_NOT_EQUAL(0, 1)
TEST_NOT_EQUAL('A', 'B')
END_SECTION
START_SECTION("TEST_EXCEPTION")
TEST_EXCEPTION(Exception::NullPointer, throw Exception::NullPointer(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION))
END_SECTION
START_SECTION("TEST_EXCEPTION_WITH_MESSAGE")
TEST_EXCEPTION_WITH_MESSAGE(Exception::NullPointer, throw Exception::NullPointer(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION), "a null pointer was specified")
END_SECTION
START_SECTION("TEST_PRECONDITION_VIOLATED")
// recommended usage, success
TEST_PRECONDITION_VIOLATED(throw_a_Precondition_Exception());
int this_was_evaluated = false;
// recommended usage, but failure will be signaled only when compiled in Debug mode.
TEST_PRECONDITION_VIOLATED(this_was_evaluated = true); if ( this_was_evaluated ) { FAILURE_IS_SUCCESS; }
// wrong exception thrown, or none at all
TEST_PRECONDITION_VIOLATED(throw_a_Postcondition_Exception()); if ( this_was_evaluated ) { FAILURE_IS_SUCCESS; }
#ifndef OPENMS_ASSERTIONS
NOT_TESTABLE; // just to avoid a warning message in Release mode - all test macros will expand empty.
#endif
END_SECTION
START_SECTION("TEST_POSTCONDITION_VIOLATED")
// recommended usage, success
TEST_POSTCONDITION_VIOLATED(throw_a_Postcondition_Exception());
int this_was_evaluated = false;
// recommended usage, but failure will be signaled only when compiled in Debug mode.
TEST_POSTCONDITION_VIOLATED(this_was_evaluated = true); if ( this_was_evaluated ) { FAILURE_IS_SUCCESS; }
// wrong exception thrown, or none at all
TEST_POSTCONDITION_VIOLATED(throw_a_Precondition_Exception()); if ( this_was_evaluated ) { FAILURE_IS_SUCCESS; }
#ifndef OPENMS_ASSERTIONS
NOT_TESTABLE; // just to avoid a warning message in Release mode - all test macros will expand empty.
#endif
END_SECTION
START_SECTION("OPENMS_PRETTY_FUNCTION")
struct Dummy
{
std::string f_dummy(double, float,int,unsigned,long,unsigned long,char) { return OPENMS_PRETTY_FUNCTION; }
} dummy;
STATUS("\n\n\tExample for usage of OPENMS_PRETTY_FUNCTION inside a member function of a nested class in main():\n\t" << dummy.f_dummy(0,0,0,0,0,0,0) << '\n')
NOT_TESTABLE
END_SECTION
START_SECTION("STATUS")
STATUS("status message")
NOT_TESTABLE
END_SECTION
START_SECTION("TEST_FILE_EQUAL")
TEST_FILE_EQUAL(OPENMS_GET_TEST_DATA_PATH("class_test_infile.txt"), OPENMS_GET_TEST_DATA_PATH("class_test_template.txt"))
END_SECTION
START_SECTION("ABORT_IF")
TEST_EQUAL(1, 1)
while (true)
{
ABORT_IF(true) // will 'break;' internally, but we do not want to leave the test
}
FAILURE_IS_SUCCESS;
END_SECTION
START_SECTION("TEST_REAL_SIMILAR : type checking")
{
TEST_REAL_SIMILAR( 0.0 , 0.0 );
TEST_REAL_SIMILAR( 0.0 , 0.0F );
TEST_REAL_SIMILAR( 0.0 , 0.0L );
TEST_REAL_SIMILAR( 0.0F , 0.0 );
TEST_REAL_SIMILAR( 0.0F , 0.0F );
TEST_REAL_SIMILAR( 0.0F , 0.0L );
TEST_REAL_SIMILAR( 0.0L , 0.0 );
TEST_REAL_SIMILAR( 0.0L , 0.0F );
TEST_REAL_SIMILAR( 0.0L , 0.0L );
TEST_REAL_SIMILAR( 0.0 , 0U );
TEST_REAL_SIMILAR( 0U , 0.0 ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0U , 0U ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0.0 , 0L );
TEST_REAL_SIMILAR( 0L , 0.0 ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0L , 0L ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0 , 0U ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0 , 0L ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0 , 0UL ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0.0 , 0UL );
TEST_REAL_SIMILAR( 0UL , 0.0 ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0UL , 0UL ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0.0F , 0 );
TEST_REAL_SIMILAR( 0.0 , 0 );
TEST_REAL_SIMILAR( 0.0L , 0 );
TEST_REAL_SIMILAR( 0 , 0.0F ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0 , 0.0 ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0 , 0.0L ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0.0F , 0U );
TEST_REAL_SIMILAR( 0.0 , 0U );
TEST_REAL_SIMILAR( 0.0L , 0U );
TEST_REAL_SIMILAR( 0U , 0.0F ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0U , 0.0 ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0U , 0.0L ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( std::numeric_limits<double>::quiet_NaN(), 0.0 ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0.0, std::numeric_limits<double>::quiet_NaN() ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN() ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( std::numeric_limits<float>::quiet_NaN(), 0.0 ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0.0, std::numeric_limits<float>::quiet_NaN() ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN() ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( std::numeric_limits<long double>::quiet_NaN(), 0.0 ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( 0.0, std::numeric_limits<long double>::quiet_NaN() ); FAILURE_IS_SUCCESS;
TEST_REAL_SIMILAR( std::numeric_limits<long double>::quiet_NaN(), std::numeric_limits<long double>::quiet_NaN() ); FAILURE_IS_SUCCESS;
}
END_SECTION
#endif
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MetaInfoInterfaceUtils_test.cpp | .cpp | 3,325 | 94 | // 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/METADATA/MetaInfoInterfaceUtils.h>
#include <OpenMS/METADATA/PeptideHit.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MetaInfoInterfaceUtils, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION((template<typename T_In, T_Out> static T_Out findCommonMetaKeys(const T::const_iterator& start, const T::const_iterator& end, const float min_frequency = 100.0)))
{
vector<PeptideHit> hits; // some class derived from MetaInfoInterface
for (Size i = 0; i < 10; ++i)
{
PeptideHit h;
h.setMetaValue("commonMeta1", i);
h.setMetaValue("commonMeta2", i);
if (i % 2 == 0)
{
h.setMetaValue("meta50pc", i);
}
hits.push_back(h);
}
hits.back().setMetaValue("metaSingle", "single");
// common keys for ALL entries (i.e. 100% min_frequency)
{
std::vector<String> common = MetaInfoInterfaceUtils::findCommonMetaKeys<std::vector<PeptideHit>, std::vector<String> >(hits.begin(), hits.end(), 100.0);
TEST_EQUAL(common.size(), 2);
ABORT_IF(common.size() != 2);
TEST_EQUAL(common[0], "commonMeta1");
TEST_EQUAL(common[1], "commonMeta2");
// exceeds 100% --> should be corrected to 100% internally
std::vector<String> common2 = MetaInfoInterfaceUtils::findCommonMetaKeys<std::vector<PeptideHit>, std::vector<String> >(hits.begin(), hits.end(), 1110.0);
TEST_TRUE(common == common2);
}
// occurrence of at least 50 (i.e. 50% min_frequency)
{
std::set<String> set50 = MetaInfoInterfaceUtils::findCommonMetaKeys<std::vector<PeptideHit>, std::set<String> >(hits.begin(), hits.end(), 50.0);
TEST_EQUAL(set50.size(), 3);
ABORT_IF(set50.size() != 3);
std::set<String> set50_expected;
set50_expected.insert("commonMeta1");
set50_expected.insert("commonMeta2");
set50_expected.insert("meta50pc");
TEST_TRUE(set50 == set50_expected);
}
// ALL keys (i.e. 0% min_frequency)
{
std::set<String> set0 = MetaInfoInterfaceUtils::findCommonMetaKeys<std::vector<PeptideHit>, std::set<String> >(hits.begin(), hits.end(), 0.0);
TEST_EQUAL(set0.size(), 4);
ABORT_IF(set0.size() != 4);
std::set<String> set0_expected;
set0_expected.insert("commonMeta1");
set0_expected.insert("commonMeta2");
set0_expected.insert("meta50pc");
set0_expected.insert("metaSingle");
TEST_TRUE(set0 == set0_expected);
// exceeds 0% --> should be corrected to 0% internally
std::set<String> set0_2 = MetaInfoInterfaceUtils::findCommonMetaKeys<std::vector<PeptideHit>, std::set<String> >(hits.begin(), hits.end(), -10.0);
TEST_TRUE(set0 == set0_2);
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/EmgModel_test.cpp | .cpp | 6,895 | 255 | // 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/EmgModel.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <boost/math/special_functions/fpclassify.hpp>
///////////////////////////
START_TEST(EmgModel, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using std::stringstream;
// default ctor
EmgModel* ptr = nullptr;
EmgModel* nullPointer = nullptr;
START_SECTION((EmgModel()))
ptr = new EmgModel();
TEST_EQUAL(ptr->getName(), "EmgModel")
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
// destructor
START_SECTION((virtual ~EmgModel()))
delete ptr;
END_SECTION
// assignment operator
START_SECTION((virtual EmgModel& operator=(const EmgModel &source)))
EmgModel em1;
em1.setInterpolationStep(0.2);
Param tmp;
tmp.setValue("bounding_box:min", 678.9);
tmp.setValue("bounding_box:max", 789.0);
tmp.setValue("statistics:mean", 680.1 );
tmp.setValue("statistics:variance", 2.0);
tmp.setValue("emg:height",100000.0);
tmp.setValue("emg:width",5.0);
tmp.setValue("emg:symmetry",5.0);
tmp.setValue("emg:retention",725.0);
em1.setParameters(tmp);
EmgModel em2;
em2 = em1;
EmgModel em3;
em3.setInterpolationStep(0.2);
em3.setParameters(tmp);
TEST_EQUAL(em3.getParameters(), em2.getParameters())
END_SECTION
// copy ctor
START_SECTION((EmgModel(const EmgModel& source)))
EmgModel em1;
em1.setInterpolationStep(0.2);
Param tmp;
tmp.setValue("bounding_box:min", 678.9);
tmp.setValue("bounding_box:max", 789.0);
tmp.setValue("statistics:mean", 680.1 );
tmp.setValue("statistics:variance", 2.0);
tmp.setValue("emg:height",100000.0);
tmp.setValue("emg:width",5.0);
tmp.setValue("emg:symmetry",5.0);
tmp.setValue("emg:retention",725.0);
em1.setParameters(tmp);
EmgModel em2(em1);
EmgModel em3;
em3.setInterpolationStep(0.2);
em3.setParameters(tmp);
em1 = EmgModel();
TEST_EQUAL(em3.getParameters(), em2.getParameters())
END_SECTION
START_SECTION([EXTRA] DefaultParamHandler::setParameters(...))
TOLERANCE_ABSOLUTE(0.001)
EmgModel em1;
Param tmp;
tmp.setValue("bounding_box:min", 678.9);
tmp.setValue("bounding_box:max", 680.9);
tmp.setValue("statistics:mean", 679.1 );
tmp.setValue("statistics:variance", 2.0);
tmp.setValue("emg:height", 100000.0);
tmp.setValue("emg:width", 5.0);
tmp.setValue("emg:symmetry", 5.0);
tmp.setValue("emg:retention", 1200.0);
em1.setParameters(tmp);
em1.setOffset(680.0);
TEST_REAL_SIMILAR(em1.getCenter(), 680.2)
EmgModel em3;
em3.setParameters(em1.getParameters());
std::vector<Peak1D> dpa1;
std::vector<Peak1D> dpa2;
em1.getSamples(dpa1);
em3.getSamples(dpa2);
TOLERANCE_ABSOLUTE(0.0001)
TEST_EQUAL(dpa1.size(),dpa2.size())
ABORT_IF(dpa1.size()!=dpa2.size());
for (Size i=0; i<dpa1.size(); ++i)
{
TEST_REAL_SIMILAR(dpa1[i].getPosition()[0],dpa2[i].getPosition()[0])
TEST_REAL_SIMILAR(dpa1[i].getIntensity(),dpa2[i].getIntensity())
}
EmgModel em2;
em2.setInterpolationStep(0.1);
tmp.setValue("bounding_box:min", -1.0);
tmp.setValue("bounding_box:max", 4.0);
tmp.setValue("statistics:mean", 0.0 );
tmp.setValue("statistics:variance", 0.1);
tmp.setValue("emg:height", 10.0);
tmp.setValue("emg:width", 1.0);
tmp.setValue("emg:symmetry", 2.0);
tmp.setValue("emg:retention", 3.0);
em2.setParameters(tmp);
TEST_REAL_SIMILAR(em2.getCenter(), 0.0)
TOLERANCE_ABSOLUTE(0.01)
TEST_REAL_SIMILAR(em2.getIntensity(-1.0), 0.0497198);
TEST_REAL_SIMILAR(em2.getIntensity(0.0), 0.164882);
TEST_REAL_SIMILAR(em2.getIntensity(1.0), 0.54166);
TEST_REAL_SIMILAR(em2.getIntensity(2.0), 1.69364);
em2.setInterpolationStep(0.2);
em2.setSamples();
TEST_REAL_SIMILAR(em2.getIntensity(-1.0), 0.0497198);
TEST_REAL_SIMILAR(em2.getIntensity(0.0), 0.164882);
TEST_REAL_SIMILAR(em2.getIntensity(1.0), 0.54166);
TEST_REAL_SIMILAR(em2.getIntensity(2.0), 1.69364);
// checked small values of parameter symmetry
tmp.setValue("bounding_box:min", 0.0);
tmp.setValue("bounding_box:max", 10.0);
tmp.setValue("statistics:mean", 0.0 );
tmp.setValue("statistics:variance", 0.1);
tmp.setValue("emg:height", 10.0);
tmp.setValue("emg:width", 6.0);
tmp.setValue("emg:symmetry", 1.0);
tmp.setValue("emg:retention", 3.0);
em2.setParameters(tmp);
TEST_REAL_SIMILAR(em2.getIntensity(2.0), 747203);
tmp.setValue("emg:symmetry", 0.1);
em2.setParameters(tmp);
ABORT_IF(std::isinf(em2.getIntensity(2.0)))
tmp.setValue("emg:symmetry", 0.16);
em2.setParameters(tmp);
ABORT_IF(std::isinf(em2.getIntensity(2.0)))
tmp.setValue("emg:symmetry", 0.17);
em2.setParameters(tmp);
ABORT_IF(std::isinf(float(!em2.getIntensity(2.0))))
END_SECTION
START_SECTION((void setOffset(CoordinateType offset)))
EmgModel em1;
Param tmp;
tmp.setValue("bounding_box:min", 678.9);
tmp.setValue("bounding_box:max", 789.0);
tmp.setValue("statistics:mean", 680.1 );
tmp.setValue("statistics:variance", 2.0);
tmp.setValue("emg:height", 100000.0);
tmp.setValue("emg:width", 5.0);
tmp.setValue("emg:symmetry", 5.0);
tmp.setValue("emg:retention", 725.0);
em1.setParameters(tmp);
em1.setOffset(680.9);
EmgModel em2;
em2.setParameters(tmp);
em2.setOffset(680.9);
TEST_EQUAL(em1.getParameters(), em2.getParameters())
TEST_REAL_SIMILAR(em1.getCenter(), em2.getCenter())
TEST_REAL_SIMILAR(em1.getCenter(), 682.1)
std::vector<Peak1D> dpa1;
std::vector<Peak1D> dpa2;
em1.getSamples(dpa1);
em2.getSamples(dpa2);
TOLERANCE_ABSOLUTE(0.01)
TEST_EQUAL(dpa1.size(),dpa2.size())
ABORT_IF(dpa1.size()!=dpa2.size());
for (Size i=0; i<dpa1.size(); ++i)
{
TEST_REAL_SIMILAR(dpa1[i].getPosition()[0],dpa2[i].getPosition()[0])
TEST_REAL_SIMILAR(dpa1[i].getIntensity(),dpa2[i].getIntensity())
}
END_SECTION
START_SECTION((CoordinateType getCenter() const))
TOLERANCE_ABSOLUTE(0.001)
EmgModel em1;
Param tmp;
tmp.setValue("bounding_box:min", 678.9);
tmp.setValue("bounding_box:max", 789.0);
tmp.setValue("statistics:mean", 680.1 );
tmp.setValue("statistics:variance", 2.0);
tmp.setValue("emg:height", 100000.0);
tmp.setValue("emg:width", 5.0);
tmp.setValue("emg:symmetry", 5.0);
tmp.setValue("emg:retention", 725.0);
em1.setParameters(tmp);
em1.setOffset(680.0);
TEST_REAL_SIMILAR(em1.getCenter(), 681.2)
END_SECTION
START_SECTION((void setSamples()))
{
// dummy subtest
TEST_EQUAL(1,1)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Sample_test.cpp | .cpp | 7,506 | 312 | // 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/Sample.h>
#include <sstream>
///////////////////////////
START_TEST(Sample, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
TOLERANCE_ABSOLUTE(0.001)
// default ctor
Sample* dv_ptr = nullptr;
Sample* dv_nullPointer = nullptr;
START_SECTION((Sample()))
dv_ptr = new Sample;
TEST_NOT_EQUAL(dv_ptr, dv_nullPointer)
END_SECTION
// destructor
START_SECTION((~Sample()))
delete dv_ptr;
END_SECTION
START_SECTION((const String& getName() const))
Sample s;
TEST_EQUAL(s.getName(),"")
END_SECTION
START_SECTION((const String& getOrganism() const))
Sample s;
TEST_EQUAL(s.getOrganism(),"")
END_SECTION
START_SECTION((const String& getNumber() const))
Sample s;
TEST_EQUAL(s.getNumber(),"")
END_SECTION
START_SECTION((const String& getComment() const))
Sample s;
TEST_EQUAL(s.getComment(),"")
END_SECTION
START_SECTION((SampleState getState() const))
Sample s;
TEST_EQUAL(s.getState(),Sample::SampleState::SAMPLENULL)
END_SECTION
START_SECTION((double getMass() const ))
Sample s;
TEST_REAL_SIMILAR(s.getMass(),0.0)
END_SECTION
START_SECTION((double getVolume() const ))
Sample s;
TEST_REAL_SIMILAR(s.getVolume(),0.0)
END_SECTION
START_SECTION((double getConcentration() const ))
Sample s;
TEST_REAL_SIMILAR(s.getConcentration(),0.0)
END_SECTION
START_SECTION((void setName(const String& name)))
Sample s;
s.setName("TTEST");
TEST_EQUAL(s.getName(),"TTEST")
END_SECTION
START_SECTION((void setOrganism(const String& organism)))
Sample s;
s.setOrganism("TTEST");
TEST_EQUAL(s.getOrganism(),"TTEST")
END_SECTION
START_SECTION((void setNumber(const String& number)))
Sample s;
s.setNumber("Sample4711");
TEST_EQUAL(s.getNumber(),"Sample4711")
END_SECTION
START_SECTION((void setComment(const String& comment)))
Sample s;
s.setComment("Sample Description");
TEST_EQUAL(s.getComment(),"Sample Description")
END_SECTION
START_SECTION((void setState(SampleState state)))
Sample s;
s.setState(Sample::SampleState::LIQUID);
TEST_EQUAL(s.getState(),Sample::SampleState::LIQUID)
END_SECTION
START_SECTION((void setMass(double mass)))
Sample s;
s.setMass(4711.2);
TEST_REAL_SIMILAR(s.getMass(),4711.2)
END_SECTION
START_SECTION((void setVolume(double volume)))
Sample s;
s.setVolume(4711.3);
TEST_REAL_SIMILAR(s.getVolume(),4711.3)
END_SECTION
START_SECTION((void setConcentration(double concentration)))
Sample s;
s.setConcentration(4711.4);
TEST_REAL_SIMILAR(s.getConcentration(),4711.4)
END_SECTION
START_SECTION((const std::vector<Sample>& getSubsamples() const))
Sample s;
TEST_EQUAL(s.getSubsamples().size(),0)
END_SECTION
START_SECTION((std::vector<Sample>& getSubsamples()))
Sample s,s2;
s.getSubsamples().push_back(s2);
TEST_EQUAL(s.getSubsamples().size(),1)
END_SECTION
START_SECTION((void setSubsamples(const std::vector<Sample>& subsamples)))
Sample s,s2,s3;
vector<Sample> v;
//size=2
s2.setName("2");
s3.setName("3");
v.push_back(s2);
v.push_back(s3);
s.setSubsamples(v);
TEST_EQUAL(s.getSubsamples().size(),2)
TEST_EQUAL(s.getSubsamples()[0].getName(),"2")
TEST_EQUAL(s.getSubsamples()[1].getName(),"3")
END_SECTION
//copy ctr
START_SECTION((Sample(const Sample& source)))
Sample s;
//basic stuff
s.setOrganism("TTEST2");
s.setName("TTEST");
s.setNumber("Sample4711");
s.setComment("Sample Description");
s.setState(Sample::SampleState::LIQUID);
s.setMass(4711.2);
s.setVolume(4711.3);
s.setConcentration(4711.4);
//meta info
s.setMetaValue("label",String("horse"));
//subsamples
Sample ss;
ss.setName("2");
s.getSubsamples().push_back(ss);
//-----------------
//Copy construction
//-----------------
Sample s2(s);
//basic stuff
TEST_EQUAL(s2.getName(),"TTEST")
TEST_EQUAL(s2.getNumber(),"Sample4711")
TEST_EQUAL(s2.getComment(),"Sample Description")
TEST_EQUAL(s2.getState(),Sample::SampleState::LIQUID)
TEST_REAL_SIMILAR(s2.getMass(),4711.2)
TEST_REAL_SIMILAR(s2.getVolume(),4711.3)
TEST_REAL_SIMILAR(s2.getConcentration(),4711.4)
TEST_EQUAL(s2.getOrganism(),"TTEST2")
//meta
TEST_EQUAL(s.getMetaValue("label"),"horse")
//subsamples
TEST_EQUAL(s.getSubsamples()[0].getName(),"2")
END_SECTION
//assignment operator
START_SECTION((Sample& operator= (const Sample& source)))
Sample s;
//basic stuff
s.setName("TTEST");
s.setOrganism("TTEST2");
s.setNumber("Sample4711");
s.setComment("Sample Description");
s.setState(Sample::SampleState::LIQUID);
s.setMass(4711.2);
s.setVolume(4711.3);
s.setConcentration(4711.4);
//meta
s.setMetaValue("label",String("horse"));
//subsamples
Sample ss;
ss.setName("2");
s.getSubsamples().push_back(ss);
//-----------------
//Copy construction
//-----------------
Sample s2;
s2=s;
//basic stuff
TEST_EQUAL(s2.getName(),"TTEST")
TEST_EQUAL(s2.getNumber(),"Sample4711")
TEST_EQUAL(s2.getComment(),"Sample Description")
TEST_EQUAL(s2.getOrganism(),"TTEST2")
TEST_EQUAL(s2.getState(),Sample::SampleState::LIQUID)
TEST_REAL_SIMILAR(s2.getMass(),4711.2)
TEST_REAL_SIMILAR(s2.getVolume(),4711.3)
TEST_REAL_SIMILAR(s2.getConcentration(),4711.4)
//meta
TEST_EQUAL(s.getMetaValue("label"),"horse")
//subsamples
TEST_EQUAL(s.getSubsamples()[0].getName(),"2")
END_SECTION
START_SECTION((bool operator== (const Sample& rhs) const))
const Sample empty;
Sample edit;
TEST_EQUAL(edit==empty,true)
edit.setName("TTEST");
TEST_EQUAL(edit==empty,false)
edit = empty;
TEST_EQUAL(edit==empty,true)
edit.setOrganism("TTEST2");
TEST_EQUAL(edit==empty,false)
edit = empty;
TEST_EQUAL(edit==empty,true)
edit.setNumber("Sample4711");
TEST_EQUAL(edit==empty,false)
edit = empty;
TEST_EQUAL(edit==empty,true)
edit.setComment("Sample Description");
TEST_EQUAL(edit==empty,false)
edit = empty;
TEST_EQUAL(edit==empty,true)
edit.setState(Sample::SampleState::LIQUID);
TEST_EQUAL(edit==empty,false)
edit = empty;
TEST_EQUAL(edit==empty,true)
edit.setMass(4711.2);
TEST_EQUAL(edit==empty,false)
edit = empty;
TEST_EQUAL(edit==empty,true)
edit.setVolume(4711.3);
TEST_EQUAL(edit==empty,false)
edit = empty;
TEST_EQUAL(edit==empty,true)
edit.setConcentration(4711.4);
TEST_EQUAL(edit==empty,false)
edit = empty;
TEST_EQUAL(edit==empty,true)
edit.getSubsamples().push_back(empty);
TEST_EQUAL(edit==empty,false)
edit = empty;
TEST_EQUAL(edit==empty,true)
edit.setMetaValue("color",45);
TEST_EQUAL(edit==empty,false)
edit = empty;
TEST_EQUAL(edit==empty,true)
END_SECTION
START_SECTION((static StringList getAllNamesOfSampleState()))
StringList names = Sample::getAllNamesOfSampleState();
TEST_EQUAL(names.size(), static_cast<size_t>(Sample::SampleState::SIZE_OF_SAMPLESTATE));
TEST_EQUAL(names[static_cast<size_t>(Sample::SampleState::LIQUID)], "liquid");
TEST_EQUAL(names[static_cast<size_t>(Sample::SampleState::SOLID)], "solid");
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/CachedMzML_test.cpp | .cpp | 6,426 | 206 | // 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/CachedMzML.h>
///////////////////////////
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wshadow"
#endif
using namespace OpenMS;
using namespace std;
START_TEST(CachedmzML, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
CachedmzML* ptr = nullptr;
CachedmzML* nullPointer = nullptr;
START_SECTION(CachedmzML())
{
ptr = new CachedmzML();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~CachedmzML())
{
delete ptr;
}
END_SECTION
// Load experiment
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp);
std::string tmpf;
NEW_TMP_FILE(tmpf);
// Cache the experiment to a temporary file
CachedmzML::store(tmpf, exp);
CachedmzML cache_example;
CachedmzML::load(tmpf, cache_example);
// see also MSDataCachedConsumer_test.cpp -> consumeSpectrum
// this is a complete test of the caching object
START_SECTION(( [EXTRA] testCaching))
{
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
// Load experiment
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp);
TEST_EQUAL(exp.getNrSpectra() > 0, true)
TEST_EQUAL(exp.getNrChromatograms() > 0, true)
// Cache the experiment to a temporary file
CachedmzML::store(tmp_filename, exp);
// Check whether spectra were written to disk correctly...
{
// Create the index from the given file
CachedmzML cache;
CachedmzML::load(tmp_filename, cache);
TEST_EQUAL(cache.getNrSpectra(), 4)
// retrieve the spectrum (old interface)
for (int i = 0; i < 4; i++)
{
TEST_EQUAL(cache.getSpectrum(i).size(), exp.getSpectrum(i).size())
// identical except DataProcessing (and extra data arrays -- does not have all fields)
auto tmp1 = cache.getSpectrum(i);
auto tmp2 = exp.getSpectrum(i);
tmp1.getDataProcessing().clear();
tmp2.getDataProcessing().clear();
tmp1.getFloatDataArrays().clear(); // clear for now, see test below
tmp2.getFloatDataArrays().clear(); // clear for now, see test below
TEST_TRUE(tmp1 == tmp2)
}
// test spec 1
auto scomp = exp.getSpectrum(1);
TEST_EQUAL(scomp.getFloatDataArrays().size(), 2)
TEST_EQUAL(scomp.getIntegerDataArrays().size(), 0)
TEST_EQUAL(scomp.getStringDataArrays().size(), 0)
// test spec 1
auto s = cache.getSpectrum(1);
TEST_EQUAL(s.getFloatDataArrays().size(), 2)
TEST_EQUAL(s.getIntegerDataArrays().size(), 0)
TEST_EQUAL(s.getStringDataArrays().size(), 0)
TEST_EQUAL(s.getFloatDataArrays()[0].getName(), scomp.getFloatDataArrays()[0].getName())
TEST_EQUAL(s.getFloatDataArrays()[1].getName(), scomp.getFloatDataArrays()[1].getName())
TEST_EQUAL(s.getFloatDataArrays()[0].getName(), "signal to noise array")
TEST_EQUAL(s.getFloatDataArrays()[1].getName(), "user-defined name")
TEST_EQUAL(s.getFloatDataArrays()[0].size(), scomp.getFloatDataArrays()[0].size())
TEST_EQUAL(s.getFloatDataArrays()[1].size(), scomp.getFloatDataArrays()[1].size())
for (Size k = 0; k < s.getFloatDataArrays()[0].size(); k++)
{
TEST_REAL_SIMILAR(s.getFloatDataArrays()[0][k], scomp.getFloatDataArrays()[0][k])
}
for (Size k = 0; k < s.getFloatDataArrays()[1].size(); k++)
{
TEST_REAL_SIMILAR(s.getFloatDataArrays()[1][k], scomp.getFloatDataArrays()[1][k])
}
}
// Check whether chromatograms were written to disk correctly...
{
// Create the index from the given file
CachedmzML cache;
CachedmzML::load(tmp_filename, cache);
TEST_EQUAL(cache.getNrChromatograms(), 2)
// retrieve the chromatogram
for (int i = 0; i < 2; i++)
{
TEST_EQUAL(cache.getChromatogram(i).size(), exp.getChromatogram(i).size())
TEST_EQUAL(cache.getChromatogram(i).getNativeID(), exp.getChromatogram(i).getNativeID())
TEST_EQUAL(cache.getChromatogram(i).getInstrumentSettings() == exp.getChromatogram(i).getInstrumentSettings(), true)
// identical except DataProcessing
auto tmp1 = cache.getChromatogram(i);
auto tmp2 = exp.getChromatogram(i);
tmp1.getDataProcessing().clear();
tmp2.getDataProcessing().clear();
TEST_TRUE(tmp1 == tmp2)
}
}
}
END_SECTION
START_SECTION(( size_t getNrSpectra() const ))
TEST_EQUAL(cache_example.getNrSpectra(), 4)
END_SECTION
START_SECTION(( size_t getNrChromatograms() const ))
TEST_EQUAL(cache_example.getNrChromatograms(), 2)
END_SECTION
START_SECTION(( const MSExperiment& getMetaData() const ))
TEST_EQUAL(cache_example.getMetaData().size(), 4)
TEST_EQUAL(cache_example.getMetaData().getNrSpectra(), 4)
TEST_EQUAL(cache_example.getMetaData().getNrChromatograms(), 2)
END_SECTION
START_SECTION(( const MSExperiment& getMetaData() const ))
{
TEST_EQUAL(cache_example.getNrSpectra(), cache_example.getMetaData().getNrSpectra())
for (int i = 0; i < 4; i++)
{
// identical except DataProcessing
SpectrumSettings tmp1 = cache_example.getMetaData()[i];
SpectrumSettings tmp2 = exp.getSpectrum(i);
tmp1.getDataProcessing().clear();
tmp2.getDataProcessing().clear();
TEST_TRUE(tmp1 == tmp2)
}
TEST_EQUAL(cache_example.getNrChromatograms(), cache_example.getMetaData().getNrChromatograms())
for (int i = 0; i < 2; i++)
{
// identical except DataProcessing
ChromatogramSettings tmp1 = cache_example.getMetaData().getChromatograms()[i];
ChromatogramSettings tmp2 = exp.getChromatogram(i);
tmp1.getDataProcessing().clear();
tmp2.getDataProcessing().clear();
TEST_TRUE(tmp1 == tmp2)
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
#ifdef __clang__
#pragma clang diagnostic pop
#endif | C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/AverageLinkage_test.cpp | .cpp | 3,560 | 127 | // 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/AverageLinkage.h>
#include <OpenMS/ML/CLUSTERING/ClusterAnalyzer.h>
#include <OpenMS/DATASTRUCTURES/DistanceMatrix.h>
#include <vector>
//#include <iostream>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(AverageLinkage, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
AverageLinkage* ptr = nullptr;
AverageLinkage* nullPointer = nullptr;
START_SECTION(AverageLinkage())
{
ptr = new AverageLinkage();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~AverageLinkage())
{
delete ptr;
}
END_SECTION
START_SECTION((AverageLinkage(const AverageLinkage &source)))
{
AverageLinkage al1;
AverageLinkage copy(al1);
}
END_SECTION
START_SECTION((AverageLinkage& operator=(const AverageLinkage &source)))
{
AverageLinkage copy,al2;
copy = al2;
}
END_SECTION
START_SECTION((void operator()(DistanceMatrix< float > &original_distance, std::vector<BinaryTreeNode>& cluster_tree, const float threshold=1) const))
{
DistanceMatrix<float> matrix(6,666);
matrix.setValue(1,0,0.5f);
matrix.setValue(2,0,0.8f);
matrix.setValue(2,1,0.3f);
matrix.setValue(3,0,0.6f);
matrix.setValue(3,1,0.8f);
matrix.setValue(3,2,0.8f);
matrix.setValue(4,0,0.8f);
matrix.setValue(4,1,0.8f);
matrix.setValue(4,2,0.8f);
matrix.setValue(4,3,0.4f);
matrix.setValue(5,0,0.7000001f); //~ minimal adjustment for gcc 4 with -o2
matrix.setValue(5,1,0.8f);
matrix.setValue(5,2,0.8f);
matrix.setValue(5,3,0.8f);
matrix.setValue(5,4,0.8f);
DistanceMatrix<float> matrix2(matrix);
vector< BinaryTreeNode > result;
vector< BinaryTreeNode > tree;
//~ tree.push_back(BinaryTreeNode(1,2,0.3f));
//~ tree.push_back(BinaryTreeNode(2,3,0.4f));
//~ tree.push_back(BinaryTreeNode(0,1,0.65f));
//~ tree.push_back(BinaryTreeNode(0,1,0.766667f));
//~ tree.push_back(BinaryTreeNode(0,1,0.78f));
tree.push_back(BinaryTreeNode(1,2,0.3f));
tree.push_back(BinaryTreeNode(3,4,0.4f));
tree.push_back(BinaryTreeNode(0,1,0.65f));
tree.push_back(BinaryTreeNode(0,3,0.766667f));
tree.push_back(BinaryTreeNode(0,5,0.78f));
AverageLinkage al;
al(matrix,result);
TEST_EQUAL(tree.size(), result.size());
for (Size i = 0; i < result.size(); ++i)
{
TEST_EQUAL(tree[i].left_child, result[i].left_child);
TEST_EQUAL(tree[i].right_child, result[i].right_child);
TOLERANCE_ABSOLUTE(0.0001);
TEST_REAL_SIMILAR(tree[i].distance, result[i].distance);
}
float th(0.7f);
tree.pop_back();
tree.pop_back();
tree.push_back(BinaryTreeNode(0,3,-1.0f));
tree.push_back(BinaryTreeNode(0,5,-1.0f));
result.clear();
al(matrix2,result,th);
TEST_EQUAL(tree.size(), result.size());
for (Size i = 0; i < result.size(); ++i)
{
TEST_EQUAL(tree[i].left_child, result[i].left_child);
TEST_EQUAL(tree[i].right_child, result[i].right_child);
TOLERANCE_ABSOLUTE(0.0001);
TEST_REAL_SIMILAR(tree[i].distance, result[i].distance);
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MRMFeatureScoring_test.cpp | .cpp | 8,689 | 224 | // 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 <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include "OpenSwathTestHelper.h"
#include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/MRMFeatureAccessOpenMS.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DIAScoring.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMTransitionGroupPicker.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMScoring.h>
#include <OpenMS/OPENSWATHALGO/ALGO/Scoring.h>
///////////////////////////
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MRMScoring, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
OpenSwath::MRMScoring* ptr = nullptr;
OpenSwath::MRMScoring* nullPointer = nullptr;
START_SECTION(MRMScoring())
{
ptr = new OpenSwath::MRMScoring();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~MRMScoring())
{
delete ptr;
}
END_SECTION
///////////////////////////////////////////////////////////////////////////
// testing the individual scores that are produced
// calcXcorrCoelutionScore
// calcXcorrCoelutionWeightedScore
// calcXcorrShapeScore
// calcXcorrShapeWeightedScore
// calcLibraryScore
START_SECTION([EXTRA] test_scores())
{
// load the mock objects
MRMFeature mrmfeature = OpenSWATH_Test::createMockFeature();
OpenSWATH_Test::MRMTransitionGroupType transition_group = OpenSWATH_Test::createMockTransitionGroup();
// create the Interface objects
OpenSwath::IMRMFeature * imrmfeature;
imrmfeature = new MRMFeatureOpenMS(mrmfeature);
//initialize the XCorr Matrix
OpenSwath::MRMScoring mrmscore;
std::vector<std::string> native_ids;
for (Size i = 0; i < transition_group.getTransitions().size(); i++) {native_ids.push_back(transition_group.getTransitions()[i].getNativeID());}
mrmscore.initializeXCorrMatrix(imrmfeature, native_ids);
static const double arr_lib[] = {0.5,1,0.5};
std::vector<double> normalized_library_intensity (arr_lib, arr_lib + sizeof(arr_lib) / sizeof(arr_lib[0]) );
//mrmscore.standardize_data(normalized_library_intensity);
double sumx = std::accumulate( normalized_library_intensity.begin(), normalized_library_intensity.end(), 0.0 );
for(Size m =0; m<normalized_library_intensity.size();m++) { normalized_library_intensity[m] /= sumx;}
TEST_REAL_SIMILAR(mrmscore.calcXcorrCoelutionScore(), 2.26491106406735)
TEST_REAL_SIMILAR(mrmscore.calcXcorrCoelutionWeightedScore(normalized_library_intensity), 1.375)
TEST_REAL_SIMILAR(mrmscore.calcXcorrShapeScore(), 0.757687954406132)
TEST_REAL_SIMILAR(mrmscore.calcXcorrShapeWeightedScore(normalized_library_intensity), 0.7130856895)
// numpy
double library_corr, library_rmsd;
double manhatten, dotproduct;
double spectral_angle, rmsd;
mrmscore.calcLibraryScore(imrmfeature, transition_group.getTransitions(), library_corr, library_rmsd, manhatten, dotproduct, spectral_angle, rmsd);
TEST_REAL_SIMILAR(library_corr, -0.654591316)
TEST_REAL_SIMILAR(library_rmsd, 0.5800337593)
TEST_REAL_SIMILAR(manhatten, 1.279644714)
TEST_REAL_SIMILAR(dotproduct, 0.34514801)
TEST_REAL_SIMILAR(spectral_angle, 1.483262)
TEST_REAL_SIMILAR(rmsd, 0.6727226674)
delete imrmfeature;
}
END_SECTION
// testing the individual DIA (data independent / SWATH) scores that are produced
// dia_isotope_scores
// dia_massdiff_score
// dia_by_ion_score
START_SECTION((virtual void test_dia_scores()))
{
OpenSWATH_Test::MRMTransitionGroupType transition_group;
transition_group = OpenSWATH_Test::createMockTransitionGroup();
PeakMap swath_map;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("ChromatogramExtractor_input.mzML"), swath_map);
MRMFeature mrmfeature = OpenSWATH_Test::createMockFeature();
int by_charge_state = 1;
RangeMobility empty_im_range;
// find spectrum that is closest to the apex of the peak (set to 3120) using binary search
MSSpectrum OpenMSspectrum = (*swath_map.RTBegin( 3120 ));
OpenSwath::BinaryDataArrayPtr intensity_array(new OpenSwath::BinaryDataArray);
OpenSwath::BinaryDataArrayPtr mz_array(new OpenSwath::BinaryDataArray);
for(MSSpectrum::iterator it = OpenMSspectrum.begin(); it != OpenMSspectrum.end(); it++)
{
mz_array->data.push_back(it->getMZ());
intensity_array->data.push_back(it->getIntensity());
}
OpenSwath::SpectrumPtr sptr(new OpenSwath::Spectrum);
sptr->setMZArray( mz_array );
sptr->setIntensityArray( intensity_array);
OpenSwath::MRMScoring mrmscore;
DIAScoring diascoring;
// diascoring.set_dia_parameters(0.05, false, 30, 50, 4, 4); // here we use 50 ppm and a cutoff of 30 in intensity -- because our peptide does not match with the testdata :-)
Param p_dia = diascoring.getDefaults();
p_dia.setValue("dia_extraction_window", 0.05);
p_dia.setValue("dia_extraction_unit", "Th");
p_dia.setValue("dia_centroided", "false");
p_dia.setValue("dia_byseries_intensity_min", 30.0);
p_dia.setValue("dia_byseries_ppm_diff", 50.0);
p_dia.setValue("dia_nr_isotopes", 4);
p_dia.setValue("dia_nr_charges", 4);
diascoring.setParameters(p_dia);
// calculate the normalized library intensity (expected value of the intensities)
// Numpy
// arr1 = [ 0,1,3,5,2,0 ];
// arr2 = [ 1,3,5,2,0,0 ];
// (arr1 - mean(arr1) ) / std(arr1)
// (arr2 - mean(arr2) ) / std(arr2)
static const double arr_lib[] = {1.0,0.5,0.5};
std::vector<double> normalized_library_intensity (arr_lib, arr_lib + sizeof(arr_lib) / sizeof(arr_lib[0]) );
//mrmscore.standardize_data(normalized_library_intensity);
double sumx = std::accumulate( normalized_library_intensity.begin(), normalized_library_intensity.end(), 0.0 );
for(Size m =0; m<normalized_library_intensity.size();m++) { normalized_library_intensity[m] /= sumx;}
// Isotope correlation / overlap score: Is this peak part of an
// isotopic pattern or is it the monoisotopic peak in an isotopic
// pattern?
OpenSwath::IMRMFeature * imrmfeature;
imrmfeature = new MRMFeatureOpenMS(mrmfeature);
// We have to reorder the transitions to make the tests work
std::vector<OpenSWATH_Test::TransitionType> transitions = transition_group.getTransitions();
double isotope_corr = 0, isotope_overlap = 0;
std::vector<OpenSwath::SpectrumPtr> sptrArr;
sptrArr.push_back(sptr);
diascoring.dia_isotope_scores(transitions, sptrArr, imrmfeature, empty_im_range, isotope_corr, isotope_overlap);
delete imrmfeature;
// Mass deviation score
double ppm_score = 0, ppm_score_weighted = 0;
std::vector<double> ppm_errors;
diascoring.dia_massdiff_score(transition_group.getTransitions(),
sptrArr, normalized_library_intensity, empty_im_range, ppm_score, ppm_score_weighted, ppm_errors);
// Presence of b/y series score
double bseries_score = 0, yseries_score = 0;
String sequence = "SYVAWDR";
OpenMS::AASequence aas = AASequence::fromString(sequence);
diascoring.dia_by_ion_score(sptrArr, aas, by_charge_state, empty_im_range, bseries_score, yseries_score);
TEST_REAL_SIMILAR(isotope_corr, 0.2866618 * transition_group.getTransitions().size() )
TEST_REAL_SIMILAR(isotope_corr, 0.85998565339479)
TEST_REAL_SIMILAR(isotope_overlap, 0.0599970892071724)
TEST_REAL_SIMILAR(ppm_score, 1.76388919944981 / 3)
TEST_REAL_SIMILAR(ppm_score_weighted, 0.484116946070573)
double ppm_expected[] = {0.17257858483247876, 0.79565530730866774, 0.79565530730866774};
for (size_t i = 0; i < ppm_errors.size(); ++i)
{
TEST_REAL_SIMILAR(ppm_errors[i], ppm_expected[i]);
}
TEST_EQUAL(bseries_score, 0)
TEST_EQUAL(yseries_score, 1)
// b/y series score with modifications
bseries_score = 0, yseries_score = 0;
aas.setModification(1, "Phospho" ); // modify the Y
diascoring.dia_by_ion_score(sptrArr, aas, by_charge_state, empty_im_range, bseries_score, yseries_score);
TEST_EQUAL(bseries_score, 0)
TEST_EQUAL(yseries_score, 1)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SpectrumMetaDataLookup_test.cpp | .cpp | 9,531 | 270 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/METADATA/SpectrumMetaDataLookup.h>
#include <OpenMS/IONMOBILITY/IMTypes.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(SpectrumMetaDataLookup, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
SpectrumMetaDataLookup* ptr = nullptr;
SpectrumMetaDataLookup* null_ptr = nullptr;
START_SECTION((SpectrumMetaDataLookup()))
{
ptr = new SpectrumMetaDataLookup();
TEST_NOT_EQUAL(ptr, null_ptr);
TEST_EQUAL(ptr->empty(), true);
}
END_SECTION
START_SECTION((~SpectrumMetaDataLookup()))
{
delete ptr;
}
END_SECTION
vector<MSSpectrum> spectra;
MSSpectrum spectrum;
spectrum.setNativeID("spectrum=0");
spectrum.setRT(1.0);
spectrum.setMSLevel(1);
spectra.push_back(spectrum);
spectrum.setNativeID("spectrum=1");
spectrum.setRT(2.0);
spectrum.setMSLevel(2);
Precursor prec;
prec.setMZ(1000.0);
prec.setCharge(2);
spectrum.getPrecursors().push_back(prec);
spectra.push_back(spectrum);
spectrum.setNativeID("spectrum=2");
spectrum.setRT(3.0);
spectrum.setMSLevel(2);
prec.setMZ(500.0);
prec.setCharge(3);
spectrum.getPrecursors()[0] = prec;
spectra.push_back(spectrum);
SpectrumMetaDataLookup lookup;
START_SECTION((template <typename SpectrumContainer> void readSpectra(const SpectrumContainer&, const String&, bool)))
{
lookup.readSpectra(spectra, SpectrumLookup::default_scan_regexp, true);
TEST_EQUAL(lookup.empty(), false);
}
END_SECTION
START_SECTION((void getSpectrumMetaData(Size, SpectrumMetaData&) const))
{
SpectrumMetaDataLookup::SpectrumMetaData meta;
lookup.getSpectrumMetaData(0, meta);
TEST_EQUAL(meta.rt, 1.0);
TEST_EQUAL(meta.ms_level, 1);
TEST_EQUAL(meta.native_id, "spectrum=0");
TEST_EQUAL(meta.scan_number, 0);
lookup.getSpectrumMetaData(1, meta);
TEST_EQUAL(meta.rt, 2.0);
TEST_EQUAL(meta.precursor_rt, 1.0);
TEST_EQUAL(meta.precursor_mz, 1000.0);
TEST_EQUAL(meta.precursor_charge, 2);
TEST_EQUAL(meta.ms_level, 2);
TEST_EQUAL(meta.native_id, "spectrum=1");
TEST_EQUAL(meta.scan_number, 1);
}
END_SECTION
START_SECTION((static void getSpectrumMetaData(const MSSpectrum&, SpectrumMetaData&, const boost::regex&, const map<Size, double>&)))
{
SpectrumMetaDataLookup::SpectrumMetaData meta;
SpectrumMetaDataLookup::getSpectrumMetaData(spectrum, meta);
TEST_EQUAL(meta.rt, 3.0);
TEST_EQUAL(meta.precursor_mz, 500.0);
TEST_EQUAL(meta.precursor_charge, 3);
TEST_EQUAL(meta.ms_level, 2);
TEST_EQUAL(meta.native_id, "spectrum=2");
TEST_EQUAL(meta.scan_number, -1); // not extracted
map<Size, double> precursor_rts;
precursor_rts[1] = 1.0;
boost::regex scan_regexp("=(?<SCAN>\\d+)$");
SpectrumMetaDataLookup::getSpectrumMetaData(spectrum, meta, scan_regexp,
precursor_rts);
TEST_EQUAL(meta.precursor_rt, 1.0);
TEST_EQUAL(meta.scan_number, 2);
}
END_SECTION
START_SECTION((void getSpectrumMetaData(const String&, SpectrumMetaData&, MetaDataFlags) const))
{
SpectrumMetaDataLookup::SpectrumMetaData meta;
lookup.addReferenceFormat(SpectrumLookup::default_scan_regexp);
lookup.getSpectrumMetaData("scan_number=1", meta);
TEST_EQUAL(meta.rt, 2.0);
TEST_EQUAL(meta.native_id, "spectrum=1");
lookup.addReferenceFormat(R"(rt=(?<RT>\d+(\.\d+)?),mz=(?<MZ>\d+(\.\d+)?))");
SpectrumMetaDataLookup::SpectrumMetaData meta2;
SpectrumMetaDataLookup::MetaDataFlags flags =
(SpectrumMetaDataLookup::MDF_RT | SpectrumMetaDataLookup::MDF_PRECURSORMZ);
// no actual look-up of the spectrum necessary:
lookup.getSpectrumMetaData("rt=5.0,mz=1000.0", meta2, flags);
TEST_EQUAL(meta2.rt, 5.0);
TEST_EQUAL(meta2.precursor_mz, 1000.0);
TEST_EQUAL(meta2.precursor_charge, 0);
TEST_EQUAL(meta2.native_id, "");
// look-up of the spectrum necessary:
SpectrumMetaDataLookup::SpectrumMetaData meta3;
lookup.getSpectrumMetaData("rt=2.0,mz=1000.0", meta3);
TEST_EQUAL(meta3.rt, 2.0);
TEST_EQUAL(meta3.precursor_mz, 1000.0);
TEST_EQUAL(meta3.precursor_charge, 2);
TEST_EQUAL(meta3.native_id, "spectrum=1");
TEST_EXCEPTION(Exception::ElementNotFound, lookup.getSpectrumMetaData("rt=5.0,mz=1000.0", meta3));
}
END_SECTION
START_SECTION((bool addMissingRTsToPeptideIDs(PeptideIdentificationList& peptides, const MSExperiment& exp)))
{
// Test 1: No spectra in MSExperiment
PeptideIdentificationList peptides(1);
peptides[0].setRT(1.0); // RT already set
MSExperiment exp_empty; // Empty experiment
TEST_EQUAL(SpectrumMetaDataLookup::addMissingRTsToPeptideIDs(peptides, exp_empty), false);
TEST_EQUAL(peptides[0].getRT(), 1.0); // RT should remain unchanged
// Test 2: Valid MSExperiment with missing RTs
MSExperiment exp_valid;
MSSpectrum spectrum1, spectrum2;
spectrum1.setNativeID("index=0");
spectrum1.setRT(2.5);
spectrum2.setNativeID("index=2");
spectrum2.setRT(5.3);
exp_valid.addSpectrum(spectrum1);
exp_valid.addSpectrum(spectrum2);
peptides.resize(2);
peptides[0].setSpectrumReference("index=0");
peptides[0].setRT(std::numeric_limits<double>::quiet_NaN()); // Missing RT
peptides[1].setSpectrumReference("index=2");
peptides[1].setRT(std::numeric_limits<double>::quiet_NaN()); // Missing RT
TEST_EQUAL(SpectrumMetaDataLookup::addMissingRTsToPeptideIDs(peptides, exp_valid), true);
// Verify RT annotations
TEST_REAL_SIMILAR(peptides[0].getRT(), 2.5);
TEST_REAL_SIMILAR(peptides[1].getRT(), 5.3);
// Test 3: Missing spectrum reference in experiment
peptides.resize(1);
peptides[0].setSpectrumReference("index=nonexistent");
peptides[0].setRT(std::numeric_limits<double>::quiet_NaN()); // Missing RT
TEST_EQUAL(SpectrumMetaDataLookup::addMissingRTsToPeptideIDs(peptides, exp_valid), false);
TEST_EQUAL(std::isnan(peptides[0].getRT()), true); // RT should remain NaN
// Test 4: No missing RTs in peptides
peptides.resize(1);
peptides[0].setSpectrumReference("index=0");
peptides[0].setRT(2.0); // Already has RT
TEST_EQUAL(SpectrumMetaDataLookup::addMissingRTsToPeptideIDs(peptides, exp_valid), true);
TEST_EQUAL(peptides[0].getRT(), 2.0); // RT should remain unchanged
}
END_SECTION
START_SECTION((bool addMissingIMToPeptideIDs(PeptideIdentificationList& peptides, const MSExperiment& exp)))
{
// Test 1: Empty MSExperiment
PeptideIdentificationList peptides(1);
peptides[0].setSpectrumReference("index=0");
MSExperiment exp_empty;
TEST_EQUAL(SpectrumMetaDataLookup::addMissingIMToPeptideIDs(peptides, exp_empty), false);
// Test 2: MSExperiment with no IM format (not MULTIPLE_SPECTRA)
MSExperiment exp_no_im;
MSSpectrum spectrum_no_im;
spectrum_no_im.setNativeID("index=0");
exp_no_im.addSpectrum(spectrum_no_im);
TEST_EQUAL(SpectrumMetaDataLookup::addMissingIMToPeptideIDs(peptides, exp_no_im), false);
// Test 3: MSExperiment with valid IM values
MSExperiment exp_valid;
MSSpectrum spectrum1, spectrum2;
spectrum1.setNativeID("index=0");
spectrum1.setDriftTime(2.5);
spectrum2.setNativeID("index=2");
spectrum2.setDriftTime(5.3);
exp_valid.addSpectrum(spectrum1);
exp_valid.addSpectrum(spectrum2);
peptides.resize(2);
peptides[0].setSpectrumReference("index=0");
peptides[1].setSpectrumReference("index=2");
TEST_EQUAL(SpectrumMetaDataLookup::addMissingIMToPeptideIDs(peptides, exp_valid), true);
// Verify peptide annotations
TEST_REAL_SIMILAR(peptides[0].getMetaValue(Constants::UserParam::IM), 2.5);
TEST_REAL_SIMILAR(peptides[1].getMetaValue(Constants::UserParam::IM), 5.3);
}
END_SECTION
START_SECTION((bool addMissingSpectrumReferences(PeptideIdentificationList& peptides,
const String& filename,
bool stop_on_error,
bool override_spectra_data,
bool override_spectra_references,
vector<ProteinIdentification> proteins)))
{
PeptideIdentificationList peptides(1);
peptides[0].setRT(5.1);
peptides[0].setSpectrumReference( "index=666");
String filename = "this_file_does_not_exist.mzML";
SpectrumMetaDataLookup lookup;
// missing file -> exception, no non-effective executions
TEST_EXCEPTION(Exception::FileNotFound, SpectrumMetaDataLookup::addMissingSpectrumReferences(
peptides, filename, false, false));
// no lookup, no spectrum_references
TEST_EQUAL(peptides[0].getSpectrumReference(), "index=666");
peptides.resize(2);
peptides[1].setRT(5.3);
filename = OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML");
SpectrumMetaDataLookup::addMissingSpectrumReferences(peptides, filename, false, false, false);
TEST_EQUAL(peptides[0].getSpectrumReference(), "index=666"); // no overwrite
TEST_EQUAL(peptides[1].getSpectrumReference(), "index=2");
SpectrumMetaDataLookup::addMissingSpectrumReferences(peptides, filename, false, true, true);
TEST_EQUAL(peptides[0].getSpectrumReference(), "index=0"); // gets updated
TEST_EQUAL(peptides[1].getSpectrumReference(), "index=2");
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MapAlignmentTransformer_test.cpp | .cpp | 7,715 | 257 | // 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/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/ConsensusFeature.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
///////////////////////////
#include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentTransformer.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MapAlignmentTransformer, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MapAlignmentTransformer* ptr = nullptr;
MapAlignmentTransformer* null_ptr = nullptr;
TransformationDescription::DataPoints data;
data.push_back(make_pair(0.0, 1.0));
data.push_back(make_pair(1.0, 3.0));
TransformationDescription td(data);
Param params;
td.fitModel("linear", params);
START_SECTION(MapAlignmentTransformer())
{
ptr = new MapAlignmentTransformer();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~MapAlignmentTransformer())
{
delete ptr;
}
END_SECTION
START_SECTION((static void transformRetentionTimes(PeakMap& msexp, const TransformationDescription& trafo, bool store_original_rt = false)))
{
PeakMap exp;
PeakMap::SpectrumType spec;
// first spectrum (MS)
spec.setRT(11.1);
spec.setMSLevel(1);
exp.addSpectrum(spec);
// second spectrum (MS/MS)
spec.clear(true);
spec.setRT(11.5);
spec.setMSLevel(2);
exp.addSpectrum(spec);
// third spectrum (MS)
spec.clear(true);
spec.setRT(12.2);
spec.setMSLevel(1);
exp.addSpectrum(spec);
// forth spectrum (MS/MS)
spec.clear(true);
spec.setRT(12.5);
spec.setMSLevel(2);
exp.addSpectrum(spec);
MapAlignmentTransformer::transformRetentionTimes(exp, td);
// check the spectra:
TEST_EQUAL(exp[0].getRT(), 23.2)
TEST_EQUAL(exp[1].getRT(), 24.0)
TEST_EQUAL(exp[2].getRT(), 25.4)
TEST_EQUAL(exp[3].getRT(), 26.0)
// check storing of original RTs:
for (Size i = 0; i < 4; ++i)
{
TEST_EQUAL(exp[i].metaValueExists("original_RT"), false);
}
MapAlignmentTransformer::transformRetentionTimes(exp, td, true);
TEST_EQUAL(exp[0].getMetaValue("original_RT"), 23.2);
TEST_EQUAL(exp[1].getMetaValue("original_RT"), 24.0);
TEST_EQUAL(exp[2].getMetaValue("original_RT"), 25.4);
TEST_EQUAL(exp[3].getMetaValue("original_RT"), 26.0);
// applying a transform again doesn't overwrite the original RTs:
MapAlignmentTransformer::transformRetentionTimes(exp, td, true);
TEST_EQUAL(exp[0].getMetaValue("original_RT"), 23.2);
TEST_EQUAL(exp[1].getMetaValue("original_RT"), 24.0);
TEST_EQUAL(exp[2].getMetaValue("original_RT"), 25.4);
TEST_EQUAL(exp[3].getMetaValue("original_RT"), 26.0);
}
END_SECTION
START_SECTION((static void transformRetentionTimes(FeatureMap& fmap, const TransformationDescription& trafo, bool store_original_rt = false)))
{
Feature f;
FeatureMap featmap;
f.setRT(11.1);
featmap.push_back(f);
f.setRT(11.5);
featmap.push_back(f);
f.setRT(12.2);
featmap.push_back(f);
f.setRT(12.5);
featmap.push_back(f);
MapAlignmentTransformer::transformRetentionTimes(featmap, td);
// check the features:
TEST_EQUAL(featmap[0].getRT(), 23.2)
TEST_EQUAL(featmap[1].getRT(), 24.0)
TEST_EQUAL(featmap[2].getRT(), 25.4)
TEST_EQUAL(featmap[3].getRT(), 26.0)
// check storing of original RTs:
for (Size i = 0; i < 4; ++i)
{
TEST_EQUAL(featmap[i].metaValueExists("original_RT"), false);
}
MapAlignmentTransformer::transformRetentionTimes(featmap, td, true);
TEST_EQUAL(featmap[0].getMetaValue("original_RT"), 23.2);
TEST_EQUAL(featmap[1].getMetaValue("original_RT"), 24.0);
TEST_EQUAL(featmap[2].getMetaValue("original_RT"), 25.4);
TEST_EQUAL(featmap[3].getMetaValue("original_RT"), 26.0);
// applying a transform again doesn't overwrite the original RTs:
MapAlignmentTransformer::transformRetentionTimes(featmap, td, true);
TEST_EQUAL(featmap[0].getMetaValue("original_RT"), 23.2);
TEST_EQUAL(featmap[1].getMetaValue("original_RT"), 24.0);
TEST_EQUAL(featmap[2].getMetaValue("original_RT"), 25.4);
TEST_EQUAL(featmap[3].getMetaValue("original_RT"), 26.0);
}
END_SECTION
START_SECTION((static void transformRetentionTimes(ConsensusMap& cmap, const TransformationDescription& trafo, bool store_original_rt = false)))
{
ConsensusFeature cf;
ConsensusMap consensusmap;
cf.setRT(11.1);
consensusmap.push_back(cf);
cf.setRT(11.5);
consensusmap.push_back(cf);
cf.setRT(12.2);
consensusmap.push_back(cf);
cf.setRT(12.5);
consensusmap.push_back(cf);
MapAlignmentTransformer::transformRetentionTimes(consensusmap, td);
// check the consensus features:
TEST_EQUAL(consensusmap[0].getRT(), 23.2)
TEST_EQUAL(consensusmap[1].getRT(), 24.0)
TEST_EQUAL(consensusmap[2].getRT(), 25.4)
TEST_EQUAL(consensusmap[3].getRT(), 26.0)
// check storing of original RTs:
for (Size i = 0; i < 4; ++i)
{
TEST_EQUAL(consensusmap[i].metaValueExists("original_RT"), false);
}
MapAlignmentTransformer::transformRetentionTimes(consensusmap, td, true);
TEST_EQUAL(consensusmap[0].getMetaValue("original_RT"), 23.2);
TEST_EQUAL(consensusmap[1].getMetaValue("original_RT"), 24.0);
TEST_EQUAL(consensusmap[2].getMetaValue("original_RT"), 25.4);
TEST_EQUAL(consensusmap[3].getMetaValue("original_RT"), 26.0);
// applying a transform again doesn't overwrite the original RTs:
MapAlignmentTransformer::transformRetentionTimes(consensusmap, td, true);
TEST_EQUAL(consensusmap[0].getMetaValue("original_RT"), 23.2);
TEST_EQUAL(consensusmap[1].getMetaValue("original_RT"), 24.0);
TEST_EQUAL(consensusmap[2].getMetaValue("original_RT"), 25.4);
TEST_EQUAL(consensusmap[3].getMetaValue("original_RT"), 26.0);
}
END_SECTION
START_SECTION((static void transformRetentionTimes(PeptideIdentificationList& pep_ids, const TransformationDescription& trafo, bool store_original_rt = false)))
{
PeptideIdentification pi;
PeptideIdentificationList pis;
pi.setRT(11.1);
pis.push_back(pi);
pi.setRT(11.5);
pis.push_back(pi);
pi.setRT(12.2);
pis.push_back(pi);
pi.setRT(12.5);
pis.push_back(pi);
MapAlignmentTransformer::transformRetentionTimes(pis, td);
// check the peptide IDs:
TEST_EQUAL(pis[0].getRT(), 23.2)
TEST_EQUAL(pis[1].getRT(), 24.0)
TEST_EQUAL(pis[2].getRT(), 25.4)
TEST_EQUAL(pis[3].getRT(), 26.0)
// check storing of original RTs:
for (Size i = 0; i < 4; ++i)
{
TEST_EQUAL(pis[i].metaValueExists("original_RT"), false);
}
MapAlignmentTransformer::transformRetentionTimes(pis, td, true);
TEST_EQUAL(pis[0].getMetaValue("original_RT"), 23.2);
TEST_EQUAL(pis[1].getMetaValue("original_RT"), 24.0);
TEST_EQUAL(pis[2].getMetaValue("original_RT"), 25.4);
TEST_EQUAL(pis[3].getMetaValue("original_RT"), 26.0);
// applying a transform again doesn't overwrite the original RTs:
MapAlignmentTransformer::transformRetentionTimes(pis, td, true);
TEST_EQUAL(pis[0].getMetaValue("original_RT"), 23.2);
TEST_EQUAL(pis[1].getMetaValue("original_RT"), 24.0);
TEST_EQUAL(pis[2].getMetaValue("original_RT"), 25.4);
TEST_EQUAL(pis[3].getMetaValue("original_RT"), 26.0);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MSChromatogram_test.cpp | .cpp | 32,845 | 1,119 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
#ifndef OPENMS_WINDOWSPLATFORM
#pragma clang diagnostic push
// Ignore -Wpessimizing-move, becuase it's intentional
#pragma clang diagnostic ignored "-Wpessimizing-move"
#endif
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/KERNEL/MSChromatogram.h>
///////////////////////////
#include <sstream>
using namespace OpenMS;
using namespace std;
START_TEST(MSChromatogram, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MSChromatogram* ptr = nullptr;
MSChromatogram* nullPointer = nullptr;
START_SECTION(MSChromatogram())
{
ptr = new MSChromatogram();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(virtual ~MSChromatogram())
{
delete ptr;
}
END_SECTION
ptr = new MSChromatogram();
ChromatogramPeak p1;
p1.setIntensity(1.0f);
p1.setRT(2.0);
ChromatogramPeak p2;
p2.setIntensity(2.0f);
p2.setRT(10.0);
ChromatogramPeak p3;
p3.setIntensity(3.0f);
p3.setRT(30.0);
ChromatogramPeak p4;
p4.setIntensity(6.0f);
p4.setRT(30);
ChromatogramPeak p5;
p5.setIntensity(3.0f);
p5.setRT(30.0001);
START_SECTION((const String& getName() const ))
{
TEST_STRING_EQUAL(ptr->getName(), "")
ptr->setName("my_fancy_name");
TEST_STRING_EQUAL(ptr->getName(), "my_fancy_name")
delete ptr;
}
END_SECTION
START_SECTION((void setName(const String &name)))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((const FloatDataArrays& getFloatDataArrays() const ))
{
MSChromatogram chrom;
TEST_EQUAL(chrom.getFloatDataArrays().size(),0)
}
END_SECTION
START_SECTION((FloatDataArrays& getFloatDataArrays()))
{
MSChromatogram chrom;
chrom.getFloatDataArrays().resize(2);
TEST_EQUAL(chrom.getFloatDataArrays().size(), 2)
}
END_SECTION
START_SECTION((const StringDataArrays& getStringDataArrays() const ))
{
MSChromatogram chrom;
TEST_EQUAL(chrom.getStringDataArrays().size(),0)
}
END_SECTION
START_SECTION((StringDataArrays& getStringDataArrays()))
{
MSChromatogram chrom;
chrom.getStringDataArrays().resize(2);
TEST_EQUAL(chrom.getStringDataArrays().size(), 2)
}
END_SECTION
START_SECTION((const IntegerDataArrays& getIntegerDataArrays() const ))
{
MSChromatogram chrom;
TEST_EQUAL(chrom.getIntegerDataArrays().size(), 0)
}
END_SECTION
START_SECTION((IntegerDataArrays& getIntegerDataArrays()))
{
MSChromatogram chrom;
chrom.getIntegerDataArrays().resize(2);
TEST_EQUAL(chrom.getIntegerDataArrays().size(), 2)
}
END_SECTION
START_SECTION((void sortByIntensity(bool reverse=false)))
{
MSChromatogram ds;
ChromatogramPeak p;
MSChromatogram::FloatDataArray float_array;
MSChromatogram::StringDataArray string_array;
MSChromatogram::IntegerDataArray int_array;
std::vector<double> rts, intensities;
MSChromatogram::IntegerDataArray in_array;
intensities.push_back(201); rts.push_back(420.130); float_array.push_back(420.130f); string_array.push_back("420.13"); int_array.push_back(420);
intensities.push_back(60); rts.push_back(412.824); float_array.push_back(412.824f); string_array.push_back("412.82"); int_array.push_back(412);
intensities.push_back(56); rts.push_back(423.269); float_array.push_back(423.269f); string_array.push_back("423.27"); int_array.push_back(423);
intensities.push_back(37); rts.push_back(415.287); float_array.push_back(415.287f); string_array.push_back("415.29"); int_array.push_back(415);
intensities.push_back(34); rts.push_back(413.800); float_array.push_back(413.800f); string_array.push_back("413.80"); int_array.push_back(413);
intensities.push_back(31); rts.push_back(419.113); float_array.push_back(419.113f); string_array.push_back("419.11"); int_array.push_back(419);
intensities.push_back(31); rts.push_back(416.293); float_array.push_back(416.293f); string_array.push_back("416.29"); int_array.push_back(416);
intensities.push_back(31); rts.push_back(418.232); float_array.push_back(418.232f); string_array.push_back("418.23"); int_array.push_back(418);
intensities.push_back(29); rts.push_back(414.301); float_array.push_back(414.301f); string_array.push_back("414.30"); int_array.push_back(414);
intensities.push_back(29); rts.push_back(412.321); float_array.push_back(412.321f); string_array.push_back("412.32"); int_array.push_back(412);
for (Size i = 0; i < rts.size(); ++i)
{
p.setIntensity(intensities[i]);
p.setRT(rts[i]);
ds.push_back(p);
}
ds.sortByIntensity();
std::vector<double> intensities_copy(intensities);
std::sort(intensities_copy.begin(),intensities_copy.end());
MSChromatogram::iterator it_ds = ds.begin();
for(std::vector<double>::iterator it = intensities_copy.begin(); it != intensities_copy.end(); ++it)
{
if(it_ds == ds.end())
{
TEST_EQUAL(true,false)
}
TEST_EQUAL(it_ds->getIntensity(), *it);
++it_ds;
}
ds.clear(true);
for (Size i = 0; i < rts.size(); ++i)
{
p.setIntensity(intensities[i]);
p.setRT(rts[i]);
ds.push_back(p);
}
intensities_copy = intensities;
std::sort(intensities_copy.begin(),intensities_copy.end());
ds.getFloatDataArrays() = std::vector<MSChromatogram::FloatDataArray>(3,float_array);
ds.getFloatDataArrays()[0].setName("f1");
ds.getFloatDataArrays()[1].setName("f2");
ds.getFloatDataArrays()[2].setName("f3");
ds.getStringDataArrays() = std::vector<MSChromatogram::StringDataArray>(2, string_array);
ds.getStringDataArrays()[0].setName("s1");
ds.getStringDataArrays()[1].setName("s2");
ds.getIntegerDataArrays() = std::vector<MSChromatogram::IntegerDataArray>(1, int_array);
ds.getIntegerDataArrays()[0].setName("i1");
ds.sortByIntensity();
TEST_STRING_EQUAL(ds.getFloatDataArrays()[0].getName(),"f1")
TEST_STRING_EQUAL(ds.getFloatDataArrays()[1].getName(),"f2")
TEST_STRING_EQUAL(ds.getFloatDataArrays()[2].getName(),"f3")
TEST_STRING_EQUAL(ds.getStringDataArrays()[0].getName(),"s1")
TEST_STRING_EQUAL(ds.getStringDataArrays()[1].getName(),"s2")
TEST_STRING_EQUAL(ds.getIntegerDataArrays()[0].getName(),"i1")
MSChromatogram::iterator it1 = ds.begin();
MSChromatogram::FloatDataArray::iterator it2 = ds.getFloatDataArrays()[1].begin();
MSChromatogram::StringDataArray::iterator it3 = ds.getStringDataArrays()[0].begin();
MSChromatogram::IntegerDataArray::iterator it4 = ds.getIntegerDataArrays()[0].begin();
TOLERANCE_ABSOLUTE(0.0001)
for(std::vector<double>::iterator it = intensities_copy.begin(); it != intensities_copy.end(); ++it)
{
if(it1 != ds.end() && it2 != ds.getFloatDataArrays()[1].end() && it3 != ds.getStringDataArrays()[0].end() && it4 != ds.getIntegerDataArrays()[0].end())
{
//metadataarray values == mz values
TEST_REAL_SIMILAR(it1->getIntensity(), *it);
TEST_REAL_SIMILAR(*it2 , it1->getRT());
TEST_STRING_EQUAL(*it3 , String::number(it1->getRT(),2));
TEST_EQUAL(*it4 , (Int)floor(it1->getRT()));
++it1;
++it2;
++it3;
++it4;
}
else
{
TEST_EQUAL(true,false)
}
}
}
END_SECTION
START_SECTION((void sortByPosition()))
{
MSChromatogram ds;
ChromatogramPeak p;
MSChromatogram::FloatDataArray float_array;
MSChromatogram::StringDataArray string_array;
MSChromatogram::IntegerDataArray int_array;
std::vector<double> rts, intensities;
intensities.push_back(56); rts.push_back(423.269); float_array.push_back(56); string_array.push_back("56"); int_array.push_back(56);
intensities.push_back(201); rts.push_back(420.130); float_array.push_back(201); string_array.push_back("201"); int_array.push_back(201);
intensities.push_back(31); rts.push_back(419.113); float_array.push_back(31); string_array.push_back("31"); int_array.push_back(31);
intensities.push_back(31); rts.push_back(418.232); float_array.push_back(31); string_array.push_back("31"); int_array.push_back(31);
intensities.push_back(31); rts.push_back(416.293); float_array.push_back(31); string_array.push_back("31"); int_array.push_back(31);
intensities.push_back(37); rts.push_back(415.287); float_array.push_back(37); string_array.push_back("37"); int_array.push_back(37);
intensities.push_back(29); rts.push_back(414.301); float_array.push_back(29); string_array.push_back("29"); int_array.push_back(29);
intensities.push_back(34); rts.push_back(413.800); float_array.push_back(34); string_array.push_back("34"); int_array.push_back(34);
intensities.push_back(60); rts.push_back(412.824); float_array.push_back(60); string_array.push_back("60"); int_array.push_back(60);
intensities.push_back(29); rts.push_back(412.321); float_array.push_back(29); string_array.push_back("29"); int_array.push_back(29);
for (Size i = 0; i < rts.size(); ++i)
{
p.setIntensity(intensities[i]); p.setRT(rts[i]);
ds.push_back(p);
}
ds.sortByPosition();
MSChromatogram::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(true);
for (Size i = 0; i < rts.size(); ++i)
{
p.setIntensity(intensities[i]); p.setRT(rts[i]);
ds.push_back(p);
}
ds.getFloatDataArrays() = std::vector<MSChromatogram::FloatDataArray>(3,float_array);
ds.getFloatDataArrays()[0].setName("f1");
ds.getFloatDataArrays()[1].setName("f2");
ds.getFloatDataArrays()[2].setName("f3");
ds.getStringDataArrays() = std::vector<MSChromatogram::StringDataArray>(2, string_array);
ds.getStringDataArrays()[0].setName("s1");
ds.getStringDataArrays()[1].setName("s2");
ds.getIntegerDataArrays() = std::vector<MSChromatogram::IntegerDataArray>(2, int_array);
ds.getIntegerDataArrays()[0].setName("i1");
ds.sortByPosition();
TEST_STRING_EQUAL(ds.getFloatDataArrays()[0].getName(),"f1")
TEST_STRING_EQUAL(ds.getFloatDataArrays()[1].getName(),"f2")
TEST_STRING_EQUAL(ds.getFloatDataArrays()[2].getName(),"f3")
TEST_STRING_EQUAL(ds.getStringDataArrays()[0].getName(),"s1")
TEST_STRING_EQUAL(ds.getStringDataArrays()[1].getName(),"s2")
TEST_STRING_EQUAL(ds.getIntegerDataArrays()[0].getName(),"i1")
MSChromatogram::iterator it1 = ds.begin();
MSChromatogram::FloatDataArray::iterator it2 = ds.getFloatDataArrays()[1].begin();
MSChromatogram::StringDataArray::iterator it3 = ds.getStringDataArrays()[0].begin();
MSChromatogram::IntegerDataArray::iterator it4 = ds.getIntegerDataArrays()[0].begin();
for(std::vector<double>::reverse_iterator rit = intensities.rbegin(); rit != intensities.rend(); ++rit)
{
if(it1 != ds.end() && it2 != ds.getFloatDataArrays()[1].end() && it3 != ds.getStringDataArrays()[0].end())
{
//metadataarray values == intensity values
TEST_REAL_SIMILAR(it1->getIntensity(), *rit);
TEST_REAL_SIMILAR(*it2 , *rit);
TEST_STRING_EQUAL(*it3 , String::number(*rit,0));
TEST_EQUAL(*it4 , (Int)floor(*rit));
++it1;
++it2;
++it3;
++it4;
}
else
{
TEST_EQUAL(true,false)
}
}
}
END_SECTION
START_SECTION((bool isSorted() const ))
{
//make test dataset
MSChromatogram spec;
ChromatogramPeak p;
p.setIntensity(1.0);
p.setRT(1000.0);
spec.push_back(p);
p.setIntensity(1.0);
p.setRT(1001.0);
spec.push_back(p);
p.setIntensity(1.0);
p.setRT(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((Size findNearest(CoordinateType rt) const ))
{
MSChromatogram tmp;
ChromatogramPeak p;
p.setIntensity(29.0f); p.setRT(412.321); tmp.push_back(p); //0
p.setIntensity(60.0f); p.setRT(412.824); tmp.push_back(p); //1
p.setIntensity(34.0f); p.setRT(413.8); tmp.push_back(p); //2
p.setIntensity(29.0f); p.setRT(414.301); tmp.push_back(p); //3
p.setIntensity(37.0f); p.setRT(415.287); tmp.push_back(p); //4
p.setIntensity(31.0f); p.setRT(416.293); tmp.push_back(p); //5
p.setIntensity(31.0f); p.setRT(418.232); tmp.push_back(p); //6
p.setIntensity(31.0f); p.setRT(419.113); tmp.push_back(p); //7
p.setIntensity(201.0f); p.setRT(420.13); tmp.push_back(p); //8
p.setIntensity(56.0f); p.setRT(423.269); tmp.push_back(p); //9
p.setIntensity(34.0f); p.setRT(426.292); tmp.push_back(p); //10
p.setIntensity(82.0f); p.setRT(427.28); tmp.push_back(p); //11
p.setIntensity(87.0f); p.setRT(428.322); tmp.push_back(p); //12
p.setIntensity(30.0f); p.setRT(430.269); tmp.push_back(p); //13
p.setIntensity(29.0f); p.setRT(431.246); tmp.push_back(p); //14
p.setIntensity(42.0f); p.setRT(432.289); tmp.push_back(p); //15
p.setIntensity(32.0f); p.setRT(436.161); tmp.push_back(p); //16
p.setIntensity(54.0f); p.setRT(437.219); tmp.push_back(p); //17
p.setIntensity(40.0f); p.setRT(439.186); tmp.push_back(p); //18
p.setIntensity(40); p.setRT(440.27); tmp.push_back(p); //19
p.setIntensity(23.0f); p.setRT(441.224); tmp.push_back(p); //20
//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
MSChromatogram tmp2;
TEST_PRECONDITION_VIOLATED(tmp2.findNearest(427.3));
}
END_SECTION
START_SECTION((Iterator RTBegin(CoordinateType rt)))
{
MSChromatogram tmp;
MSChromatogram::PeakType rdp;
rdp.getPosition()[0] = 1.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 2.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 3.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 4.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 5.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 6.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 7.0;
tmp.push_back(rdp);
MSChromatogram::Iterator it;
it = tmp.RTBegin(4.5);
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTBegin(5.0);
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTBegin(5.5);
TEST_EQUAL(it->getPosition()[0],6.0)
}
END_SECTION
START_SECTION((Iterator RTBegin(Iterator begin, CoordinateType rt, Iterator end)))
{
MSChromatogram tmp;
MSChromatogram::PeakType rdp;
rdp.getPosition()[0] = 1.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 2.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 3.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 4.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 5.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 6.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 7.0;
tmp.push_back(rdp);
MSChromatogram::Iterator it;
it = tmp.RTBegin(tmp.begin(), 4.5, tmp.end());
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTBegin(tmp.begin(), 4.5, tmp.end());
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTBegin(tmp.begin(), 4.5, tmp.begin());
TEST_EQUAL(it->getPosition()[0],tmp.begin()->getPosition()[0])
}
END_SECTION
START_SECTION((Iterator RTEnd(CoordinateType rt)))
{
MSChromatogram tmp;
MSChromatogram::PeakType rdp;
rdp.getPosition()[0] = 1.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 2.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 3.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 4.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 5.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 6.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 7.0;
tmp.push_back(rdp);
MSChromatogram::Iterator it;
it = tmp.RTEnd(4.5);
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTEnd(5.0);
TEST_EQUAL(it->getPosition()[0],6.0)
it = tmp.RTEnd(5.5);
TEST_EQUAL(it->getPosition()[0],6.0)
}
END_SECTION
START_SECTION((Iterator RTEnd(Iterator begin, CoordinateType rt, Iterator end)))
{
MSChromatogram tmp;
MSChromatogram::PeakType rdp;
rdp.getPosition()[0] = 1.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 2.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 3.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 4.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 5.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 6.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 7.0;
tmp.push_back(rdp);
MSChromatogram::Iterator it;
it = tmp.RTEnd(tmp.begin(), 3.5, tmp.end());
TEST_EQUAL(it->getPosition()[0],4.0)
it = tmp.RTEnd(tmp.begin(), 5.0, tmp.end());
TEST_EQUAL(it->getPosition()[0],6.0)
it = tmp.RTEnd(tmp.begin(), 4.5, tmp.begin());
TEST_EQUAL(it->getPosition()[0],tmp.begin()->getPosition()[0])
}
END_SECTION
START_SECTION((ConstIterator RTBegin(CoordinateType rt) const ))
{
MSChromatogram tmp;
MSChromatogram::PeakType rdp;
rdp.getPosition()[0] = 1.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 2.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 3.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 4.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 5.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 6.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 7.0;
tmp.push_back(rdp);
MSChromatogram::ConstIterator it;
it = tmp.RTBegin(4.5);
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTBegin(5.0);
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTBegin(5.5);
TEST_EQUAL(it->getPosition()[0],6.0)
}
END_SECTION
START_SECTION((ConstIterator RTBegin(ConstIterator begin, CoordinateType rt, ConstIterator end) const ))
{
MSChromatogram tmp;
MSChromatogram::PeakType rdp;
rdp.getPosition()[0] = 1.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 2.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 3.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 4.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 5.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 6.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 7.0;
tmp.push_back(rdp);
MSChromatogram::ConstIterator it;
it = tmp.RTBegin(tmp.begin(), 4.5, tmp.end());
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTBegin(tmp.begin(), 4.5, tmp.end());
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTBegin(tmp.begin(), 4.5, tmp.begin());
TEST_EQUAL(it->getPosition()[0],tmp.begin()->getPosition()[0])
}
END_SECTION
START_SECTION((ConstIterator RTEnd(CoordinateType rt) const ))
{
MSChromatogram tmp;
MSChromatogram::PeakType rdp;
rdp.getPosition()[0] = 1.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 2.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 3.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 4.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 5.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 6.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 7.0;
tmp.push_back(rdp);
MSChromatogram::ConstIterator it;
it = tmp.RTEnd(4.5);
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTEnd(5.0);
TEST_EQUAL(it->getPosition()[0],6.0)
it = tmp.RTEnd(5.5);
TEST_EQUAL(it->getPosition()[0],6.0)
}
END_SECTION
START_SECTION((ConstIterator RTEnd(ConstIterator begin, CoordinateType rt, ConstIterator end) const ))
{
MSChromatogram tmp;
MSChromatogram::PeakType rdp;
rdp.getPosition()[0] = 1.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 2.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 3.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 4.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 5.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 6.0;
tmp.push_back(rdp);
rdp.getPosition()[0] = 7.0;
tmp.push_back(rdp);
MSChromatogram::ConstIterator it;
it = tmp.RTEnd(tmp.begin(), 4.5, tmp.end());
TEST_EQUAL(it->getPosition()[0],5.0)
it = tmp.RTEnd(tmp.begin(), 5, tmp.end());
TEST_EQUAL(it->getPosition()[0],6.0)
it = tmp.RTEnd(tmp.begin(), 4.5, tmp.begin());
TEST_EQUAL(it->getPosition()[0],tmp.begin()->getPosition()[0])
}
END_SECTION
MSChromatogram tmp;
vector<double> position = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0};
for (Size i=0; i<position.size(); ++i)
{
ChromatogramPeak cp;
cp.setPos(position[i]);
tmp.push_back(cp);
}
START_SECTION((Iterator PosBegin(CoordinateType rt)))
{
MSChromatogram::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 rt, Iterator end)))
{
MSChromatogram::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 rt) const ))
{
MSChromatogram::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 rt, ConstIterator end) const ))
{
MSChromatogram::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 rt)))
{
MSChromatogram::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 rt, Iterator end)))
{
MSChromatogram::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 rt) const ))
{
MSChromatogram::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 rt, ConstIterator end) const ))
{
MSChromatogram::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
/////////////////////////////////////////////////////////////
// Copy constructor, move constructor, assignment operator, move assignment operator, equality
START_SECTION((MSChromatogram(const MSChromatogram &source)))
{
MSChromatogram tmp;
tmp.getInstrumentSettings().getScanWindows().resize(1);
tmp.setMetaValue("label",5.0);
Product prod;
prod.setMZ(7.0);
tmp.setProduct(prod);
tmp.setName("bla");
//peaks
MSChromatogram::PeakType peak;
peak.getPosition()[0] = 47.11;
tmp.push_back(peak);
MSChromatogram tmp2(tmp);
TEST_EQUAL(tmp2.getInstrumentSettings().getScanWindows().size(),1);
TEST_REAL_SIMILAR(tmp2.getMetaValue("label"), 5.0)
TEST_REAL_SIMILAR(tmp2.getMZ(), 7.0)
TEST_EQUAL(tmp2.getName(),"bla")
//peaks
TEST_EQUAL(tmp2.size(),1);
TEST_REAL_SIMILAR(tmp2[0].getPosition()[0],47.11);
}
END_SECTION
START_SECTION((MSChromatogram(const MSChromatogram &&source)))
{
// Ensure that MSChromatogram has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(MSChromatogram(std::declval<MSChromatogram&&>())), true)
MSChromatogram tmp;
tmp.getInstrumentSettings().getScanWindows().resize(1);
tmp.setMetaValue("label",5.0);
Product prod;
prod.setMZ(7.0);
tmp.setProduct(prod);
tmp.setName("bla");
//peaks
MSChromatogram::PeakType peak;
peak.getPosition()[0] = 47.11;
tmp.push_back(peak);
//copy tmp so we can move one of them
MSChromatogram orig = tmp;
MSChromatogram tmp2(std::move(tmp));
TEST_EQUAL(tmp2, orig); // should be equal to the original
TEST_EQUAL(tmp2.getInstrumentSettings().getScanWindows().size(),1);
TEST_REAL_SIMILAR(tmp2.getMetaValue("label"), 5.0)
TEST_REAL_SIMILAR(tmp2.getMZ(), 7.0)
TEST_EQUAL(tmp2.getName(),"bla")
//peaks
TEST_EQUAL(tmp2.size(),1);
TEST_REAL_SIMILAR(tmp2[0].getPosition()[0],47.11);
// test move
TEST_EQUAL(tmp.size(),0);
TEST_EQUAL(tmp.metaValueExists("label"), false);
}
END_SECTION
START_SECTION((MSChromatogram& operator=(const MSChromatogram &source)))
{
MSChromatogram tmp;
tmp.setMetaValue("label",5.0);
Product prod;
prod.setMZ(7.0);
tmp.setProduct(prod);
tmp.setName("bla");
//peaks
MSChromatogram::PeakType peak;
peak.getPosition()[0] = 47.11;
tmp.push_back(peak);
//normal assignment
MSChromatogram tmp2;
tmp2 = tmp;
TEST_REAL_SIMILAR(tmp2.getMetaValue("label"), 5.0)
TEST_REAL_SIMILAR(tmp2.getMZ(), 7.0)
TEST_EQUAL(tmp2.getName(),"bla")
TEST_EQUAL(tmp2.size(),1);
TEST_REAL_SIMILAR(tmp2[0].getPosition()[0],47.11);
//Assignment of empty object
//normal assignment
tmp2 = MSChromatogram();
TEST_EQUAL(tmp2.getInstrumentSettings().getScanWindows().size(),0);
TEST_EQUAL(tmp2.metaValueExists("label"), false)
TEST_REAL_SIMILAR(tmp2.getMZ(), 0.0)
TEST_EQUAL(tmp2.getName(),"")
TEST_EQUAL(tmp2.size(),0);
}
END_SECTION
START_SECTION((MSChromatogram& operator=(const MSChromatogram &&source)))
{
MSChromatogram tmp;
tmp.setMetaValue("label",5.0);
Product prod;
prod.setMZ(7.0);
tmp.setProduct(prod);
tmp.setName("bla");
//peaks
MSChromatogram::PeakType peak;
peak.getPosition()[0] = 47.11;
tmp.push_back(peak);
//copy tmp so we can move one of them
MSChromatogram orig = tmp;
//move assignment
MSChromatogram tmp2;
tmp2 = std::move(tmp);
TEST_EQUAL(tmp2, orig); // should be equal to the original
//normal assignment
TEST_REAL_SIMILAR(tmp2.getMetaValue("label"), 5.0)
TEST_REAL_SIMILAR(tmp2.getMZ(), 7.0)
TEST_EQUAL(tmp2.getName(),"bla")
TEST_EQUAL(tmp2.size(),1);
TEST_REAL_SIMILAR(tmp2[0].getPosition()[0],47.11);
// test move
TEST_EQUAL(tmp.size(),0);
TEST_EQUAL(tmp.metaValueExists("label"), false);
//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(MSChromatogram());
#ifndef OPENMS_WINDOWSPLATFORM
#pragma clang diagnostic pop
#endif
TEST_EQUAL(tmp2.getInstrumentSettings().getScanWindows().size(),0);
TEST_EQUAL(tmp2.metaValueExists("label"), false)
TEST_REAL_SIMILAR(tmp2.getMZ(), 0.0)
TEST_EQUAL(tmp2.getName(),"")
TEST_EQUAL(tmp2.size(),0);
}
END_SECTION
START_SECTION((bool operator==(const MSChromatogram &rhs) const ))
{
MSChromatogram edit, empty;
TEST_EQUAL(edit==empty,true);
edit = empty;
edit.resize(1);
TEST_EQUAL(edit==empty,false);
edit = empty;
edit.setMetaValue("label",String("bla"));
TEST_EQUAL(empty==edit, false);
Product prod;
prod.setMZ(5);
edit.setProduct(prod);
TEST_EQUAL(empty==edit, false);
edit = empty;
edit.getFloatDataArrays().resize(5);
TEST_EQUAL(empty==edit, false);
edit = empty;
edit.getStringDataArrays().resize(5);
TEST_EQUAL(empty==edit, false);
edit = empty;
edit.getIntegerDataArrays().resize(5);
TEST_EQUAL(empty==edit, false);
//name is not checked => no change
edit = empty;
edit.setName("bla");
TEST_TRUE(empty == edit);
edit = empty;
edit.push_back(p1);
edit.push_back(p2);
edit.updateRanges();
edit.clear(false);
TEST_TRUE(empty == edit);
}
END_SECTION
START_SECTION((bool operator!=(const MSChromatogram &rhs) const ))
{
MSChromatogram edit, empty;
TEST_EQUAL(edit!=empty,false);
edit = empty;
edit.getInstrumentSettings().getScanWindows().resize(1);
TEST_EQUAL(edit!=empty,true);
edit = empty;
edit.resize(1);
TEST_EQUAL(edit!=empty,true);
edit = empty;
edit.setMetaValue("label",String("bla"));
TEST_EQUAL(edit!=empty,true);
Product prod;
prod.setMZ(5);
edit.setProduct(prod);
TEST_EQUAL(edit!=empty,true);
edit = empty;
edit.getFloatDataArrays().resize(5);
TEST_EQUAL(edit!=empty,true);
edit = empty;
edit.getIntegerDataArrays().resize(5);
TEST_EQUAL(edit!=empty,true);
edit = empty;
edit.getStringDataArrays().resize(5);
TEST_EQUAL(edit!=empty,true);
//name is not checked => no change
edit = empty;
edit.setName("bla");
TEST_EQUAL(edit == empty, true);
edit = empty;
edit.push_back(p1);
edit.push_back(p2);
edit.updateRanges();
edit.clear(false);
TEST_TRUE(empty == edit);
}
END_SECTION
START_SECTION((virtual void updateRanges()))
{
MSChromatogram 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.getMaxRT(),10)
TEST_REAL_SIMILAR(s.getMinRT(),2)
//test with only one peak
s.clear(true);
s.push_back(p1);
s.updateRanges();
TEST_REAL_SIMILAR(s.getMaxIntensity(), 1)
TEST_REAL_SIMILAR(s.getMinIntensity(), 1)
TEST_REAL_SIMILAR(s.getMaxRT(),2)
TEST_REAL_SIMILAR(s.getMinRT(),2)
}
END_SECTION
START_SECTION(void clear(bool clear_meta_data))
{
MSChromatogram edit;
edit.getInstrumentSettings().getScanWindows().resize(1);
edit.resize(1);
edit.setMetaValue("label",String("bla"));
edit.getProduct().setMZ(5);
edit.getFloatDataArrays().resize(5);
edit.getIntegerDataArrays().resize(5);
edit.getStringDataArrays().resize(5);
edit.clear(false);
TEST_EQUAL(edit.size(),0)
TEST_EQUAL(edit.empty(),true)
TEST_EQUAL(edit == MSChromatogram(),false)
edit.clear(true);
TEST_EQUAL(edit.size(),0)
TEST_EQUAL(edit.empty(),true)
TEST_EQUAL(edit == MSChromatogram(),true)
}
END_SECTION
START_SECTION((double getMZ() const))
{
MSChromatogram tmp;
Product prod;
prod.setMZ(0.1);
TEST_REAL_SIMILAR(tmp.getMZ(), 0.0)
tmp.setProduct(prod);
TEST_REAL_SIMILAR(tmp.getMZ(), 0.1)
}
END_SECTION
START_SECTION(([MSChromatogram::MZLess] bool operator()(const MSChromatogram &a, const MSChromatogram &b) const))
{
MSChromatogram a;
Product pa;
pa.setMZ(1000.0);
a.setProduct(pa);
MSChromatogram b;
Product pb;
pb.setMZ(1000.1);
b.setProduct(pb);
TEST_EQUAL(MSChromatogram::MZLess().operator ()(a,b), true)
TEST_EQUAL(MSChromatogram::MZLess().operator ()(b,a), false)
TEST_EQUAL(MSChromatogram::MZLess().operator ()(a,a), false)
}
END_SECTION
START_SECTION(void mergePeaks(MSChromatogram & other) )
{
MSChromatogram a, b, c;
a.push_back(p1);
b.push_back(p2);
a.push_back(p3);
b.push_back(p5);
c.push_back(p1);
c.push_back(p2);
c.push_back(p4);
a.sortByPosition();
b.sortByPosition();
c.sortByPosition();
a.mergePeaks(b, true);
DoubleList dl = { b.getMZ() };
c.setMetaValue(Constants::UserParam::MERGED_CHROMATOGRAM_MZS, dl);
TEST_EQUAL(a, c)
}
END_SECTION
START_SECTION( std::ostream& operator<<(std::ostream& os, const MSChromatogram& chrom))
{
MSChromatogram a;
Product pa;
pa.setMZ(1000.0);
a.setProduct(pa);
MSChromatogram::PeakType peak;
peak.getPosition()[0] = 47.11;
a.push_back(peak);
std::ostringstream os;
os << a;
TEST_EQUAL(String(os.str()).hasSubstring("MSCHROMATOGRAM BEGIN"), true);
TEST_EQUAL(String(os.str()).hasSubstring("47.11"), true);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
#ifndef OPENMS_WINDOWSPLATFORM
#pragma clang diagnostic pop
#endif
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/FWHM_test.cpp | .cpp | 1,915 | 70 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/QC/FWHM.h>
///////////////////////////
START_TEST(FWHM, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
FWHM* ptr = nullptr;
FWHM* nullPointer = nullptr;
START_SECTION(MzCalibration())
ptr = new FWHM();
TEST_NOT_EQUAL(ptr, nullPointer);
END_SECTION
START_SECTION(~FWHM())
delete ptr;
END_SECTION
START_SECTION(void compute(FeatureMap& features))
{
Feature f;
PeptideIdentification pi;
pi.getHits().push_back(PeptideHit(1.0, 1, 3, AASequence::fromString("KKK")));
f.getPeptideIdentifications().push_back(pi);
f.setMetaValue("FWHM", 123.4);
FeatureMap fm;
fm.push_back(f);
f.clearMetaInfo();
f.setMetaValue("model_FWHM", 98.1);
fm.push_back(f);
FWHM fw;
fw.compute(fm);
TEST_EQUAL(fm[0].getPeptideIdentifications()[0].getMetaValue("FWHM"), 123.4)
TEST_EQUAL(fm[1].getPeptideIdentifications()[0].getMetaValue("FWHM"), 98.1)
}
END_SECTION
START_SECTION(QCBase::Status requirements() const override)
{
FWHM fw;
TEST_EQUAL(fw.requirements() == (QCBase::Status() | QCBase::Requires::POSTFDRFEAT), true);
}
END_SECTION
START_SECTION(const String& getName() const)
{
TEST_EQUAL(FWHM().getName(), "FWHM");
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SimpleSearchEngineAlgorithm_test.cpp | .cpp | 1,394 | 52 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
///////////////////////////
#include <OpenMS/ANALYSIS/ID/SimpleSearchEngineAlgorithm.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(SimpleSearchEngineAlgorithm, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
SimpleSearchEngineAlgorithm* ptr = 0;
SimpleSearchEngineAlgorithm* null_ptr = 0;
START_SECTION(SimpleSearchEngineAlgorithm())
{
ptr = new SimpleSearchEngineAlgorithm();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~SimpleSearchEngineAlgorithm())
{
delete ptr;
}
END_SECTION
START_SECTION((ExitCodes search(const String &in_mzML, const String &in_db, std::vector< ProteinIdentification > &prot_ids, std::vector< PeptideIdentification > &pep_ids) const ))
{
// tested via tool
NOT_TESTABLE
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/AbsoluteQuantitationMethodFile_test.cpp | .cpp | 11,807 | 252 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
//
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/SYSTEM/File.h>
///////////////////////////
#include <OpenMS/FORMAT/AbsoluteQuantitationMethodFile.h>
#include <OpenMS/ANALYSIS/QUANTITATION/AbsoluteQuantitationMethod.h>
using namespace OpenMS;
using namespace std;
class AbsoluteQuantitationMethodFile_facade : AbsoluteQuantitationMethodFile
{
public:
void parseLine_(StringList & line, std::map<String,Size> & headers, AbsoluteQuantitationMethod & aqm)
{
AbsoluteQuantitationMethodFile::parseLine_(line, headers, aqm);
}
};
///////////////////////////
START_TEST(AbsoluteQuantitationMethodFile, "$Id$")
/////////////////////////////////////////////////////////////
AbsoluteQuantitationMethodFile* ptr = nullptr;
AbsoluteQuantitationMethodFile* nullPointer = nullptr;
const String in_file_1 = OPENMS_GET_TEST_DATA_PATH("AbsoluteQuantitationMethodFile_in_1.csv");
const String in_file_2 = OPENMS_GET_TEST_DATA_PATH("AbsoluteQuantitationMethodFile_in_2.csv");
const String out_file = File::getTemporaryFile();
START_SECTION((AbsoluteQuantitationMethodFile()))
ptr = new AbsoluteQuantitationMethodFile();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~AbsoluteQuantitationMethodFile()))
delete ptr;
END_SECTION
START_SECTION(void parseLine_(StringList & line, std::map<String,Size> & headers, AbsoluteQuantitationMethod & aqm) const)
AbsoluteQuantitationMethodFile_facade aqmf;
AbsoluteQuantitationMethod aqm;
// headers
std::map<String, Size> headers;
headers["IS_name"] = 0;
headers["component_name"] = 1;
headers["feature_name"] = 2;
headers["concentration_units"] = 3;
headers["llod"] = 4;
headers["ulod"] = 5;
headers["lloq"] = 6;
headers["uloq"] = 7;
headers["correlation_coefficient"] = 8;
headers["n_points"] = 9;
headers["transformation_model"] = 10;
headers["transformation_model_param_slope"] = 11;
headers["transformation_model_param_intercept"] = 12;
// line test 1
StringList line1;
line1.push_back("IS1");
line1.push_back("component1");
line1.push_back("feature1");
line1.push_back("uM");
line1.push_back("3.0");
line1.push_back(" "); //test for empty string
line1.push_back(" 2.0 "); //test for leading and trailing white spaces
line1.push_back("8.0");
line1.push_back("0.99");
line1.push_back("5");
line1.push_back("TransformationModelLinear");
line1.push_back("2.0");
line1.push_back("1.0");
aqmf.parseLine_(line1, headers, aqm);
TEST_EQUAL(aqm.getISName(), "IS1");
TEST_EQUAL(aqm.getComponentName(), "component1");
TEST_EQUAL(aqm.getFeatureName(), "feature1");
TEST_EQUAL(aqm.getConcentrationUnits(), "uM");
TEST_REAL_SIMILAR(aqm.getLLOD(), 3.0);
TEST_REAL_SIMILAR(aqm.getULOD(), 0.0);
TEST_REAL_SIMILAR(aqm.getLLOQ(), 2.0);
TEST_REAL_SIMILAR(aqm.getULOQ(), 8.0);
TEST_REAL_SIMILAR(aqm.getCorrelationCoefficient(), 0.99);
TEST_EQUAL(aqm.getNPoints(), 5);
TEST_EQUAL(aqm.getTransformationModel(), "TransformationModelLinear");
const Param transformation_model_params = aqm.getTransformationModelParams();
TEST_REAL_SIMILAR(transformation_model_params.getValue("slope"), 2.0);
TEST_REAL_SIMILAR(transformation_model_params.getValue("intercept"), 1.0);
END_SECTION
START_SECTION(void load(const String & filename, std::vector<AbsoluteQuantitationMethod> & aqm_list))
AbsoluteQuantitationMethodFile aqmf;
std::vector<AbsoluteQuantitationMethod> aqm_list;
aqmf.load(in_file_1, aqm_list);
TEST_EQUAL(aqm_list[0].getComponentName(), "component1");
TEST_EQUAL(aqm_list[0].getISName(), "IS1");
TEST_EQUAL(aqm_list[0].getFeatureName(), "feature1");
TEST_EQUAL(aqm_list[0].getConcentrationUnits(), "uM");
TEST_REAL_SIMILAR(aqm_list[0].getLLOD(), 0.0);
TEST_REAL_SIMILAR(aqm_list[0].getULOD(), 10.0);
TEST_REAL_SIMILAR(aqm_list[0].getLLOQ(), 2.0);
TEST_REAL_SIMILAR(aqm_list[0].getULOQ(), 8.0);
TEST_REAL_SIMILAR(aqm_list[0].getCorrelationCoefficient(), 0.99);
TEST_EQUAL(aqm_list[0].getNPoints(), 5);
TEST_EQUAL(aqm_list[0].getTransformationModel(), "TransformationModelLinear");
Param transformation_model_params;
transformation_model_params = aqm_list[0].getTransformationModelParams();
TEST_REAL_SIMILAR(transformation_model_params.getValue("slope"), 2.0);
TEST_REAL_SIMILAR(transformation_model_params.getValue("intercept"), 1.0);
TEST_EQUAL(aqm_list[1].getComponentName(), "component2");
TEST_EQUAL(aqm_list[1].getISName(), "IS2");
TEST_EQUAL(aqm_list[1].getFeatureName(), "feature2");
TEST_EQUAL(aqm_list[1].getConcentrationUnits(), "uM");
TEST_REAL_SIMILAR(aqm_list[1].getLLOD(), 1.0);
TEST_REAL_SIMILAR(aqm_list[1].getULOD(), 9.0);
TEST_REAL_SIMILAR(aqm_list[1].getLLOQ(), 3.0);
TEST_REAL_SIMILAR(aqm_list[1].getULOQ(), 7.0);
TEST_REAL_SIMILAR(aqm_list[1].getCorrelationCoefficient(), 0.98);
TEST_EQUAL(aqm_list[1].getNPoints(), 4);
TEST_EQUAL(aqm_list[1].getTransformationModel(), "TransformationModelLinear");
transformation_model_params = aqm_list[1].getTransformationModelParams();
TEST_REAL_SIMILAR(transformation_model_params.getValue("slope"), 2.0);
TEST_REAL_SIMILAR(transformation_model_params.getValue("intercept"), 2.0);
TEST_EQUAL(aqm_list[2].getComponentName(), "component3");
TEST_EQUAL(aqm_list[2].getISName(), "IS3");
TEST_EQUAL(aqm_list[2].getFeatureName(), "feature3");
TEST_EQUAL(aqm_list[2].getConcentrationUnits(), "uM");
TEST_REAL_SIMILAR(aqm_list[2].getLLOD(), 2.0);
TEST_REAL_SIMILAR(aqm_list[2].getULOD(), 8.0);
TEST_REAL_SIMILAR(aqm_list[2].getLLOQ(), 4.0);
TEST_REAL_SIMILAR(aqm_list[2].getULOQ(), 6.0);
TEST_REAL_SIMILAR(aqm_list[2].getCorrelationCoefficient(), 0.97);
TEST_EQUAL(aqm_list[2].getNPoints(), 3);
TEST_EQUAL(aqm_list[2].getTransformationModel(), "TransformationModelLinear");
transformation_model_params = aqm_list[2].getTransformationModelParams();
TEST_REAL_SIMILAR(transformation_model_params.getValue("slope"), 1.0);
TEST_REAL_SIMILAR(transformation_model_params.getValue("intercept"), 2.0);
TEST_EQUAL(aqm_list[6].getComponentName(), "component 7"); // Checking for space within the name
TEST_EQUAL(aqm_list[6].getISName(), ""); // empty cell, default value is used.
TEST_EQUAL(aqm_list[6].getFeatureName(), "feature 7");
TEST_EQUAL(aqm_list[6].getConcentrationUnits(), "");
TEST_REAL_SIMILAR(aqm_list[6].getLLOD(), 0.0); // empty cell, default value is used.
TEST_REAL_SIMILAR(aqm_list[6].getULOD(), 0.0);
TEST_REAL_SIMILAR(aqm_list[6].getLLOQ(), 0.0);
TEST_REAL_SIMILAR(aqm_list[6].getULOQ(), 0.0);
TEST_REAL_SIMILAR(aqm_list[6].getCorrelationCoefficient(), 0.0);
TEST_EQUAL(aqm_list[6].getNPoints(), 0);
TEST_EQUAL(aqm_list[6].getTransformationModel(), "");
transformation_model_params = aqm_list[6].getTransformationModelParams();
TEST_REAL_SIMILAR(transformation_model_params.getValue("slope"), 0.0); // empty cell, default value is used.
TEST_REAL_SIMILAR(transformation_model_params.getValue("intercept"), 2.0);
TEST_EQUAL(aqm_list[7].getComponentName(), "component8");
TEST_EQUAL(aqm_list[7].getISName(), "IS8");
TEST_EQUAL(aqm_list[7].getFeatureName(), "feature8");
TEST_EQUAL(aqm_list[7].getConcentrationUnits(), "uM");
TEST_REAL_SIMILAR(aqm_list[7].getLLOD(), 7.0);
TEST_REAL_SIMILAR(aqm_list[7].getULOD(), 3.0);
TEST_REAL_SIMILAR(aqm_list[7].getLLOQ(), 0.0);
TEST_REAL_SIMILAR(aqm_list[7].getULOQ(), 1.0);
TEST_REAL_SIMILAR(aqm_list[7].getCorrelationCoefficient(), 0.92);
TEST_EQUAL(aqm_list[7].getNPoints(), 1);
TEST_EQUAL(aqm_list[7].getTransformationModel(), "TransformationModelLinear");
transformation_model_params = aqm_list[7].getTransformationModelParams();
TEST_REAL_SIMILAR(transformation_model_params.getValue("slope"), 1.0);
TEST_REAL_SIMILAR(transformation_model_params.getValue("intercept"), 2.0);
// The following input file doesn't have the headers: component_name, llod
// Note that a default value of "" and 0 is given for these missing columns.
aqmf.load(in_file_2, aqm_list);
TEST_EQUAL(aqm_list[0].getComponentName(), ""); // A component name with a default value.
TEST_EQUAL(aqm_list[0].getISName(), "IS1");
TEST_EQUAL(aqm_list[0].getFeatureName(), "feature1");
TEST_EQUAL(aqm_list[0].getConcentrationUnits(), "uM");
TEST_REAL_SIMILAR(aqm_list[0].getLLOD(), 0.0); // A LLOD with a default value.
TEST_REAL_SIMILAR(aqm_list[0].getULOD(), 10.0);
TEST_REAL_SIMILAR(aqm_list[0].getLLOQ(), 2.0);
TEST_REAL_SIMILAR(aqm_list[0].getULOQ(), 8.0);
TEST_REAL_SIMILAR(aqm_list[0].getCorrelationCoefficient(), 0.99);
TEST_EQUAL(aqm_list[0].getNPoints(), 5);
TEST_EQUAL(aqm_list[0].getTransformationModel(), "TransformationModelLinear");
transformation_model_params = aqm_list[0].getTransformationModelParams();
TEST_REAL_SIMILAR(transformation_model_params.getValue("slope"), 2.0);
TEST_REAL_SIMILAR(transformation_model_params.getValue("intercept"), 1.0);
TEST_EQUAL(aqm_list[1].getComponentName(), ""); // A component name with a default value.
TEST_EQUAL(aqm_list[1].getISName(), ""); // empty cell, default value is used.
TEST_EQUAL(aqm_list[1].getFeatureName(), "feature 7");
TEST_EQUAL(aqm_list[1].getConcentrationUnits(), "");
TEST_REAL_SIMILAR(aqm_list[1].getLLOD(), 0.0); // empty cell, default value is used.
TEST_REAL_SIMILAR(aqm_list[1].getULOD(), 0.0);
TEST_REAL_SIMILAR(aqm_list[1].getLLOQ(), 0.0);
TEST_REAL_SIMILAR(aqm_list[1].getULOQ(), 0.0);
TEST_REAL_SIMILAR(aqm_list[1].getCorrelationCoefficient(), 0.0);
TEST_EQUAL(aqm_list[1].getNPoints(), 0);
TEST_EQUAL(aqm_list[1].getTransformationModel(), "");
transformation_model_params = aqm_list[1].getTransformationModelParams();
TEST_REAL_SIMILAR(transformation_model_params.getValue("slope"), 0.0); // empty cell, default value is used.
TEST_REAL_SIMILAR(transformation_model_params.getValue("intercept"), 2.0);
TEST_EQUAL(aqm_list[2].getComponentName(), ""); // A component name with a default value.
TEST_EQUAL(aqm_list[2].getISName(), "IS8");
TEST_EQUAL(aqm_list[2].getFeatureName(), "feature8");
TEST_EQUAL(aqm_list[2].getConcentrationUnits(), "uM");
TEST_REAL_SIMILAR(aqm_list[2].getLLOD(), 0.0); // A LLOD with a default value.
TEST_REAL_SIMILAR(aqm_list[2].getULOD(), 3.0);
TEST_REAL_SIMILAR(aqm_list[2].getLLOQ(), 0.0);
TEST_REAL_SIMILAR(aqm_list[2].getULOQ(), 1.0);
TEST_REAL_SIMILAR(aqm_list[2].getCorrelationCoefficient(), 0.92);
TEST_EQUAL(aqm_list[2].getNPoints(), 1);
TEST_EQUAL(aqm_list[2].getTransformationModel(), "TransformationModelLinear");
transformation_model_params = aqm_list[2].getTransformationModelParams();
TEST_REAL_SIMILAR(transformation_model_params.getValue("slope"), 1.0);
TEST_REAL_SIMILAR(transformation_model_params.getValue("intercept"), 2.0);
END_SECTION
START_SECTION(void store(const String & filename, const std::vector<AbsoluteQuantitationMethod> & aqm_list) const)
AbsoluteQuantitationMethodFile aqmf;
vector<AbsoluteQuantitationMethod> aqm_list1, aqm_list2;
aqmf.load(in_file_1, aqm_list1);
aqmf.store(out_file, aqm_list1);
aqmf.load(out_file, aqm_list2);
TEST_EQUAL(aqm_list1.size(), aqm_list2.size())
for (Size i = 0; i < aqm_list1.size(); ++i)
{
TEST_EQUAL(aqm_list1[i] == aqm_list2[i], true)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MZTrafoModel_test.cpp | .cpp | 7,522 | 216 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/PROCESSING/CALIBRATION/MZTrafoModel.h>
///////////////////////////
#include <OpenMS/MATH/MathFunctions.h>
using namespace OpenMS;
using namespace std;
using namespace OpenMS;
using namespace std;
START_TEST(MZTrafoModel, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MZTrafoModel* ptr = nullptr;
MZTrafoModel* null_ptr = nullptr;
START_SECTION(MZTrafoModel())
ptr = new MZTrafoModel();
TEST_NOT_EQUAL(ptr, null_ptr)
END_SECTION
START_SECTION(~MZTrafoModel())
delete ptr;
END_SECTION
CalibrationData cd;
for (Size i = 0; i < 10; ++i)
{
cd.insertCalibrationPoint(100.100 + i, 200.200 + i, 128.5 + i, 200.0 + i, 1, 66);
cd.insertCalibrationPoint(120.100 + i + 0.5, 400.200 + i, 128.5 + i, 200.0 + i, 1, 77);
}
START_SECTION(MZTrafoModel(bool ppm_model))
NOT_TESTABLE // see predict()
END_SECTION
START_SECTION(static const std::string names_of_modeltype[])
END_SECTION
START_SECTION(static MODELTYPE nameToEnum(const std::string& name))
//"linear", "linear_weighted", "quadratic", "quadratic_weighted", "size_of_modeltype"
TEST_EQUAL(MZTrafoModel::nameToEnum("linear"), MZTrafoModel::MODELTYPE::LINEAR)
TEST_EQUAL(MZTrafoModel::nameToEnum("linear_weighted"), MZTrafoModel::MODELTYPE::LINEAR_WEIGHTED)
TEST_EQUAL(MZTrafoModel::nameToEnum("quadratic"), MZTrafoModel::MODELTYPE::QUADRATIC)
TEST_EQUAL(MZTrafoModel::nameToEnum("quadratic_weighted"), MZTrafoModel::MODELTYPE::QUADRATIC_WEIGHTED)
TEST_EQUAL(MZTrafoModel::nameToEnum("size_of_modeltype"), MZTrafoModel::MODELTYPE::SIZE_OF_MODELTYPE)
TEST_EQUAL(MZTrafoModel::nameToEnum("something_different_______"), MZTrafoModel::MODELTYPE::SIZE_OF_MODELTYPE)
END_SECTION
START_SECTION(static const std::string& enumToName(MODELTYPE mt))
TEST_EQUAL(MZTrafoModel::enumToName(MZTrafoModel::MODELTYPE::LINEAR), "linear")
TEST_EQUAL(MZTrafoModel::enumToName(MZTrafoModel::MODELTYPE::LINEAR_WEIGHTED), "linear_weighted")
TEST_EQUAL(MZTrafoModel::enumToName(MZTrafoModel::MODELTYPE::QUADRATIC), "quadratic")
TEST_EQUAL(MZTrafoModel::enumToName(MZTrafoModel::MODELTYPE::QUADRATIC_WEIGHTED), "quadratic_weighted")
TEST_EQUAL(MZTrafoModel::enumToName(MZTrafoModel::MODELTYPE::SIZE_OF_MODELTYPE), "size_of_modeltype")
END_SECTION
START_SECTION(static void setRANSACParams(const Math::RANSACParam& p))
Math::RANSACParam p(10, 1000, 2.0, 25, false);
MZTrafoModel::setRANSACParams(p);
END_SECTION
START_SECTION(static void setCoefficientLimits(double offset, double scale, double power))
MZTrafoModel m;
m.setCoefficientLimits(30, 4, 2);
m.setCoefficients(25, 3, 1);
TEST_EQUAL(MZTrafoModel::isValidModel(m), true)
TEST_EQUAL(m.isTrained(), true)
m.setCoefficients(-25, -3, -1);
TEST_EQUAL(MZTrafoModel::isValidModel(m), true)
TEST_EQUAL(m.isTrained(), true)
m.setCoefficients(33, 3, 1);
TEST_EQUAL(MZTrafoModel::isValidModel(m), false)
TEST_EQUAL(m.isTrained(), true)
m.setCoefficients(25, 5, 1);
TEST_EQUAL(MZTrafoModel::isValidModel(m), false)
TEST_EQUAL(m.isTrained(), true)
m.setCoefficients(25, 3, 3);
TEST_EQUAL(MZTrafoModel::isValidModel(m), false)
TEST_EQUAL(m.isTrained(), true)
END_SECTION
START_SECTION(static bool isValidModel(const MZTrafoModel& trafo))
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(bool isTrained() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(double getRT() const)
NOT_TESTABLE // tested below
END_SECTION
START_SECTION(double predict(double mz) const)
MZTrafoModel m(true);
m.setCoefficients(25, 0, 0);
double mz_theo = 100.0;
double mz_obs = mz_theo + Math::ppmToMass(25.0, mz_theo);
TEST_REAL_SIMILAR(m.predict(mz_obs), mz_theo);
MZTrafoModel m2(false);
m2.setCoefficients(0.25, 0, 0);
mz_theo = 100.0;
mz_obs = mz_theo + 0.25;
TEST_REAL_SIMILAR(m2.predict(mz_obs), mz_theo);
END_SECTION
START_SECTION(static Size findNearest(const std::vector<MZTrafoModel>& tms, double rt))
std::vector<MZTrafoModel> tms;
MZTrafoModel m;
// unsorted RT
m.train(cd, MZTrafoModel::MODELTYPE::LINEAR, false, 100.0, 104.0); // RT = 102
tms.push_back(m);
m.train(cd, MZTrafoModel::MODELTYPE::LINEAR, false, 110.0, 114.0); // RT = 112
tms.push_back(m);
m.train(cd, MZTrafoModel::MODELTYPE::LINEAR, false, 106.0, 108.0); // RT = 107
tms.push_back(m);
m.train(cd, MZTrafoModel::MODELTYPE::LINEAR, false, 126.0, 128.0); // RT = 127
tms.push_back(m);
std::sort(tms.begin(), tms.end(), MZTrafoModel::RTLess());
TEST_REAL_SIMILAR(tms[0].getRT(), 102.0)
TEST_REAL_SIMILAR(tms[1].getRT(), 107.0)
TEST_REAL_SIMILAR(tms[2].getRT(), 112.0)
TEST_REAL_SIMILAR(tms[3].getRT(), 127.0)
TEST_EQUAL(MZTrafoModel::findNearest(tms, 0.0), 0)
TEST_EQUAL(MZTrafoModel::findNearest(tms, 100.0), 0)
TEST_EQUAL(MZTrafoModel::findNearest(tms, 105.0), 1)
TEST_EQUAL(MZTrafoModel::findNearest(tms, 140.0), 3)
END_SECTION
START_SECTION(bool train(const CalibrationData& cd, MODELTYPE md, bool use_RANSAC, double rt_left = -std::numeric_limits<double>::max(), double rt_right = std::numeric_limits<double>::max()))
MZTrafoModel m;
m.train(cd, MZTrafoModel::MODELTYPE::LINEAR, false);
std::cout << m.toString() << std::endl;
TEST_REAL_SIMILAR(m.getRT(), 0.0);
END_SECTION
START_SECTION(bool train(std::vector<double> error_mz, std::vector<double> theo_mz, std::vector<double> weights, MODELTYPE md, bool use_RANSAC))
MZTrafoModel m;
std::vector<double> error_mz = ListUtils::create<double>("10,11,9,10,9,11");
std::vector<double> theo_mz = ListUtils::create<double>("100,200,300,400,500,600");
std::vector<double> weights;
Math::RANSACParam p(3, 1000, 4.0, 1, false);
MZTrafoModel::setRANSACParams(p);
m.train(error_mz, theo_mz, weights, MZTrafoModel::MODELTYPE::LINEAR, true);
std::cout << m.toString() << std::endl;
TEST_REAL_SIMILAR(m.predict(300.0 + Math::ppmToMass(10.0, 300.0)), 300.0);
double a,b,c;
m.getCoefficients(a,b,c);
TEST_REAL_SIMILAR(a, 10.0)
TEST_REAL_SIMILAR(b, 0.0)
TEST_REAL_SIMILAR(c, 0.0)
MZTrafoModel m2;
m2.setCoefficients(m);
m2.getCoefficients(a,b,c);
TEST_REAL_SIMILAR(a, 10.0)
TEST_REAL_SIMILAR(b, 0.0)
TEST_REAL_SIMILAR(c, 0.0)
m2.setCoefficients(1.0, 2.0, 3.0);
m2.getCoefficients(a,b,c);
TEST_REAL_SIMILAR(a, 1.0)
TEST_REAL_SIMILAR(b, 2.0)
TEST_REAL_SIMILAR(c, 3.0)
END_SECTION
START_SECTION(void getCoefficients(double& intercept, double& slope, double& power))
MZTrafoModel m;
double a,b,c;
TEST_EXCEPTION(Exception::Precondition, m.getCoefficients(a,b,c))
// more tests see above
END_SECTION
START_SECTION(void setCoefficients(const MZTrafoModel& rhs))
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setCoefficients(double intercept, double slope, double power))
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(String toString() const)
NOT_TESTABLE // tested above
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MetaInfoDescription_test.cpp | .cpp | 3,352 | 115 | // 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/MetaInfoDescription.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MetaInfoDescription, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MetaInfoDescription* ptr = nullptr;
MetaInfoDescription* nullPointer = nullptr;
START_SECTION((MetaInfoDescription()))
ptr = new MetaInfoDescription();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~MetaInfoDescription()))
delete ptr;
END_SECTION
START_SECTION((const String& getName() const))
MetaInfoDescription tmp;
TEST_EQUAL(tmp.getName(),"");
END_SECTION
START_SECTION((void setName(const String& name)))
MetaInfoDescription tmp;
tmp.setName("name");
TEST_EQUAL(tmp.getName(),"name");
END_SECTION
START_SECTION((const std::vector<DataProcessing>& getDataProcessing() const))
MetaInfoDescription tmp;
TEST_EQUAL(tmp.getDataProcessing().size(),0);
END_SECTION
START_SECTION((void setDataProcessing(const std::vector< DataProcessing > &data_processing)))
MetaInfoDescription tmp;
std::vector<DataProcessingPtr> dummy;
dummy.resize(1);
tmp.setDataProcessing(dummy);
TEST_EQUAL(tmp.getDataProcessing().size(),1);
END_SECTION
START_SECTION((std::vector<DataProcessing>& getDataProcessing()))
MetaInfoDescription tmp;
tmp.getDataProcessing().resize(1);
TEST_EQUAL(tmp.getDataProcessing().size(),1);
END_SECTION
START_SECTION((MetaInfoDescription(const MetaInfoDescription& source)))
MetaInfoDescription tmp;
tmp.setName("bla2");
tmp.getDataProcessing().resize(1);
tmp.setMetaValue("label",String("label"));
MetaInfoDescription tmp2(tmp);
TEST_EQUAL(tmp2.getName(),"bla2");
TEST_EQUAL(tmp.getDataProcessing().size(),1);
TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label");
END_SECTION
START_SECTION((MetaInfoDescription& operator= (const MetaInfoDescription& source)))
MetaInfoDescription tmp;
tmp.setName("bla2");
tmp.getDataProcessing().resize(1);
tmp.setMetaValue("label",String("label"));
MetaInfoDescription tmp2;
tmp2 = tmp;
TEST_EQUAL(tmp2.getName(),"bla2");
TEST_EQUAL(tmp.getDataProcessing().size(),1);
TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label");
tmp2 = MetaInfoDescription();
TEST_EQUAL(tmp2.getName(),"");
TEST_EQUAL(tmp2.getDataProcessing().size(),0);
TEST_EQUAL(tmp2.getMetaValue("label").isEmpty(), true);
END_SECTION
START_SECTION((bool operator== (const MetaInfoDescription& rhs) const))
MetaInfoDescription edit, empty;
TEST_TRUE(edit == empty);
edit = empty;
edit.setName("bla2");
TEST_EQUAL(edit==empty, false);
edit = empty;
edit.setMetaValue("label",String("label"));
TEST_EQUAL(edit==empty, false);
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IncludeExcludeTarget_test.cpp | .cpp | 6,256 | 312 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: $
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
///////////////////////////
#include <OpenMS/ANALYSIS/TARGETED/IncludeExcludeTarget.h>
///////////////////////////
#include <unordered_set>
#include <unordered_map>
using namespace OpenMS;
using namespace std;
START_TEST(IncludeExcludeTarget, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IncludeExcludeTarget* ptr = nullptr;
IncludeExcludeTarget* null_ptr = nullptr;
START_SECTION(IncludeExcludeTarget())
{
ptr = new IncludeExcludeTarget();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IncludeExcludeTarget())
{
delete ptr;
}
END_SECTION
START_SECTION((IncludeExcludeTarget(const IncludeExcludeTarget &rhs)))
{
// TODO
}
END_SECTION
START_SECTION((virtual ~IncludeExcludeTarget()))
{
// TODO
}
END_SECTION
START_SECTION((void setName(const String &name)))
{
// TODO
}
END_SECTION
START_SECTION((const String& getName() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setPeptideRef(const String &peptide_ref)))
{
// TODO
}
END_SECTION
START_SECTION((const String& getPeptideRef() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setCompoundRef(const String &compound_ref)))
{
// TODO
}
END_SECTION
START_SECTION((const String& getCompoundRef() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setPrecursorMZ(double mz)))
{
// TODO
}
END_SECTION
START_SECTION((double getPrecursorMZ() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setPrecursorCVTermList(const CVTermList &list)))
{
// TODO
}
END_SECTION
START_SECTION((void addPrecursorCVTerm(const CVTerm &cv_term)))
{
// TODO
}
END_SECTION
START_SECTION((const CVTermList& getPrecursorCVTermList() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setProductMZ(double mz)))
{
// TODO
}
END_SECTION
START_SECTION((double getProductMZ() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setProductCVTermList(const CVTermList &list)))
{
// TODO
}
END_SECTION
START_SECTION((void addProductCVTerm(const CVTerm &cv_term)))
{
// TODO
}
END_SECTION
START_SECTION((const CVTermList& getProductCVTermList() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setInterpretations(const std::vector< CVTermList > &interpretations)))
{
// TODO
}
END_SECTION
START_SECTION((const std::vector<CVTermList>& getInterpretations() const ))
{
// TODO
}
END_SECTION
START_SECTION((void addInterpretation(const CVTermList &interpretation)))
{
// TODO
}
END_SECTION
START_SECTION((void setConfigurations(const std::vector< Configuration > &configuration)))
{
// TODO
}
END_SECTION
START_SECTION((const std::vector<Configuration>& getConfigurations() const ))
{
// TODO
}
END_SECTION
START_SECTION((void addConfiguration(const Configuration &configuration)))
{
// TODO
}
END_SECTION
START_SECTION((void setPrediction(const CVTermList &prediction)))
{
// TODO
}
END_SECTION
START_SECTION((void addPredictionTerm(const CVTerm &prediction)))
{
// TODO
}
END_SECTION
START_SECTION((const CVTermList& getPrediction() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setRetentionTime(RetentionTime rt)))
{
// TODO
}
END_SECTION
START_SECTION((const RetentionTime& getRetentionTime() const ))
{
// TODO
}
END_SECTION
START_SECTION((bool operator==(const IncludeExcludeTarget &rhs) const ))
{
// TODO
}
END_SECTION
START_SECTION((bool operator!=(const IncludeExcludeTarget &rhs) const ))
{
// TODO
}
END_SECTION
START_SECTION((IncludeExcludeTarget& operator=(const IncludeExcludeTarget &rhs)))
{
// TODO
}
END_SECTION
START_SECTION(([EXTRA] std::hash<IncludeExcludeTarget>))
{
// Test that equal targets have equal hashes
IncludeExcludeTarget t1, t2;
t1.setName("target1");
t1.setPrecursorMZ(500.0);
t1.setProductMZ(200.0);
t1.setPeptideRef("peptide_ref_1");
t1.setCompoundRef("compound_ref_1");
t2.setName("target1");
t2.setPrecursorMZ(500.0);
t2.setProductMZ(200.0);
t2.setPeptideRef("peptide_ref_1");
t2.setCompoundRef("compound_ref_1");
std::hash<IncludeExcludeTarget> hasher;
TEST_EQUAL(hasher(t1), hasher(t2))
// Test that hash changes when values change
IncludeExcludeTarget t3;
t3.setName("target2"); // Different name
t3.setPrecursorMZ(500.0);
t3.setProductMZ(200.0);
t3.setPeptideRef("peptide_ref_1");
t3.setCompoundRef("compound_ref_1");
TEST_NOT_EQUAL(hasher(t1), hasher(t3))
// Test that different precursor_mz produces different hash
IncludeExcludeTarget t4;
t4.setName("target1");
t4.setPrecursorMZ(600.0); // Different precursor_mz
t4.setProductMZ(200.0);
t4.setPeptideRef("peptide_ref_1");
t4.setCompoundRef("compound_ref_1");
TEST_NOT_EQUAL(hasher(t1), hasher(t4))
// Test use in unordered_set
std::unordered_set<IncludeExcludeTarget> target_set;
target_set.insert(t1);
TEST_EQUAL(target_set.size(), 1)
target_set.insert(t2); // same as t1
TEST_EQUAL(target_set.size(), 1) // should not increase
target_set.insert(t3);
TEST_EQUAL(target_set.size(), 2)
// Test use in unordered_map
std::unordered_map<IncludeExcludeTarget, int> target_map;
target_map[t1] = 42;
TEST_EQUAL(target_map[t1], 42)
TEST_EQUAL(target_map[t2], 42) // t2 == t1, should get same value
target_map[t3] = 99;
TEST_EQUAL(target_map[t3], 99)
TEST_EQUAL(target_map.size(), 2)
// Test with retention time set
IncludeExcludeTarget t5, t6;
TargetedExperimentHelper::RetentionTime rt;
rt.setRT(100.0);
t5.setRetentionTime(rt);
t6.setRetentionTime(rt);
TEST_EQUAL(hasher(t5), hasher(t6))
// Test with different retention times
IncludeExcludeTarget t7;
TargetedExperimentHelper::RetentionTime rt2;
rt2.setRT(200.0);
t7.setRetentionTime(rt2);
TEST_NOT_EQUAL(hasher(t5), hasher(t7))
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/FeatureGroupingAlgorithmQT_test.cpp | .cpp | 1,547 | 53 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmQT.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(FeatureGroupingAlgorithmQT, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
FeatureGroupingAlgorithmQT* ptr = nullptr;
FeatureGroupingAlgorithmQT* nullPointer = nullptr;
START_SECTION((FeatureGroupingAlgorithmQT()))
ptr = new FeatureGroupingAlgorithmQT();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~FeatureGroupingAlgorithmQT()))
delete ptr;
END_SECTION
START_SECTION((virtual void group(const std::vector< FeatureMap >& maps, ConsensusMap& out)))
// This is tested extensively in TEST/TOPP
NOT_TESTABLE;
END_SECTION
START_SECTION((virtual void group(const std::vector<ConsensusMap>& maps, ConsensusMap& out)))
// This is tested extensively in TEST/TOPP
NOT_TESTABLE;
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/CompressedInputSource_test.cpp | .cpp | 2,309 | 68 | // 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/CompressedInputSource.h>
#include <OpenMS/FORMAT/GzipInputStream.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
using namespace OpenMS;
///////////////////////////
START_TEST(CompressedInputSource, "$Id$")
xercesc::XMLPlatformUtils::Initialize();
CompressedInputSource* ptr = nullptr;
CompressedInputSource* nullPointer = nullptr;
START_SECTION(CompressedInputSource(const String& file_path, const char * header, xercesc::MemoryManager* const manager = xercesc::XMLPlatformUtils::fgMemoryManager))
char header[3];
header[0] = 'B';
header[1] = 'Z';
header[2] = '\0';
String bz = String(header);
ptr = new CompressedInputSource(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2"), bz);
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~CompressedInputSource()))
delete ptr;
END_SECTION
START_SECTION(CompressedInputSource(const XMLCh *const file_path, const char *header, xercesc::MemoryManager *const manager=xercesc::XMLPlatformUtils::fgMemoryManager))
char header[3];
header[0] = 'B';
header[1] = 'Z';
header[2] = '\0';
String bz = String(header);
String filename(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2"));
ptr = new CompressedInputSource(Internal::StringManager().convert(filename.c_str()).c_str(), bz);
TEST_NOT_EQUAL(ptr, nullPointer)
delete ptr;
END_SECTION
START_SECTION(virtual xercesc::BinInputStream* makeStream() const)
char header[3];
header[0] = 'B';
header[1] = 'Z';
header[2] = '\0';
String bz = String(header);
CompressedInputSource source(OPENMS_GET_TEST_DATA_PATH("ThisFileDoesNotExist"), bz);
TEST_EXCEPTION(Exception::FileNotFound,source.makeStream())
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/OPXLDataStructs_test.cpp | .cpp | 6,664 | 194 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Eugen Netz $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/XLMS/OPXLDataStructs.h>
#include <unordered_set>
#include <unordered_map>
//#include <OpenMS/KERNEL/MSSpectrum.h>
//#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGeneratorXLMS.h>
using namespace OpenMS;
START_TEST(OPXLDataStructs, "$Id$")
OPXLDataStructs::ProteinProteinCrossLink cross_link;
AASequence alpha = AASequence::fromString("PEPTIDE");
AASequence beta = AASequence::fromString("EDEPITPEPE");
cross_link.alpha = α
cross_link.beta = β
cross_link.cross_link_position = std::make_pair<SignedSize, SignedSize>(3, 5);
cross_link.cross_linker_mass = 150.0;
cross_link.cross_linker_name = "NOTDSS";
cross_link.term_spec_alpha = ResidueModification::N_TERM;
cross_link.term_spec_beta = ResidueModification::ANYWHERE;
START_SECTION(ProteinProteinCrossLink())
TEST_EQUAL(cross_link.getType(), OPXLDataStructs::CROSS)
cross_link.beta = nullptr;
TEST_EQUAL(cross_link.getType(), OPXLDataStructs::LOOP)
cross_link.cross_link_position = std::make_pair<SignedSize, SignedSize>(3, -1);
TEST_EQUAL(cross_link.getType(), OPXLDataStructs::MONO)
END_SECTION
START_SECTION(XLPrecursor())
std::vector<OPXLDataStructs::XLPrecursor> precursors;
for (Size i = 20; i > 1; --i)
{
OPXLDataStructs::XLPrecursor prec;
prec.precursor_mass = i * 3.33;
prec.alpha_index = 1;
prec.beta_index = 2;
precursors.push_back(prec);
}
// sorting using the XLPrecursorComparator
std::sort(precursors.begin(), precursors.end(), OPXLDataStructs::XLPrecursorComparator());
for (Size i = 0; i < precursors.size()-1; ++i)
{
TEST_EQUAL(precursors[i].precursor_mass < precursors[i+1].precursor_mass, true)
}
// searching for a precursor mass using a double value
std::vector< OPXLDataStructs::XLPrecursor >::const_iterator low_it;
low_it = lower_bound(precursors.begin(), precursors.end(), 9 * 3.33 - 1, OPXLDataStructs::XLPrecursorComparator());
TEST_REAL_SIMILAR((*low_it).precursor_mass, 9 * 3.33)
END_SECTION
START_SECTION(AASeqWithMass())
std::vector<OPXLDataStructs::AASeqWithMass> peptides;
OPXLDataStructs::AASeqWithMass pep;
pep.position = OPXLDataStructs::INTERNAL;
pep.peptide_seq = AASequence::fromString("TESTEE");
pep.peptide_mass = pep.peptide_seq.getMonoWeight();
peptides.push_back(pep);
pep.peptide_seq = AASequence::fromString("TESTEEE");
pep.peptide_mass = pep.peptide_seq.getMonoWeight();
peptides.push_back(pep);
pep.peptide_seq = AASequence::fromString("TESTEEEEEEEEEEEE");
pep.peptide_mass = pep.peptide_seq.getMonoWeight();
peptides.push_back(pep);
pep.peptide_seq = AASequence::fromString("TESTEEEEE");
pep.peptide_mass = pep.peptide_seq.getMonoWeight();
peptides.push_back(pep);
pep.peptide_seq = AASequence::fromString("TES");
pep.peptide_mass = pep.peptide_seq.getMonoWeight();
peptides.push_back(pep);
// sorting using the AASeqWithMassComparator
std::sort(peptides.begin(), peptides.end(), OPXLDataStructs::AASeqWithMassComparator());
for (Size i = 0; i < peptides.size()-1; ++i)
{
TEST_EQUAL(peptides[i].peptide_mass < peptides[i+1].peptide_mass, true)
}
// searching for a peptide mass using a double value
std::vector< OPXLDataStructs::AASeqWithMass >::const_iterator low_it;
low_it = lower_bound(peptides.begin(), peptides.end(), AASequence::fromString("TESTEEE").getMonoWeight() - 0.1, OPXLDataStructs::AASeqWithMassComparator());
TEST_REAL_SIMILAR((*low_it).peptide_mass, AASequence::fromString("TESTEEE").getMonoWeight())
END_SECTION
START_SECTION(([EXTRA] std::hash<ProteinProteinCrossLink>))
{
// Create test sequences
AASequence alpha1 = AASequence::fromString("PEPTIDE");
AASequence beta1 = AASequence::fromString("EDEPITPEPE");
AASequence alpha2 = AASequence::fromString("DIFFERENT");
AASequence beta2 = AASequence::fromString("SEQUENCE");
// Create first cross-link
OPXLDataStructs::ProteinProteinCrossLink link1;
link1.alpha = &alpha1;
link1.beta = &beta1;
link1.cross_link_position = {3, 5};
link1.cross_linker_mass = 150.0;
link1.cross_linker_name = "DSS";
link1.term_spec_alpha = ResidueModification::ANYWHERE;
link1.term_spec_beta = ResidueModification::ANYWHERE;
link1.precursor_correction = 0;
// Create identical cross-link
OPXLDataStructs::ProteinProteinCrossLink link2;
link2.alpha = &alpha1;
link2.beta = &beta1;
link2.cross_link_position = {3, 5};
link2.cross_linker_mass = 150.0;
link2.cross_linker_name = "DSS";
link2.term_spec_alpha = ResidueModification::ANYWHERE;
link2.term_spec_beta = ResidueModification::ANYWHERE;
link2.precursor_correction = 0;
// Create different cross-link
OPXLDataStructs::ProteinProteinCrossLink link3;
link3.alpha = &alpha2;
link3.beta = &beta2;
link3.cross_link_position = {1, 2};
link3.cross_linker_mass = 200.0;
link3.cross_linker_name = "BS3";
link3.term_spec_alpha = ResidueModification::N_TERM;
link3.term_spec_beta = ResidueModification::C_TERM;
link3.precursor_correction = 1;
std::hash<OPXLDataStructs::ProteinProteinCrossLink> hasher;
// Test: Equal objects must have equal hashes
TEST_EQUAL(link1 == link2, true)
TEST_EQUAL(hasher(link1), hasher(link2))
// Test: Hash is consistent for same object
TEST_EQUAL(hasher(link1), hasher(link1))
// Test: Different objects should (likely) have different hashes
TEST_EQUAL(link1 == link3, false)
TEST_NOT_EQUAL(hasher(link1), hasher(link3))
// Test: Use in unordered_set
std::unordered_set<OPXLDataStructs::ProteinProteinCrossLink> link_set;
link_set.insert(link1);
TEST_EQUAL(link_set.size(), 1)
link_set.insert(link2); // Equal to link1, should not increase size
TEST_EQUAL(link_set.size(), 1)
link_set.insert(link3); // Different, should increase size
TEST_EQUAL(link_set.size(), 2)
TEST_EQUAL(link_set.count(link1), 1)
TEST_EQUAL(link_set.count(link3), 1)
// Test: Use in unordered_map
std::unordered_map<OPXLDataStructs::ProteinProteinCrossLink, int> link_map;
link_map[link1] = 42;
TEST_EQUAL(link_map[link1], 42)
TEST_EQUAL(link_map[link2], 42) // link2 equals link1
link_map[link3] = 100;
TEST_EQUAL(link_map[link3], 100)
TEST_EQUAL(link_map.size(), 2)
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Ms2SpectrumStats_test.cpp | .cpp | 7,068 | 213 | // 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, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/DataProcessing.h>
#include <OpenMS/QC/Ms2SpectrumStats.h>
///////////////////////////
START_TEST(Ms2SpectrumStats, "$Id$");
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
Ms2SpectrumStats* ptr = nullptr;
Ms2SpectrumStats* nullPointer = nullptr;
START_SECTION(Ms2SpectrumStats())
{
ptr = new Ms2SpectrumStats;
TEST_NOT_EQUAL(ptr, nullPointer);
}
END_SECTION
START_SECTION(~Ms2SpectrumStats())
{
delete ptr;
}
END_SECTION
Ms2SpectrumStats top;
START_SECTION(const String& getName() const override) {TEST_EQUAL(top.getName(), "Ms2SpectrumStats")} END_SECTION
START_SECTION(QCBase::Status requirements() const override)
{
TEST_EQUAL(top.requirements() == (QCBase::Status() | QCBase::Requires::RAWMZML | QCBase::Requires::POSTFDRFEAT), true);
}
END_SECTION
START_SECTION(compute(const MSExperiment& exp, FeatureMap& features, const QCBase::SpectraMap& map_to_spectrum))
{
// Valid FeatureMap
FeatureMap fmap;
PeptideIdentification peptide_ID;
PeptideIdentificationList identifications;
PeptideIdentificationList unassignedIDs;
Feature f1;
peptide_ID.setSpectrumReference( "XTandem::0");
identifications.push_back(peptide_ID);
peptide_ID.setSpectrumReference( "XTandem::1");
identifications.push_back(peptide_ID);
f1.setPeptideIdentifications(identifications);
identifications.clear();
fmap.push_back(f1);
peptide_ID.setSpectrumReference( "XTandem::10");
identifications.push_back(peptide_ID);
peptide_ID.setSpectrumReference( "XTandem::12");
identifications.push_back(peptide_ID);
f1.setPeptideIdentifications(identifications);
fmap.push_back(f1);
// unassigned PeptideHits
peptide_ID.setSpectrumReference( "XTandem::1.5");
unassignedIDs.push_back(peptide_ID);
peptide_ID.setSpectrumReference( "XTandem::2.5");
unassignedIDs.push_back(peptide_ID);
fmap.setUnassignedPeptideIdentifications(unassignedIDs);
// MSExperiment
PeakMap exp;
MSSpectrum spec;
Peak1D p;
Precursor pre;
pre.setMZ(5.5);
std::vector<MSSpectrum> spectra;
spec.setPrecursors({pre});
spec.setMSLevel(2);
spec.setRT(0);
spec.setNativeID("XTandem::0");
p.setIntensity(2);
spec.push_back(p);
p.setIntensity(1);
spec.push_back(p);
spectra.push_back(spec);
spec.clear(false);
spec.setMSLevel(1);
spec.setRT(0.5);
spec.setNativeID("XTandem::0.5");
spectra.push_back(spec);
spec.clear(false);
spec.setMSLevel(2);
spec.setRT(1);
spec.setNativeID("XTandem::1");
p.setIntensity(4);
spec.push_back(p);
p.setIntensity(2);
spec.push_back(p);
spectra.push_back(spec);
spec.clear(false);
spec.setRT(1.5);
spec.setNativeID("XTandem::1.5");
spectra.push_back(spec);
spec.setRT(2.5);
spec.setNativeID("XTandem::2.5");
spectra.push_back(spec);
spec.setMSLevel(1);
spec.setRT(9);
spec.setNativeID("XTandem::9");
spectra.push_back(spec);
spec.setMSLevel(2);
spec.setRT(10);
spec.setNativeID("XTandem::10");
p.setIntensity(3);
spec.push_back(p);
p.setIntensity(6);
spec.push_back(p);
spectra.push_back(spec);
spec.clear(false);
spec.setRT(12);
spec.setNativeID("XTandem::12");
p.setIntensity(1);
spec.push_back(p);
p.setIntensity(9);
spec.push_back(p);
spectra.push_back(spec);
spec.clear(false);
// not identified
spec.setRT(20);
spec.setNativeID("XTandem::20");
p.setIntensity(5);
spec.push_back(p);
p.setIntensity(7);
spec.push_back(p);
spectra.push_back(spec);
exp.setSpectra(spectra);
QCBase::SpectraMap map_to_spectrum(exp);
Ms2SpectrumStats top;
PeptideIdentificationList new_unassigned_pep_ids;
new_unassigned_pep_ids = top.compute(exp, fmap, map_to_spectrum);
// test features
TEST_EQUAL(fmap[0].getPeptideIdentifications()[0].getMetaValue("ScanEventNumber"), 1);
TEST_EQUAL(fmap[0].getPeptideIdentifications()[0].getMetaValue("identified"), 1);
TEST_EQUAL(fmap[0].getPeptideIdentifications()[1].getMetaValue("ScanEventNumber"), 1);
TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[1].getMetaValue("total_ion_count"), 6);
TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[1].getMetaValue("base_peak_intensity"), 4);
TEST_EQUAL(fmap[1].getPeptideIdentifications()[0].getMetaValue("ScanEventNumber"), 1);
TEST_REAL_SIMILAR(fmap[1].getPeptideIdentifications()[1].getMetaValue("total_ion_count"), 10);
TEST_REAL_SIMILAR(fmap[1].getPeptideIdentifications()[1].getMetaValue("base_peak_intensity"), 9);
TEST_EQUAL(fmap[1].getPeptideIdentifications()[1].getMetaValue("ScanEventNumber"), 2);
// test unassigned
TEST_EQUAL(fmap.getUnassignedPeptideIdentifications()[0].getMetaValue("ScanEventNumber"), 2);
TEST_EQUAL(fmap.getUnassignedPeptideIdentifications()[0].getMetaValue("identified"), 1);
TEST_EQUAL(fmap.getUnassignedPeptideIdentifications()[1].getMetaValue("ScanEventNumber"), 3);
TEST_REAL_SIMILAR(new_unassigned_pep_ids[0].getRT(), 20);
TEST_EQUAL(new_unassigned_pep_ids[0].getMetaValue("ScanEventNumber"), 3);
TEST_EQUAL(new_unassigned_pep_ids[0].getMetaValue("identified"), 0);
TEST_REAL_SIMILAR(new_unassigned_pep_ids[0].getMetaValue("total_ion_count"), 12);
TEST_REAL_SIMILAR(new_unassigned_pep_ids[0].getMetaValue("base_peak_intensity"), 7);
TEST_REAL_SIMILAR(new_unassigned_pep_ids[0].getMZ(), 5.5);
// empty FeatureMap
FeatureMap fmap_empty {};
new_unassigned_pep_ids = top.compute(exp, fmap_empty, map_to_spectrum);
TEST_EQUAL(new_unassigned_pep_ids.size(), 7);
// empty PeptideIdentifications
fmap_empty.clear();
fmap_empty.push_back(f1); // need some non-empty feature
fmap_empty.setUnassignedPeptideIdentifications({});
new_unassigned_pep_ids = top.compute(exp, fmap_empty, map_to_spectrum);
TEST_EQUAL(new_unassigned_pep_ids.size(), 5);
// empty MSExperiment
PeakMap exp_empty {};
TEST_EXCEPTION(Exception::MissingInformation, top.compute(exp_empty, fmap, map_to_spectrum));
// test exception PepID without 'spectrum_reference'
PeptideIdentification pep_no_spec_ref;
fmap[1].setPeptideIdentifications({pep_no_spec_ref});
TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidParameter, top.compute(exp, fmap, map_to_spectrum), "No spectrum reference annotated at peptide identification!");
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/PercolatorFeatureSetHelper_test.cpp | .cpp | 10,099 | 235 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: MATHIAS WALZER$
// $Authors: MATHIAS WALZER$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
///////////////////////////
#include <OpenMS/ANALYSIS/ID/PercolatorFeatureSetHelper.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
bool check_pepids(const PeptideIdentificationList& check, const PeptideIdentificationList& against)
{
std::vector<String> upk, upkc;
TEST_EQUAL(check.size(), against.size())
if (check.size() != against.size())
return false;
for (size_t i = 0; i < check.size(); ++i)
{
TEST_EQUAL(check[i].getHits().size(), against[i].getHits().size())
for (size_t j = 0; j < check[i].getHits().size(); ++j)
{
check [i].getHits()[j].getKeys(upkc);
against[i].getHits()[j].getKeys(upk);
TEST_EQUAL(upkc.size(), upk.size())
if (upkc.size() != upk.size())
return false;
for (size_t k = 0; k < upk.size(); ++k)
TEST_STRING_EQUAL(upkc[k],upk[k])
}
}
return true;
}
bool check_proids(const vector<ProteinIdentification>& check, const vector<ProteinIdentification>& against, const vector<String>& fs)
{
TEST_EQUAL(check.size(), against.size())
if (check.size()!= against.size())
return false;
for (size_t i = 0; i < check.size(); ++i)
TEST_EQUAL(check[i].getHits().size(), against[i].getHits().size())
String efc = check.front().getSearchParameters().getMetaValue("extra_features");
TEST_STRING_EQUAL(efc, ListUtils::concatenate(fs, ","))
return true;
}
START_TEST(PercolatorFeatureSetHelper, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
STATUS("Preparing test inputs.")
PeptideIdentificationList comet_check_pids;
PeptideIdentificationList msgf_check_pids;
PeptideIdentificationList xtandem_check_pids;
PeptideIdentificationList merge_check_pids;
PeptideIdentificationList concat_check_pids;
std::vector< ProteinIdentification > comet_check_pods;
std::vector< ProteinIdentification > msgf_check_pods;
std::vector< ProteinIdentification > xtandem_check_pods;
std::vector< ProteinIdentification > concat_check_pods;
std::vector< ProteinIdentification > merge_check_pods;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("comet.topperc_check.idXML"), comet_check_pods, comet_check_pids);
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("msgf.topperc_check.idXML"), msgf_check_pods, msgf_check_pids);
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("xtandem.topperc_check.idXML"), xtandem_check_pods, xtandem_check_pids);
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("combined.merge.perco.in.idXML"), merge_check_pods, merge_check_pids);
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("combined.concat.perco.in.idXML"), concat_check_pods, concat_check_pids);
START_SECTION((static void concatMULTISEPeptideIds(std::vector< PeptideIdentification > &all_peptide_ids, std::vector< PeptideIdentification > &new_peptide_ids, String search_engine)))
{
StringList fs;
PeptideIdentificationList comet_pids;
std::vector< ProteinIdentification > comet_pods;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("comet.topperc.idXML"), comet_pods, comet_pids);
PeptideIdentificationList msgf_pids;
std::vector< ProteinIdentification > msgf_pods;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("msgf.topperc.idXML"), msgf_pods, msgf_pids);
StringList ses = ListUtils::create<String>("MS-GF+,Comet");
PeptideIdentificationList concat_pids;
PercolatorFeatureSetHelper::concatMULTISEPeptideIds(concat_pids, msgf_pids, "MS-GF+");
PercolatorFeatureSetHelper::concatMULTISEPeptideIds(concat_pids, comet_pids, "Comet");
PercolatorFeatureSetHelper::addCONCATSEFeatures(concat_pids, ses, fs);
//check completeness of feature construction
ABORT_IF(!check_pepids(concat_check_pids, concat_pids));
}
END_SECTION
START_SECTION((static void mergeMULTISEPeptideIds(std::vector< PeptideIdentification > &all_peptide_ids, std::vector< PeptideIdentification > &new_peptide_ids, String search_engine)))
{
PeptideIdentificationList comet_pids;
std::vector< ProteinIdentification > comet_pods;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("comet.topperc.idXML"), comet_pods, comet_pids);
PeptideIdentificationList msgf_pids;
std::vector< ProteinIdentification > msgf_pods;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("msgf.topperc.idXML"), msgf_pods, msgf_pids);
PeptideIdentificationList merge_pids;
StringList ses = ListUtils::create<String>("MS-GF+,Comet");
PercolatorFeatureSetHelper::mergeMULTISEPeptideIds(merge_pids, msgf_pids, "MS-GF+");
PercolatorFeatureSetHelper::mergeMULTISEPeptideIds(merge_pids, comet_pids, "Comet");
StringList empty_extra;
PercolatorFeatureSetHelper::addMULTISEFeatures(merge_pids, ses, empty_extra, true);
TEST_EQUAL(merge_pids.size(),4)
for (size_t i = merge_pids.size()-1; i > 0; --i)
{
PercolatorFeatureSetHelper::checkExtraFeatures(merge_pids[i].getHits(), empty_extra); // also check against empty extra features list and inconsistency removal
merge_pids.erase(merge_pids.begin()+i); //erase to be able to use completeness check function below
}
TEST_EQUAL(merge_pids.size(),1)
//check completeness of feature construction
ABORT_IF(!check_pepids(merge_check_pids, merge_pids));
}
END_SECTION
START_SECTION((static void mergeMULTISEProteinIds(std::vector< ProteinIdentification > &all_protein_ids, std::vector< ProteinIdentification > &new_protein_ids)))
{
StringList fs;
PeptideIdentificationList comet_pids;
std::vector< ProteinIdentification > comet_pods;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("comet.topperc.idXML"), comet_pods, comet_pids);
PeptideIdentificationList msgf_pids;
std::vector< ProteinIdentification > msgf_pods;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("msgf.topperc.idXML"), msgf_pods, msgf_pids);
std::vector< ProteinIdentification > merge_pods;
PercolatorFeatureSetHelper::mergeMULTISEProteinIds(merge_pods, msgf_pods);
PercolatorFeatureSetHelper::mergeMULTISEProteinIds(merge_pods, comet_pods);
PeptideIdentificationList merge_pids;
StringList ses = ListUtils::create<String>("MS-GF+,Comet");
PercolatorFeatureSetHelper::mergeMULTISEPeptideIds(merge_pids, msgf_pids, "MS-GF+");
PercolatorFeatureSetHelper::mergeMULTISEPeptideIds(merge_pids, comet_pids, "Comet");
PercolatorFeatureSetHelper::addMULTISEFeatures(merge_pids, ses, fs, true);
//check completeness of feature construction
ABORT_IF(!check_proids(merge_check_pods, merge_pods, fs));
}
END_SECTION
START_SECTION((static void addMSGFFeatures(std::vector< PeptideIdentification > &peptide_ids, StringList &feature_set)))
{
StringList fs;
PeptideIdentificationList msgf_pids;
std::vector< ProteinIdentification > msgf_pods;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("msgf.topperc.idXML"), msgf_pods, msgf_pids);
PercolatorFeatureSetHelper::addMSGFFeatures(msgf_pids,fs);
//check completeness of feature construction
ABORT_IF(!check_pepids(msgf_check_pids, msgf_pids));
//check registration of percolator features for adapter
ABORT_IF(!check_proids(msgf_check_pods, msgf_pods, fs));
}
END_SECTION
START_SECTION((static void addXTANDEMFeatures(std::vector< PeptideIdentification > &peptide_ids, StringList &feature_set)))
{
StringList fs;
PeptideIdentificationList xtandem_pids;
std::vector< ProteinIdentification > xtandem_pods;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("xtandem.topperc.idXML"), xtandem_pods, xtandem_pids);
PercolatorFeatureSetHelper::addXTANDEMFeatures(xtandem_pids, fs);
//check completeness of feature construction
ABORT_IF(!check_pepids(xtandem_check_pids, xtandem_pids));
//check registration of percolator features for adapter
ABORT_IF(!check_proids(xtandem_check_pods, xtandem_pods, fs));
}
END_SECTION
START_SECTION((static void addCOMETFeatures(std::vector< PeptideIdentification > &peptide_ids, StringList &feature_set)))
{
StringList fs;
PeptideIdentificationList comet_pids;
std::vector< ProteinIdentification > comet_pods;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("comet.topperc.idXML"), comet_pods, comet_pids);
PercolatorFeatureSetHelper::addCOMETFeatures(comet_pids, fs);
//check completeness of feature construction
ABORT_IF(!check_pepids(comet_check_pids, comet_pids));
//check registration of percolator features for adapter
ABORT_IF(!check_proids(comet_check_pods, comet_pods, fs));
}
END_SECTION
START_SECTION((static void addMASCOTFeatures(std::vector< PeptideIdentification > &peptide_ids, StringList &feature_set)))
{
NOT_TESTABLE // yet
}
END_SECTION
START_SECTION((static void addMULTISEFeatures(std::vector< PeptideIdentification > &peptide_ids, StringList &search_engines_used, StringList &feature_set, bool complete_only=true, bool limits_imputation=false)))
{
NOT_TESTABLE // actually tested in combination with mergeMULTISEPeptideIds
}
END_SECTION
START_SECTION((static void addCONCATSEFeatures(std::vector< PeptideIdentification > &peptide_id_list, StringList &search_engines_used, StringList &feature_set)))
{
NOT_TESTABLE // actually tested in combination with concatMULTISEPeptideIds
}
END_SECTION
START_SECTION((static void checkExtraFeatures(const std::vector< PeptideHit > &psms, StringList &extra_features)))
{
NOT_TESTABLE // actually tested in combination with mergeMULTISEPeptideIds
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MRMTransitionGroup_test.cpp | .cpp | 10,228 | 357 | // 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/TARGETED/TargetedExperiment.h>
#include <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
using namespace OpenMS;
using namespace std;
typedef OpenMS::ReactionMonitoringTransition TransitionType;
typedef MRMTransitionGroup<MSChromatogram, TransitionType> MRMTransitionGroupType;
///////////////////////////
START_TEST(MRMTransitionGroup, "$Id$")
/////////////////////////////////////////////////////////////
MRMTransitionGroupType* ptr = nullptr;
MRMTransitionGroupType* nullPointer = nullptr;
START_SECTION(MRMTransitionGroup())
{
ptr = new MRMTransitionGroupType();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~MRMTransitionGroup())
{
delete ptr;
}
END_SECTION
MSChromatogram chrom1;
MSChromatogram chrom2;
TransitionType trans1;
TransitionType trans2;
MRMFeature feature1;
MRMFeature feature2;
START_SECTION(MRMTransitionGroup(const MRMTransitionGroup &rhs))
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addChromatogram(chrom1, "dummy1");
mrmtrgroup.addChromatogram(chrom2, "dummy2");
MRMTransitionGroupType tmp(mrmtrgroup);
TEST_EQUAL(mrmtrgroup.size(), tmp.size() )
}
END_SECTION
START_SECTION( MRMTransitionGroup& operator=(const MRMTransitionGroup &rhs) )
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addChromatogram(chrom1, "dummy1");
mrmtrgroup.addChromatogram(chrom2, "dummy2");
MRMTransitionGroupType tmp = mrmtrgroup;
TEST_EQUAL(mrmtrgroup.size(), tmp.size() )
}
END_SECTION
START_SECTION (Size size() const)
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addChromatogram(chrom1, "dummy1");
TEST_EQUAL(mrmtrgroup.size(), 1)
mrmtrgroup.addChromatogram(chrom2, "dummy2");
TEST_EQUAL(mrmtrgroup.size(), 2)
}
END_SECTION
START_SECTION ( const String & getTransitionGroupID() const)
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.setTransitionGroupID("some_id");
TEST_EQUAL(mrmtrgroup.getTransitionGroupID(), "some_id")
}
END_SECTION
START_SECTION ( void setTransitionGroupID(const String & tr_gr_id))
{
// tested above
NOT_TESTABLE
}
END_SECTION
START_SECTION ( std::vector<TransitionType>& getTransitionsMuteable())
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addTransition(trans1, "dummy1");
mrmtrgroup.addTransition(trans2, "dummy2");
TEST_EQUAL(mrmtrgroup.getTransitionsMuteable().size(), 2)
}
END_SECTION
START_SECTION ( void addTransition(const TransitionType &transition, String key))
{
// tested above
NOT_TESTABLE
}
END_SECTION
START_SECTION ( const TransitionType& getTransition(String key))
{
MRMTransitionGroupType mrmtrgroup;
trans1.setLibraryIntensity(42);
mrmtrgroup.addTransition(trans1, "dummy1");
TEST_EQUAL(mrmtrgroup.getTransition("dummy1").getLibraryIntensity(), 42)
}
END_SECTION
START_SECTION ( const std::vector<TransitionType>& getTransitions() const )
{
MRMTransitionGroupType mrmtrgroup;
trans1.setLibraryIntensity(42);
mrmtrgroup.addTransition(trans1, "dummy1");
trans2.setLibraryIntensity(-2);
mrmtrgroup.addTransition(trans2, "dummy2");
TEST_EQUAL(mrmtrgroup.getTransitions()[0].getLibraryIntensity(), 42)
TEST_EQUAL(mrmtrgroup.getTransitions()[1].getLibraryIntensity(), -2)
}
END_SECTION
START_SECTION ( bool hasTransition(String key))
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addTransition(trans1, "dummy1");
TEST_EQUAL(mrmtrgroup.hasTransition("dummy1"), true)
TEST_EQUAL(mrmtrgroup.hasTransition("dummy2"), false)
}
END_SECTION
START_SECTION ( const std::vector<SpectrumType>& getChromatograms() const )
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addChromatogram(chrom1, "dummy1");
mrmtrgroup.addChromatogram(chrom2, "dummy2");
TEST_EQUAL(mrmtrgroup.getChromatograms().size(), 2)
}
END_SECTION
START_SECTION ( std::vector<SpectrumType>& getChromatograms())
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addChromatogram(chrom1, "dummy1");
mrmtrgroup.addChromatogram(chrom2, "dummy2");
TEST_EQUAL(mrmtrgroup.getChromatograms().size(), 2)
}
END_SECTION
START_SECTION ( void addChromatogram(SpectrumType &chromatogram, String key))
{
// tested above
NOT_TESTABLE
}
END_SECTION
START_SECTION ( SpectrumType& getChromatogram(String key))
{
MRMTransitionGroupType mrmtrgroup;
chrom1.setMetaValue("some_value", 1);
mrmtrgroup.addChromatogram(chrom1, "dummy1");
TEST_EQUAL(mrmtrgroup.getChromatogram("dummy1").getMetaValue("some_value"), 1)
}
END_SECTION
START_SECTION ( bool hasChromatogram(String key))
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addChromatogram(chrom1, "dummy1");
TEST_EQUAL(mrmtrgroup.hasChromatogram("dummy1"), true)
TEST_EQUAL(mrmtrgroup.hasChromatogram("dummy2"), false)
}
END_SECTION
START_SECTION ( void addPrecusorChromatogram(SpectrumType &chromatogram, String key))
{
// tested below
NOT_TESTABLE
}
END_SECTION
START_SECTION ( SpectrumType& getPrecursorChromatogram(String key))
{
MRMTransitionGroupType mrmtrgroup;
chrom1.setMetaValue("some_value", 1);
mrmtrgroup.addPrecursorChromatogram(chrom1, "dummy1");
TEST_EQUAL(mrmtrgroup.getPrecursorChromatogram("dummy1").getMetaValue("some_value"), 1)
// Add a few feature chromatograms and then add a precursor chromatogram -> it should still work
mrmtrgroup.addChromatogram(chrom1, "feature1");
mrmtrgroup.addChromatogram(chrom1, "feature2");
mrmtrgroup.addChromatogram(chrom1, "feature3");
mrmtrgroup.addPrecursorChromatogram(chrom1, "dummy2");
TEST_EQUAL(mrmtrgroup.getPrecursorChromatogram("dummy2").getMetaValue("some_value"), 1)
}
END_SECTION
START_SECTION ( bool hasPrecursorChromatogram(String key))
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addPrecursorChromatogram(chrom1, "dummy1");
TEST_EQUAL(mrmtrgroup.hasPrecursorChromatogram("dummy1"), true)
TEST_EQUAL(mrmtrgroup.hasPrecursorChromatogram("dummy2"), false)
}
END_SECTION
START_SECTION ( const std::vector<MRMFeature> & getFeatures() const)
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addFeature(feature1);
mrmtrgroup.addFeature(feature2);
TEST_EQUAL(mrmtrgroup.getFeatures().size(), 2)
}
END_SECTION
START_SECTION ( std::vector<MRMFeature> & getFeaturesMuteable())
{
MRMTransitionGroupType mrmtrgroup;
mrmtrgroup.addFeature(feature1);
mrmtrgroup.addFeature(feature2);
TEST_EQUAL(mrmtrgroup.getFeaturesMuteable().size(), 2)
}
END_SECTION
START_SECTION ( void addFeature(MRMFeature & feature))
{
// tested above
NOT_TESTABLE
}
END_SECTION
START_SECTION ( void getLibraryIntensity(std::vector<double> & result) const)
{
TransitionType new_trans1;
TransitionType new_trans2;
MRMTransitionGroupType mrmtrgroup;
new_trans1.setLibraryIntensity(3);
new_trans2.setLibraryIntensity(-2);
mrmtrgroup.addTransition(new_trans1, "dummy1");
mrmtrgroup.addTransition(new_trans2, "dummy2");
std::vector< double > result;
mrmtrgroup.getLibraryIntensity(result);
TEST_EQUAL(result.size(), 2)
TEST_REAL_SIMILAR(result[0], 3)
TEST_REAL_SIMILAR(result[1], 0)
}
END_SECTION
START_SECTION ( MRMTransitionGroup subset(std::vector<std::string> tr_ids))
{
TransitionType new_trans1;
TransitionType new_trans2;
MRMTransitionGroupType mrmtrgroup, mrmtrgroupsub;
new_trans1.setLibraryIntensity(3);
new_trans1.setNativeID("new_trans1");
new_trans1.setMetaValue("detecting_transition","true");
new_trans2.setLibraryIntensity(-2);
new_trans2.setNativeID("new_trans2");
new_trans2.setMetaValue("detecting_transition","false");
mrmtrgroup.addTransition(new_trans1, "new_trans1");
mrmtrgroup.addTransition(new_trans2, "new_trans2");
std::vector< std::string > transition_ids;
transition_ids.push_back("new_trans1");
std::vector< double > result;
mrmtrgroupsub = mrmtrgroup.subset(transition_ids);
mrmtrgroupsub.getLibraryIntensity(result);
TEST_EQUAL(result.size(), 1)
TEST_REAL_SIMILAR(result[0], 3)
}
END_SECTION
START_SECTION ( inline bool isInternallyConsistent() const)
{
MRMTransitionGroupType mrmtrgroup;
TEST_EQUAL(mrmtrgroup.isInternallyConsistent(), true)
}
END_SECTION
START_SECTION (inline bool chromatogramIdsMatch() const)
{
{
MRMTransitionGroupType mrmtrgroup;
Chromatogram c;
c.setNativeID("test");
mrmtrgroup.addChromatogram(c, "test");
TEST_EQUAL(mrmtrgroup.chromatogramIdsMatch(), true)
mrmtrgroup.addChromatogram(c, "test2");
TEST_EQUAL(mrmtrgroup.chromatogramIdsMatch(), false)
}
{
MRMTransitionGroupType mrmtrgroup;
Chromatogram c;
c.setNativeID("test");
mrmtrgroup.addPrecursorChromatogram(c, "test");
TEST_EQUAL(mrmtrgroup.chromatogramIdsMatch(), true)
mrmtrgroup.addPrecursorChromatogram(c, "test2");
TEST_EQUAL(mrmtrgroup.chromatogramIdsMatch(), false)
}
}
END_SECTION
START_SECTION ( MRMTransitionGroup subsetDependent(std::vector<std::string> tr_ids))
{
TransitionType new_trans1;
TransitionType new_trans2;
MRMTransitionGroupType mrmtrgroup, mrmtrgroupsub;
new_trans1.setLibraryIntensity(3);
new_trans1.setNativeID("new_trans1");
new_trans1.setMetaValue("detecting_transition","true");
new_trans2.setLibraryIntensity(-2);
new_trans2.setNativeID("new_trans2");
new_trans2.setMetaValue("detecting_transition","false");
mrmtrgroup.addTransition(new_trans1, "new_trans1");
mrmtrgroup.addTransition(new_trans2, "new_trans2");
std::vector< std::string > transition_ids;
transition_ids.push_back("new_trans1");
transition_ids.push_back("new_trans2");
std::vector< double > result;
mrmtrgroupsub = mrmtrgroup.subset(transition_ids);
mrmtrgroupsub.getLibraryIntensity(result);
TEST_EQUAL(result.size(), 2)
TEST_REAL_SIMILAR(result[0], 3)
TEST_REAL_SIMILAR(result[1], 0)
}
END_SECTION
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Date_test.cpp | .cpp | 3,703 | 153 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/Date.h>
#include <iostream>
#include <vector>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(Date, "$Id$")
/////////////////////////////////////////////////////////////
Date* s_ptr = nullptr;
Date* s_nullPointer= nullptr;
START_SECTION((Date()))
s_ptr = new Date();
TEST_NOT_EQUAL(s_ptr, s_nullPointer)
END_SECTION
START_SECTION(([EXTRA]~Date()))
delete s_ptr;
END_SECTION
START_SECTION(Date(const QDate &date))
QDate qd(1999,12,24);
Date d(qd);
TEST_EQUAL(d.year(),1999)
TEST_EQUAL(d.month(),12)
TEST_EQUAL(d.day(),24)
END_SECTION
START_SECTION((void get(UInt& month, UInt& day, UInt& year) const))
Date date;
UInt d,m,y;
date.set("2007-12-03");
date.get(m,d,y);
TEST_EQUAL(m,12);
TEST_EQUAL(d,3);
TEST_EQUAL(y,2007);
END_SECTION
START_SECTION((void set(UInt month, UInt day, UInt year) ))
Date date;
UInt d,m,y;
date.set(12,1,1977);
date.get(m,d,y);
TEST_EQUAL(m,12);
TEST_EQUAL(d,1);
TEST_EQUAL(y,1977);
//exceptions
TEST_EXCEPTION(Exception::ParseError,date.set(0,12,1977));
TEST_EXCEPTION(Exception::ParseError,date.set(12,0,1977));
TEST_EXCEPTION(Exception::ParseError,date.set(1,32,1977));
TEST_EXCEPTION(Exception::ParseError,date.set(13,1,1977));
TEST_EXCEPTION(Exception::ParseError,date.set(02,29,2100));
END_SECTION
START_SECTION((Date& operator= (const Date& source)))
Date date, date2;
date.set(12,1,1977);
TEST_EQUAL(date==date2,false);
date2 = date;
TEST_EQUAL(date==date2,true);
END_SECTION
START_SECTION((Date(const Date& date)))
Date date;
date.set(12,1,1977);
Date date2(date);
TEST_EQUAL(date==date2,true);
END_SECTION
START_SECTION((void set(const String& date) ))
Date date;
//german
date.set("01.12.1977");
UInt d,m,y;
date.get(m,d,y);
TEST_EQUAL(m,12);
TEST_EQUAL(d,1);
TEST_EQUAL(y,1977);
//english
date.set("12/01/1977");
date.get(m,d,y);
TEST_EQUAL(m,12);
TEST_EQUAL(d,1);
TEST_EQUAL(y,1977);
//iso/ansi
date.set("1967-12-23");
date.get(m,d,y);
TEST_EQUAL(d,23);
TEST_EQUAL(m,12);
TEST_EQUAL(y,1967);
//german short
date.set("06.01.1688");
date.get(m,d,y);
TEST_EQUAL(m,1);
TEST_EQUAL(d,6);
TEST_EQUAL(y,1688);
//exceptions
TEST_EXCEPTION(Exception::ParseError,date.set("bla"));
TEST_EXCEPTION(Exception::ParseError,date.set("01.01.01.2005"));
TEST_EXCEPTION(Exception::ParseError,date.set("f1.01.1977"));
TEST_EXCEPTION(Exception::ParseError,date.set("01.1x.1977"));
TEST_EXCEPTION(Exception::ParseError,date.set("01.12.i135"));
TEST_EXCEPTION(Exception::ParseError,date.set("1135-64-3"));
END_SECTION
START_SECTION((String get() const))
Date d;
TEST_EQUAL(d.get(),"0000-00-00");
d.set("11.12.1977");
TEST_EQUAL(d.get(),"1977-12-11");
d.set("02.01.1999");
TEST_EQUAL(d.get(),"1999-01-02");
END_SECTION
START_SECTION((void clear()))
Date d;
d.set("11.12.1977");
TEST_EQUAL(d.get(),"1977-12-11");
d.clear();
TEST_EQUAL(d.get(),"0000-00-00");
END_SECTION
START_SECTION((static Date today()))
TEST_EQUAL(Date::today().isValid(), true)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/PeakFileOptions_test.cpp | .cpp | 6,863 | 273 | // 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/OPTIONS/PeakFileOptions.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
template<class T>
ostream& operator<<(ostream& os, const vector<T>& vec)
{
if (vec.empty())
{
os << "()";
return os;
}
os << "(";
typename vector<T>::const_iterator i = vec.begin();
while (true)
{
os << *i++;
if (i == vec.end())
break;
os << ",";
}
os << ")";
return os;
}
DRange<1> makeRange(double a, double b)
{
DPosition<1> pa(a), pb(b);
return DRange<1>(pa, pb);
}
START_TEST(PeakFileOptions, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PeakFileOptions* ptr = nullptr;
PeakFileOptions* nullPointer = nullptr;
START_SECTION((PeakFileOptions()))
ptr = new PeakFileOptions();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~PeakFileOptions()))
delete ptr;
END_SECTION
START_SECTION((void setCompression(bool compress)))
PeakFileOptions tmp;
tmp.setCompression(true);
TEST_EQUAL(tmp.getCompression(), true);
END_SECTION
START_SECTION((bool getCompression() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.getCompression(), false);
END_SECTION
START_SECTION((void setMetadataOnly(bool only)))
PeakFileOptions tmp;
tmp.setMetadataOnly(true);
TEST_EQUAL(tmp.getMetadataOnly(), true);
END_SECTION
START_SECTION((bool getMetadataOnly() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.getMetadataOnly(), false);
END_SECTION
START_SECTION((void setWriteSupplementalData(bool write)))
PeakFileOptions tmp;
tmp.setWriteSupplementalData(false);
TEST_EQUAL(tmp.getWriteSupplementalData(), false);
END_SECTION
START_SECTION((bool getWriteSupplementalData() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.getWriteSupplementalData(), true);
END_SECTION
START_SECTION((void setRTRange(const DRange<1>& range)))
PeakFileOptions tmp;
tmp.setRTRange(makeRange(2, 4));
TEST_EQUAL(tmp.hasRTRange(), true);
TEST_EQUAL(tmp.getRTRange(), makeRange(2, 4));
END_SECTION
START_SECTION((bool hasRTRange() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.hasRTRange(), false);
END_SECTION
START_SECTION((const DRange<1>& getRTRange() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.getRTRange(), DRange<1>());
END_SECTION
START_SECTION((void setMZRange(const DRange<1>& range)))
PeakFileOptions tmp;
tmp.setMZRange(makeRange(3, 5));
TEST_EQUAL(tmp.hasMZRange(), true);
TEST_EQUAL(tmp.getMZRange(), makeRange(3, 5));
END_SECTION
START_SECTION((bool hasMZRange() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.hasMZRange(), false);
END_SECTION
START_SECTION((const DRange<1>& getMZRange() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.getMZRange(), DRange<1>());
END_SECTION
START_SECTION((void setIntensityRange(const DRange<1>& range)))
PeakFileOptions tmp;
tmp.setIntensityRange(makeRange(3, 5));
TEST_EQUAL(tmp.hasIntensityRange(), true);
TEST_EQUAL(tmp.getIntensityRange(), makeRange(3, 5));
END_SECTION
START_SECTION((bool hasIntensityRange() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.hasIntensityRange(), false);
END_SECTION
START_SECTION((const DRange<1>& getIntensityRange() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.getIntensityRange(), DRange<1>());
END_SECTION
START_SECTION((void setPrecursorMZRange(const DRange<1>& range)))
PeakFileOptions tmp;
tmp.setPrecursorMZRange(makeRange(400, 1200));
TEST_EQUAL(tmp.hasPrecursorMZRange(), true);
TEST_EQUAL(tmp.getPrecursorMZRange(), makeRange(400, 1200));
END_SECTION
START_SECTION((bool hasPrecursorMZRange() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.hasPrecursorMZRange(), false);
END_SECTION
START_SECTION((const DRange<1>& getPrecursorMZRange() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.getPrecursorMZRange(), DRange<1>());
END_SECTION
START_SECTION((void setMSLevels(const vector<Int>& levels)))
PeakFileOptions tmp;
vector<Int> levels;
levels.push_back(1);
levels.push_back(3);
levels.push_back(5);
tmp.setMSLevels(levels);
TEST_EQUAL(tmp.hasMSLevels(), true);
TEST_EQUAL(tmp.getMSLevels()==levels,true);
END_SECTION
START_SECTION((void addMSLevel(int level)))
PeakFileOptions tmp;
tmp.addMSLevel(1);
tmp.addMSLevel(3);
tmp.addMSLevel(5);
TEST_EQUAL(tmp.hasMSLevels(), true);
TEST_EQUAL(tmp.getMSLevels().size(), 3);
vector<Int> levels;
levels.push_back(1);
levels.push_back(3);
levels.push_back(5);
TEST_EQUAL(tmp.getMSLevels()==levels,true);
END_SECTION
START_SECTION((void clearMSLevels()))
PeakFileOptions tmp;
vector<Int> levels;
levels.push_back(1);
levels.push_back(3);
levels.push_back(5);
tmp.setMSLevels(levels);
TEST_EQUAL(tmp.getMSLevels()==levels,true);
// now clear the ms levels
tmp.clearMSLevels();
TEST_EQUAL(tmp.hasMSLevels(), false);
TEST_EQUAL(tmp.getMSLevels().empty(),true);
END_SECTION
START_SECTION((bool hasMSLevels() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.hasMSLevels(), false);
END_SECTION
START_SECTION((bool containsMSLevel(int level) const))
PeakFileOptions tmp;
vector<Int> levels;
levels.push_back(1);
levels.push_back(3);
levels.push_back(5);
tmp.setMSLevels(levels);
TEST_EQUAL(tmp.containsMSLevel(3), true);
TEST_EQUAL(tmp.containsMSLevel(2), false);
END_SECTION
START_SECTION((const vector<Int>& getMSLevels() const))
PeakFileOptions tmp;
TEST_EQUAL(tmp.getMSLevels().empty(),true);
END_SECTION
START_SECTION(Size getMaxDataPoolSize() const)
{
PeakFileOptions tmp;
TEST_EQUAL(tmp.getMaxDataPoolSize()!=0,true);
}
END_SECTION
START_SECTION(void setMaxDataPoolSize(Size size))
{
PeakFileOptions tmp;
tmp.setMaxDataPoolSize(250);
TEST_EQUAL(tmp.getMaxDataPoolSize()==250,true);
}
END_SECTION
START_SECTION((skipChromatograms))
{
PeakFileOptions opts;
TEST_FALSE(opts.getSkipChromatograms())
opts.setSkipChromatograms(true);
TEST_TRUE(opts.getSkipChromatograms())
}
END_SECTION
START_SECTION((hasFilters))
{
PeakFileOptions opts;
TEST_FALSE(opts.hasFilters())
// test RT range
opts.setRTRange(makeRange(10, 100));
TEST_TRUE(opts.hasFilters())
// reset and test MS levels
PeakFileOptions opts2;
opts2.addMSLevel(2);
TEST_TRUE(opts2.hasFilters())
// reset and test precursor m/z range
PeakFileOptions opts3;
opts3.setPrecursorMZRange(makeRange(400, 1200));
TEST_TRUE(opts3.hasFilters())
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IDMapper_test.cpp | .cpp | 27,477 | 669 | // 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 $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <iostream>
#include <OpenMS/ANALYSIS/ID/IDMapper.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/FORMAT/FeatureXMLFile.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/METADATA/AnnotatedMSRun.h>
///////////////////////////
using namespace OpenMS;
class IDMapper2 : public IDMapper
{
public:
double getAbsoluteMZTolerance2_(const double mz)
{
return getAbsoluteMZTolerance_(mz);
}
bool isMatch2_(const double rt_distance, const double mz_theoretical, const double mz_observed)
{
return isMatch_(rt_distance, mz_theoretical, mz_observed);
}
};
START_TEST(IDMapper, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace std;
IDMapper* ptr = nullptr;
IDMapper* nullPointer = nullptr;
START_SECTION((IDMapper()))
ptr = new IDMapper();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~IDMapper()))
delete ptr;
END_SECTION
START_SECTION((IDMapper(const IDMapper& cp)))
{
IDMapper mapper;
Param p = mapper.getParameters();
p.setValue("rt_tolerance", 0.5);
p.setValue("mz_tolerance", 0.05);
p.setValue("mz_measure","ppm");
mapper.setParameters(p);
IDMapper m2(mapper);
TEST_EQUAL(m2.getParameters(), p);
}
END_SECTION
START_SECTION((IDMapper& operator = (const IDMapper& rhs)))
IDMapper mapper;
Param p = mapper.getParameters();
p.setValue("rt_tolerance", 0.5);
p.setValue("mz_tolerance", 0.05);
p.setValue("mz_measure", "ppm");
mapper.setParameters(p);
IDMapper m2=mapper;
TEST_EQUAL(m2.getParameters(), p);
END_SECTION
/*
START_SECTION((void annotate(AnnotatedMSRun& map, FeatureMap fmap, const bool clear_ids = false, const bool mapMS1 = false)))
// create id
FeatureMap fm;
Feature f;
f.setMZ(900.0);
f.setRT(9.0);
PeptideIdentificationList pids;
PeptideIdentification pid;
pid.setIdentifier("myID");
pid.setHits(std::vector<PeptideHit>(4));
pids.push_back(pid); // without MZ&RT for PID (take feature instead)
pid.setMZ(800.0);
pid.setRT(9.05);
pids.push_back(pid); // with MZ&RT from PID
f.setPeptideIdentifications(pids);
fm.push_back(f);
std::vector<ProteinIdentification> prids(2);
fm.setProteinIdentifications(prids);
// create experiment
AnnotatedMSRun annotated_experiment;
MSExperiment& experiment = annotated_experiment.getMSExperiment();
MSSpectrum spectrum;
Precursor precursor;
precursor.setMZ(0);
spectrum.setRT(8.9);
experiment.addSpectrum(spectrum);
experiment[0].getPrecursors().push_back(precursor);
precursor.setMZ(20);
spectrum.setRT(9.1);
experiment.addSpectrum(spectrum);
experiment[1].getPrecursors().push_back(precursor);
precursor.setMZ(11);
spectrum.setRT(12.0);
experiment.addSpectrum(spectrum);
experiment[2].getPrecursors().push_back(precursor);
// map
IDMapper mapper;
Param p = mapper.getParameters();
p.setValue("rt_tolerance", 0.3);
p.setValue("mz_tolerance", 0.05);
p.setValue("mz_measure", "Da");
p.setValue("ignore_charge", "true");
mapper.setParameters(p);
mapper.annotate(annotated_experiment, fm, true, true);
//test
TEST_EQUAL(annotated_experiment.getProteinIdentifications().size(), 2)
//scan 1
TEST_EQUAL(annotated_experiment.getPeptideIdentifications()[0].getHits().size(), 2)
//scan 2
TEST_EQUAL(annotated_experiment.getPeptideIdentifications()[1].size(), 2)
ABORT_IF(annotated_experiment.getPeptideIdentifications(1).size() != 2)
TEST_EQUAL(annotated_experiment.getPeptideIdentifications(1)[0].getHits().size(), 4)
TEST_EQUAL(annotated_experiment.getPeptideIdentifications(1)[0].getMZ(), 900.0)
TEST_EQUAL(annotated_experiment.getPeptideIdentifications(1)[1].getHits().size(), 4)
TEST_EQUAL(annotated_experiment.getPeptideIdentifications(1)[1].getMZ(), 800.0)
//scan 3
TEST_EQUAL(annotated_experiment.getPeptideIdentifications(2).size(), 0)
std::cout << annotated_experiment.getProteinIdentifications().size() << std::endl;
std::cout << fm.getProteinIdentifications().size() << std::endl;
mapper.annotate(annotated_experiment, fm, true, false); // no MS1 mapping. MZ threshold never fulfilled
std::cout << annotated_experiment.getProteinIdentifications().size() << std::endl;
//test
TEST_EQUAL(annotated_experiment.getProteinIdentifications().size(), 2)
//scan 1
TEST_EQUAL(annotated_experiment.getPeptideIdentifications(0).size(), 0)
//scan 2
TEST_EQUAL(annotated_experiment.getPeptideIdentifications(1).size(), 0)
//scan 3
TEST_EQUAL(annotated_experiment.getPeptideIdentifications(2).size(), 0)
END_SECTION
*/
START_SECTION((void annotate(AnnotatedMSRun& map, const PeptideIdentificationList& peptide_ids, const std::vector<ProteinIdentification>& protein_ids, const bool clear_ids = false, const bool mapMS1 = false)))
// load id
PeptideIdentificationList identifications;
vector<ProteinIdentification> protein_identifications;
String document_id;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDMapper_1.idXML"), protein_identifications, identifications, document_id);
PeptideIdentificationList identifications2;
vector<ProteinIdentification> protein_identifications2;
String document_id2;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDMapper_7.idXML"), protein_identifications2, identifications2, document_id2);
TEST_EQUAL(identifications.size(),3)
TEST_EQUAL(identifications[0].getHits().size(), 2)
TEST_EQUAL(identifications[1].getHits().size(), 1)
TEST_EQUAL(identifications[2].getHits().size(), 2)
TEST_EQUAL(protein_identifications.size(),1)
TEST_EQUAL(protein_identifications[0].getHits().size(), 2)
TEST_EQUAL(identifications2.size(),3)
TEST_EQUAL(identifications2[0].getHits().size(), 2)
TEST_EQUAL(identifications2[1].getHits().size(), 1)
TEST_EQUAL(identifications2[2].getHits().size(), 2)
TEST_EQUAL(protein_identifications2.size(),1)
TEST_EQUAL(protein_identifications2[0].getHits().size(), 2)
// TEST RT MAPPING
// create experiment
AnnotatedMSRun annotated_experiment;
MSExperiment & experiment = annotated_experiment.getMSExperiment();
MSSpectrum spectrum;
Precursor precursor;
precursor.setMZ(0);
spectrum.setRT(60);
experiment.addSpectrum(spectrum);
experiment[0].getPrecursors().push_back(precursor);
precursor.setMZ(20);
spectrum.setRT(181);
experiment.addSpectrum(spectrum);
experiment[1].getPrecursors().push_back(precursor);
precursor.setMZ(11);
spectrum.setRT(120.0001);
experiment.addSpectrum(spectrum);
experiment[2].getPrecursors().push_back(precursor);
//map
IDMapper mapper;
Param p = mapper.getParameters();
p.setValue("rt_tolerance", 0.5);
p.setValue("mz_tolerance", 0.05);
p.setValue("mz_measure","Da");
p.setValue("ignore_charge", "true");
mapper.setParameters(p);
mapper.annotate(annotated_experiment, identifications, protein_identifications);
//test
TEST_EQUAL(annotated_experiment.getProteinIdentifications().size(), 1)
TEST_EQUAL(annotated_experiment.getProteinIdentifications()[0].getHits().size(),2)
TEST_EQUAL(annotated_experiment.getProteinIdentifications()[0].getHits()[0].getAccession(),"ABCDE")
TEST_EQUAL(annotated_experiment.getProteinIdentifications()[0].getHits()[1].getAccession(),"FGHIJ")
//scan 1
TEST_EQUAL(annotated_experiment.getPeptideIdentifications()[0].getHits().size(), 2)
TEST_EQUAL(annotated_experiment.getPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("LHASGITVTEIPVTATNFK"))
TEST_EQUAL(annotated_experiment.getPeptideIdentifications()[0].getHits()[1].getSequence(), AASequence::fromString("MRSLGYVAVISAVATDTDK"))
//scan 2
TEST_EQUAL(annotated_experiment.getPeptideIdentifications()[1].getHits().size(), 0)
//scan 3
TEST_EQUAL(annotated_experiment.getPeptideIdentifications()[2].getHits().size(), 1)
TEST_EQUAL(annotated_experiment.getPeptideIdentifications()[2].getHits()[0].getSequence(), AASequence::fromString("HSKLSAK"))
//-----------------------------------------------------------------------------------
// TEST NATIVE_ID MAPPING
// create experiment
AnnotatedMSRun annotated_experiment2;
MSExperiment& experiment2 = annotated_experiment2.getMSExperiment();
MSSpectrum spectrum2;
Precursor precursor2;
precursor2.setMZ(0);
spectrum2.setRT(60);
spectrum2.setNativeID("spectrum=1234");
experiment2.addSpectrum(spectrum2);
experiment2[0].getPrecursors().push_back(precursor2);
precursor2.setMZ(20);
spectrum2.setRT(181);
spectrum2.setNativeID("spectrum=6666");
experiment2.addSpectrum(spectrum2);
experiment2[1].getPrecursors().push_back(precursor2);
precursor2.setMZ(11);
spectrum2.setRT(120.0001);
spectrum2.setNativeID("spectrum=4321");
experiment2.addSpectrum(spectrum2);
experiment2[2].getPrecursors().push_back(precursor2);
IDMapper mapper2;
Param p2 = mapper2.getParameters();
p2.setValue("rt_tolerance", 0.5);
p2.setValue("mz_tolerance", 0.05);
p2.setValue("mz_measure","Da");
p2.setValue("ignore_charge", "true");
mapper2.setParameters(p2);
mapper2.annotate(annotated_experiment2, identifications2, protein_identifications2);
//test
TEST_EQUAL(annotated_experiment2.getProteinIdentifications().size(), 1)
TEST_EQUAL(annotated_experiment2.getProteinIdentifications()[0].getHits().size(),2)
TEST_EQUAL(annotated_experiment2.getProteinIdentifications()[0].getHits()[0].getAccession(),"ABCDE")
TEST_EQUAL(annotated_experiment2.getProteinIdentifications()[0].getHits()[1].getAccession(),"FGHIJ")
//scan 1
TEST_EQUAL(annotated_experiment2.getPeptideIdentifications()[0].getHits().size(), 2)
TEST_EQUAL(annotated_experiment2.getPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("LHASGITVTEIPVTATNFK"))
TEST_EQUAL(annotated_experiment2.getPeptideIdentifications()[0].getHits()[1].getSequence(), AASequence::fromString("MRSLGYVAVISAVATDTDK"))
//scan 2
TEST_EQUAL(annotated_experiment2.getPeptideIdentifications()[1].getHits().size(), 0)
//scan 3
TEST_EQUAL(annotated_experiment2.getPeptideIdentifications()[2].getHits().size(), 1)
TEST_EQUAL(annotated_experiment2.getPeptideIdentifications()[2].getHits()[0].getSequence(), AASequence::fromString("HSKLSAK"))
END_SECTION
START_SECTION((template < typename FeatureType > void annotate(FeatureMap< FeatureType > &map, const PeptideIdentificationList &ids, const std::vector< ProteinIdentification > &protein_ids, bool use_centroid_rt=false, bool use_centroid_mz=false)))
{
//load id data
PeptideIdentificationList identifications;
vector<ProteinIdentification> protein_identifications;
String document_id;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDMapper_2.idXML"), protein_identifications, identifications, document_id);
//--------------------------------------------------------------------------------------
//TEST MAPPING TO CONVEX HULLS
FeatureMap fm;
FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDMapper_2.featureXML"), fm);
IDMapper mapper;
Param p = mapper.getParameters();
p.setValue("rt_tolerance", 0.0);
p.setValue("mz_tolerance", 0.0);
p.setValue("mz_measure","Da");
p.setValue("ignore_charge", "true");
mapper.setParameters(p);
mapper.annotate(fm,identifications,protein_identifications);
//test protein ids
TEST_EQUAL(fm.getProteinIdentifications().size(),1)
TEST_EQUAL(fm.getProteinIdentifications()[0].getHits().size(),2)
TEST_EQUAL(fm.getProteinIdentifications()[0].getHits()[0].getAccession(),"ABCDE")
TEST_EQUAL(fm.getProteinIdentifications()[0].getHits()[1].getAccession(),"FGHIJ")
//test peptide ids
TEST_EQUAL(fm[0].getPeptideIdentifications().size(),7)
TEST_EQUAL(fm[0].getPeptideIdentifications()[0].getHits().size(),1)
TEST_EQUAL(fm[0].getPeptideIdentifications()[1].getHits().size(),1)
TEST_EQUAL(fm[0].getPeptideIdentifications()[2].getHits().size(),1)
TEST_EQUAL(fm[0].getPeptideIdentifications()[3].getHits().size(),1)
TEST_EQUAL(fm[0].getPeptideIdentifications()[4].getHits().size(),1)
TEST_EQUAL(fm[0].getPeptideIdentifications()[5].getHits().size(),1)
TEST_EQUAL(fm[0].getPeptideIdentifications()[6].getHits().size(),1)
TEST_EQUAL(fm[0].getPeptideIdentifications()[0].getHits()[0].getSequence(),AASequence::fromString("A"))
TEST_EQUAL(fm[0].getPeptideIdentifications()[1].getHits()[0].getSequence(),AASequence::fromString("K"))
TEST_EQUAL(fm[0].getPeptideIdentifications()[2].getHits()[0].getSequence(),AASequence::fromString("C"))
TEST_EQUAL(fm[0].getPeptideIdentifications()[3].getHits()[0].getSequence(),AASequence::fromString("D"))
TEST_EQUAL(fm[0].getPeptideIdentifications()[4].getHits()[0].getSequence(),AASequence::fromString("E"))
TEST_EQUAL(fm[0].getPeptideIdentifications()[5].getHits()[0].getSequence(),AASequence::fromString("F"))
TEST_EQUAL(fm[0].getPeptideIdentifications()[6].getHits()[0].getSequence(),AASequence::fromString("I"))
//test unassigned peptide ids
TEST_EQUAL(fm.getUnassignedPeptideIdentifications().size(),3)
TEST_EQUAL(fm.getUnassignedPeptideIdentifications()[0].getHits()[0].getSequence(),AASequence::fromString("G"))
TEST_EQUAL(fm.getUnassignedPeptideIdentifications()[1].getHits()[0].getSequence(),AASequence::fromString("H"))
TEST_EQUAL(fm.getUnassignedPeptideIdentifications()[2].getHits()[0].getSequence(),AASequence::fromString("L"))
//--------------------------------------------------------------------------------------
//TEST MAPPING TO CENTROIDS
FeatureMap fm2;
FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDMapper_2.featureXML"), fm2);
p.setValue("rt_tolerance", 4.0);
p.setValue("mz_tolerance", 1.5);
p.setValue("mz_measure","Da");
p.setValue("ignore_charge", "true");
mapper.setParameters(p);
mapper.annotate(fm2,identifications,protein_identifications, true, true);
//test protein ids
TEST_EQUAL(fm2.getProteinIdentifications().size(),1)
TEST_EQUAL(fm2.getProteinIdentifications()[0].getHits().size(),2)
TEST_EQUAL(fm2.getProteinIdentifications()[0].getHits()[0].getAccession(),"ABCDE")
TEST_EQUAL(fm2.getProteinIdentifications()[0].getHits()[1].getAccession(),"FGHIJ")
//test peptide ids
TEST_EQUAL(fm2[0].getPeptideIdentifications().size(),2)
TEST_EQUAL(fm2[0].getPeptideIdentifications()[0].getHits().size(),1)
TEST_EQUAL(fm2[0].getPeptideIdentifications()[1].getHits().size(),1)
TEST_EQUAL(fm2[0].getPeptideIdentifications()[0].getHits()[0].getSequence(),AASequence::fromString("A"))
TEST_EQUAL(fm2[0].getPeptideIdentifications()[1].getHits()[0].getSequence(),AASequence::fromString("K"))
//test unassigned peptide ids
TEST_EQUAL(fm2.getUnassignedPeptideIdentifications().size(),8)
TEST_EQUAL(fm2.getUnassignedPeptideIdentifications()[0].getHits()[0].getSequence(),AASequence::fromString("C"))
TEST_EQUAL(fm2.getUnassignedPeptideIdentifications()[1].getHits()[0].getSequence(),AASequence::fromString("D"))
TEST_EQUAL(fm2.getUnassignedPeptideIdentifications()[2].getHits()[0].getSequence(),AASequence::fromString("E"))
TEST_EQUAL(fm2.getUnassignedPeptideIdentifications()[3].getHits()[0].getSequence(),AASequence::fromString("F"))
TEST_EQUAL(fm2.getUnassignedPeptideIdentifications()[4].getHits()[0].getSequence(),AASequence::fromString("G"))
TEST_EQUAL(fm2.getUnassignedPeptideIdentifications()[5].getHits()[0].getSequence(),AASequence::fromString("H"))
TEST_EQUAL(fm2.getUnassignedPeptideIdentifications()[6].getHits()[0].getSequence(),AASequence::fromString("I"))
TEST_EQUAL(fm2.getUnassignedPeptideIdentifications()[7].getHits()[0].getSequence(),AASequence::fromString("L"))
// ******* test charge-specific matching *******
FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDMapper_2.featureXML"), fm);
p.setValue("rt_tolerance", 0.0);
p.setValue("mz_tolerance", 0.0);
p.setValue("mz_measure", "Da");
p.setValue("ignore_charge", "false");
mapper.setParameters(p);
mapper.annotate(fm, identifications, protein_identifications);
//test protein ids
TEST_EQUAL(fm.getProteinIdentifications().size(), 1)
TEST_EQUAL(fm.getProteinIdentifications()[0].getHits().size(), 2)
TEST_EQUAL(fm.getProteinIdentifications()[0].getHits()[0].getAccession(),
"ABCDE")
TEST_EQUAL(fm.getProteinIdentifications()[0].getHits()[1].getAccession(),
"FGHIJ")
//test peptide ids
TEST_EQUAL(fm[0].getPeptideIdentifications().size(), 3)
TEST_EQUAL(fm[0].getPeptideIdentifications()[0].getHits().size(),1)
TEST_EQUAL(fm[0].getPeptideIdentifications()[1].getHits().size(),1)
TEST_EQUAL(fm[0].getPeptideIdentifications()[2].getHits().size(),1)
TEST_EQUAL(fm[0].getPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("A"))
TEST_EQUAL(fm[0].getPeptideIdentifications()[1].getHits()[0].getSequence(), AASequence::fromString("K"))
TEST_EQUAL(fm[0].getPeptideIdentifications()[2].getHits()[0].getSequence(), AASequence::fromString("C"))
//test unassigned peptide ids
TEST_EQUAL(fm.getUnassignedPeptideIdentifications().size(), 7)
// ******* PPM test *******
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDMapper_4.idXML"), protein_identifications, identifications);
FeatureMap fm_ppm;
FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDMapper_4.featureXML"), fm_ppm);
p.setValue("rt_tolerance", 4.0);
p.setValue("mz_tolerance", 3.0);
p.setValue("mz_measure","ppm");
p.setValue("ignore_charge", "true");
mapper.setParameters(p);
mapper.annotate(fm_ppm,identifications,protein_identifications);
//test peptide ids
TEST_EQUAL(fm_ppm[0].getPeptideIdentifications().size(),1)
TEST_EQUAL(fm_ppm[0].getPeptideIdentifications()[0].getHits().size(),2)
TEST_EQUAL(fm_ppm[0].getPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("LHASGITVTEIPVTATNFK"))
TEST_EQUAL(fm_ppm[1].getPeptideIdentifications().size(),0)
TEST_EQUAL(fm_ppm[2].getPeptideIdentifications().size(),1)
TEST_EQUAL(fm_ppm[2].getPeptideIdentifications()[0].getHits().size(),1)
TEST_EQUAL(fm_ppm[2].getPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("HSKLSAK"))
TEST_EQUAL(fm_ppm[3].getPeptideIdentifications().size(),0)
TEST_EQUAL(fm_ppm[4].getPeptideIdentifications().size(),1)
TEST_EQUAL(fm_ppm[4].getPeptideIdentifications()[0].getHits().size(),2)
TEST_EQUAL(fm_ppm[4].getPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("RASNSPQDPQSATAHSFR"))
TEST_EQUAL(fm_ppm[5].getPeptideIdentifications().size(),0)
TEST_EQUAL(fm_ppm.getUnassignedPeptideIdentifications().size(),2)
TEST_EQUAL(fm_ppm.getUnassignedPeptideIdentifications()[0].getHits()[0].getSequence(), AASequence::fromString("DEAD"))
TEST_EQUAL(fm_ppm.getUnassignedPeptideIdentifications()[0].getHits()[1].getSequence(), AASequence::fromString("DEADA"))
TEST_EQUAL(fm_ppm.getUnassignedPeptideIdentifications()[1].getHits()[0].getSequence(), AASequence::fromString("DEADAA"))
TEST_EQUAL(fm_ppm.getUnassignedPeptideIdentifications()[1].getHits()[1].getSequence(), AASequence::fromString("DEADAAA"))
}
END_SECTION
START_SECTION((void annotate(ConsensusMap& map, const PeptideIdentificationList& ids, const std::vector<ProteinIdentification>& protein_ids, bool measure_from_subelements=false)))
{
IDMapper mapper;
Param p = mapper.getParameters();
p.setValue("mz_tolerance", 0.01);
p.setValue("mz_measure","Da");
p.setValue("ignore_charge", "true");
mapper.setParameters(p);
TOLERANCE_ABSOLUTE(0.01);
std::vector<ProteinIdentification> protein_ids;
std::vector<ProteinIdentification> protein_ids2;
PeptideIdentificationList peptide_ids;
PeptideIdentificationList peptide_ids2;
String document_id;
String document_id2;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDMapper_3.idXML"), protein_ids, peptide_ids, document_id);
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDMapper_5.idXML"), protein_ids2, peptide_ids2, document_id2);
ConsensusXMLFile cons_file;
{
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
ConsensusMap cons_map;
cons_file.load(OPENMS_GET_TEST_DATA_PATH("IDMapper_3.consensusXML"), cons_map);
mapper.annotate(cons_map, peptide_ids, protein_ids);
cons_file.store(tmp_filename,cons_map);
WHITELIST("<?xml-stylesheet, date=");
TEST_FILE_SIMILAR(tmp_filename,OPENMS_GET_TEST_DATA_PATH("IDMapper_3_out1.consensusXML"));
}
{
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
ConsensusMap cons_map;
cons_file.load(OPENMS_GET_TEST_DATA_PATH("IDMapper_3.consensusXML"), cons_map);
mapper.annotate(cons_map, peptide_ids, protein_ids, true);
cons_file.store(tmp_filename,cons_map);
WHITELIST("<?xml-stylesheet, date=");
TEST_FILE_SIMILAR(tmp_filename,OPENMS_GET_TEST_DATA_PATH("IDMapper_3_out2.consensusXML"));
}
{
IDMapper mapper5;
Param p5 = mapper5.getParameters();
p5.setValue("rt_tolerance", 20.0);
p5.setValue("mz_tolerance", 20.0);
p5.setValue("mz_measure","ppm");
p5.setValue("ignore_charge", "true");
p5.setValue("consensus:use_subelements", "true");
p5.setValue("consensus:annotate_ids_with_subelements", "true");
mapper5.setParameters(p5);
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
ConsensusMap cons_map;
cons_file.load(OPENMS_GET_TEST_DATA_PATH("IDMapper_5.consensusXML"), cons_map);
mapper5.annotate(cons_map, peptide_ids2, protein_ids2, true, true);
cons_file.store(tmp_filename,cons_map);
WHITELIST("<?xml-stylesheet, date=");
TEST_FILE_SIMILAR(tmp_filename,OPENMS_GET_TEST_DATA_PATH("IDMapper_5_out1.consensusXML"));
}
// check charge-specific matching:
{
ConsensusMap cm;
cm.resize(1);
cm[0].setRT(4101.48);
cm[0].setMZ(117.1);
cm[0].setCharge(2);
mapper.annotate(cm, peptide_ids, protein_ids);
TEST_EQUAL(cm[0].getPeptideIdentifications().size(), 1);
TEST_EQUAL(cm[0].getPeptideIdentifications()[0].getHits()[0].getSequence(),
AASequence::fromString("ACSF"));
TEST_EQUAL(cm.getUnassignedPeptideIdentifications().size(),
peptide_ids.size() - 1);
cm[0].getPeptideIdentifications().clear();
cm.getUnassignedPeptideIdentifications().clear();
p.setValue("ignore_charge", "false");
mapper.setParameters(p);
mapper.annotate(cm, peptide_ids, protein_ids);
TEST_EQUAL(cm[0].getPeptideIdentifications().size(), 0);
TEST_EQUAL(cm.getUnassignedPeptideIdentifications().size(),
peptide_ids.size());
}
// annotation of precursors without id
IDMapper mapper6;
p = mapper6.getParameters();
p.setValue("mz_tolerance", 0.01);
p.setValue("mz_measure","Da");
p.setValue("ignore_charge", "true");
mapper6.setParameters(p);
TOLERANCE_ABSOLUTE(0.01);
PeakMap experiment;
MSSpectrum spectrum;
// match exactly to the first 10 consensusXML centroids
double mzs[10] = { 426.849, 405.85, 506.815, 484.83, 496.244, 430.212, 446.081, 453.233, 400.172, 437.227 };
double rts[10] = { 306.58, 306.58, 312.738, 312.738, 3112.53, 3840.95, 3849.22, 3870.67, 3880.9, 3892.26};
for (Size i = 0; i != 10; ++i)
{
vector<Precursor> precursors;
Precursor prec;
prec.setMZ(mzs[i]);
precursors.push_back(prec);
spectrum.setRT(rts[i]);
spectrum.setPrecursors(precursors);
experiment.addSpectrum(spectrum);
}
{
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
ConsensusMap cons_map;
cons_file.load(OPENMS_GET_TEST_DATA_PATH("IDMapper_3.consensusXML"), cons_map);
mapper6.annotate(cons_map, PeptideIdentificationList(), vector<ProteinIdentification>(), false, false, experiment);
cons_file.store(tmp_filename, cons_map);
WHITELIST("<?xml-stylesheet, date=");
TEST_FILE_SIMILAR(tmp_filename, OPENMS_GET_TEST_DATA_PATH("IDMapper_6_out1.consensusXML"));
}
experiment.clear(true);
// only 5 should be in the 0.01 Da tolerance (every second entry is too much off)
double mzs_5_mismatch[10] = { 426.85899, 405, 506.815, 484.85, 496.244, 430, 446.081, 453, 400.172, 437.239 };
for (Size i = 0; i != 10; ++i)
{
vector<Precursor> precursors;
Precursor prec;
prec.setMZ(mzs_5_mismatch[i]);
precursors.push_back(prec);
spectrum.setRT(rts[i]);
spectrum.setPrecursors(precursors);
experiment.addSpectrum(spectrum);
}
{
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
ConsensusMap cons_map;
cons_file.load(OPENMS_GET_TEST_DATA_PATH("IDMapper_3.consensusXML"), cons_map);
mapper6.annotate(cons_map, PeptideIdentificationList(), vector<ProteinIdentification>(), false, false, experiment);
cons_file.store(tmp_filename, cons_map);
WHITELIST("<?xml-stylesheet, date=");
TEST_FILE_SIMILAR(tmp_filename, OPENMS_GET_TEST_DATA_PATH("IDMapper_6_out2.consensusXML"));
}
// check mappings of multiple precursors to one consensus feature
experiment.clear(true);
double rts_multiple[5] = { 306.58, 305.58, 307.58, 304.58, 308.58 };
for (Size i = 0; i != 5; ++i)
{
vector<Precursor> precursors;
Precursor prec;
prec.setMZ(426.849);
precursors.push_back(prec);
spectrum.setRT(rts_multiple[i]);
spectrum.setPrecursors(precursors);
experiment.addSpectrum(spectrum);
}
{
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
ConsensusMap cons_map;
cons_file.load(OPENMS_GET_TEST_DATA_PATH("IDMapper_3.consensusXML"), cons_map);
mapper6.annotate(cons_map, PeptideIdentificationList(), vector<ProteinIdentification>(), false, false, experiment);
cons_file.store(tmp_filename, cons_map);
WHITELIST("<?xml-stylesheet, date=");
TEST_FILE_SIMILAR(tmp_filename, OPENMS_GET_TEST_DATA_PATH("IDMapper_6_out3.consensusXML"));
}
}
END_SECTION
START_SECTION([EXTRA] double getAbsoluteMZTolerance_(const double mz) const)
IDMapper2 mapper;
Param p = mapper.getParameters();
p.setValue("mz_tolerance", 1.0);
mapper.setParameters(p);
TEST_REAL_SIMILAR(mapper.getAbsoluteMZTolerance2_(1000), 0.001)
p.setValue("mz_tolerance", 3.0);
mapper.setParameters(p);
TEST_REAL_SIMILAR(mapper.getAbsoluteMZTolerance2_(1000), 0.003)
p.setValue("mz_measure","Da");
mapper.setParameters(p);
TEST_REAL_SIMILAR(mapper.getAbsoluteMZTolerance2_(1000), 3)
END_SECTION
START_SECTION([EXTRA] bool isMatch_(const double rt_distance, const double mz_theoretical, const double mz_observed) const)
IDMapper2 mapper;
TEST_EQUAL(mapper.isMatch2_(1, 1000, 1000.001), true)
Param p = mapper.getParameters();
p.setValue("mz_tolerance", 3.0);
mapper.setParameters(p);
TEST_EQUAL(mapper.isMatch2_(4, 1000, 1000.0028), true)
TEST_EQUAL(mapper.isMatch2_(4, 1000, 1000.004), false)
TEST_EQUAL(mapper.isMatch2_(4, 1000, 999.9972), true)
TEST_EQUAL(mapper.isMatch2_(4, 1000, 999.996), false)
p.setValue("mz_measure","Da");
mapper.setParameters(p);
TEST_EQUAL(mapper.isMatch2_(5, 999, 1002), true)
TEST_EQUAL(mapper.isMatch2_(5, 999, 1002.1), false)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/XTandemInfile_test.cpp | .cpp | 7,018 | 210 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Andreas Bertsch, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/XTandemInfile.h>
///////////////////////////
START_TEST(XTandemInfile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
XTandemInfile* ptr;
XTandemInfile* nullPointer = nullptr;
START_SECTION((XTandemInfile()))
ptr = new XTandemInfile();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~XTandemInfile())
delete ptr;
END_SECTION
XTandemInfile xml_file;
START_SECTION(void setFragmentMassTolerance(double tolerance))
xml_file.setFragmentMassTolerance(13.0);
TEST_REAL_SIMILAR(xml_file.getFragmentMassTolerance(), 13.0)
END_SECTION
START_SECTION(double getFragmentMassTolerance() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setPrecursorMassTolerancePlus(double tol))
xml_file.setPrecursorMassTolerancePlus(14.0);
TEST_REAL_SIMILAR(xml_file.getPrecursorMassTolerancePlus(), 14.0)
END_SECTION
START_SECTION(double getPrecursorMassTolerancePlus() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setPrecursorMassToleranceMinus(double tol))
xml_file.setPrecursorMassToleranceMinus(15.0);
TEST_REAL_SIMILAR(xml_file.getPrecursorMassToleranceMinus(), 15.0)
END_SECTION
START_SECTION(double getPrecursorMassToleranceMinus() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setPrecursorMassErrorUnit(ErrorUnit unit))
xml_file.setPrecursorMassErrorUnit(XTandemInfile::DALTONS);
TEST_EQUAL(xml_file.getPrecursorMassErrorUnit(), XTandemInfile::DALTONS)
xml_file.setPrecursorMassErrorUnit(XTandemInfile::PPM);
TEST_EQUAL(xml_file.getPrecursorMassErrorUnit(), XTandemInfile::PPM)
END_SECTION
START_SECTION(ErrorUnit getPrecursorMassErrorUnit() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setNumberOfThreads(UInt threads))
xml_file.setNumberOfThreads(16);
TEST_EQUAL(xml_file.getNumberOfThreads(), 16)
END_SECTION
START_SECTION(UInt getNumberOfThreads() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setModifications(const ModificationDefinitionsSet& mods))
ModificationDefinitionsSet sets(ListUtils::create<String>("Oxidation (M)"), ListUtils::create<String>("Carboxymethyl (C)"));
xml_file.setModifications(sets);
TEST_EQUAL(xml_file.getModifications() == sets, true)
END_SECTION
START_SECTION(const ModificationDefinitionsSet& getModifications() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setOutputFilename(const String& output))
xml_file.setOutputFilename("blubb_new_outputfilename");
TEST_STRING_EQUAL(xml_file.getOutputFilename(), "blubb_new_outputfilename")
END_SECTION
START_SECTION(const String& getOutputFilename() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setInputFilename(const String& input_file))
xml_file.setInputFilename("blubb_new_inputfilename");
TEST_STRING_EQUAL(xml_file.getInputFilename(), "blubb_new_inputfilename")
END_SECTION
START_SECTION(const String& getInputFilename() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setTaxonomyFilename(const String& filename))
xml_file.setTaxonomyFilename("blubb_new_taxonomy_file");
TEST_STRING_EQUAL(xml_file.getTaxonomyFilename(), "blubb_new_taxonomy_file")
END_SECTION
START_SECTION(const String& getTaxonomyFilename() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setDefaultParametersFilename(const String& filename))
xml_file.setDefaultParametersFilename("blubb_new_default_parameters_file");
TEST_STRING_EQUAL(xml_file.getDefaultParametersFilename(), "blubb_new_default_parameters_file")
END_SECTION
START_SECTION(const String& getDefaultParametersFilename() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setTaxon(const String& taxon))
xml_file.setTaxon("blubb_taxon");
TEST_STRING_EQUAL(xml_file.getTaxon(), "blubb_taxon")
END_SECTION
START_SECTION(const String& getTaxon() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setMaxPrecursorCharge(Int max_charge))
xml_file.setMaxPrecursorCharge(17);
TEST_EQUAL(xml_file.getMaxPrecursorCharge(), 17)
END_SECTION
START_SECTION(Int getMaxPrecursorCharge() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setNumberOfMissedCleavages(UInt missed_cleavages))
xml_file.setNumberOfMissedCleavages(18);
TEST_EQUAL(xml_file.getNumberOfMissedCleavages(), 18)
END_SECTION
START_SECTION(UInt getNumberOfMissedCleavages() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setMaxValidEValue(double value))
xml_file.setMaxValidEValue(19.0);
TEST_REAL_SIMILAR(xml_file.getMaxValidEValue(), 19.0)
END_SECTION
START_SECTION(double getMaxValidEValue() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setPrecursorErrorType(MassType mono_isotopic))
XTandemInfile::MassType mono = XTandemInfile::MONOISOTOPIC;
XTandemInfile::MassType average = XTandemInfile::AVERAGE;
xml_file.setPrecursorErrorType(mono);
TEST_EQUAL(xml_file.getPrecursorErrorType(), mono)
xml_file.setPrecursorErrorType(average);
TEST_EQUAL(xml_file.getPrecursorErrorType(), average)
END_SECTION
START_SECTION(MassType getPrecursorErrorType() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setFragmentMassErrorUnit(ErrorUnit unit))
XTandemInfile::ErrorUnit daltons = XTandemInfile::DALTONS;
XTandemInfile::ErrorUnit ppm = XTandemInfile::PPM;
xml_file.setFragmentMassErrorUnit(daltons);
TEST_EQUAL(xml_file.getFragmentMassErrorUnit(), daltons)
xml_file.setFragmentMassErrorUnit(ppm);
TEST_EQUAL(xml_file.getFragmentMassErrorUnit(), ppm)
END_SECTION
START_SECTION(ErrorUnit getFragmentMassErrorUnit() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void write(const String& filename, bool ignore_member_parameters = false, bool force_default_mods = false))
String filename("XTandemInfile_test.tmp");
NEW_TMP_FILE(filename);
ModificationDefinitionsSet sets(ListUtils::create<String>("Oxidation (M),Dimethyl (N-term),Carboxymethyl (C)"), ListUtils::create<String>("Ammonium (C-term),ICDID (C)"));
xml_file.setModifications(sets);
xml_file.setAllowIsotopeError(true);
xml_file.setSemiCleavage(true);
xml_file.setOutputResults("all");
xml_file.write(filename);
TEST_FILE_SIMILAR(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("XTandemInfile_test_write.xml"))
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MultiplexFiltering_test.cpp | .cpp | 3,550 | 81 | // 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/MultiplexFiltering.h>
#include <OpenMS/FORMAT/MzMLFile.h>
using namespace OpenMS;
START_TEST(MultiplexFiltering, "$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 = 6;
int isotopes_per_peptide_min = 3;
int isotopes_per_peptide_max = 6;
double intensity_cutoff = 10.0;
double rt_band = 2.0;
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);
}
MultiplexFiltering* nullPointer = nullptr;
MultiplexFiltering* ptr;
START_SECTION(MultiplexFiltering(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"))
MultiplexFiltering 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 MultiplexFiltering(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
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ElutionPeakDetection_test.cpp | .cpp | 8,137 | 235 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Erhan Kenar$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FEATUREFINDER/MassTraceDetection.h>
#include <OpenMS/PROCESSING/SMOOTHING/LowessSmoothing.h>
///////////////////////////
#include <OpenMS/FEATUREFINDER/ElutionPeakDetection.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(ElutionPeakDetection, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
ElutionPeakDetection* ptr = nullptr;
ElutionPeakDetection* null_ptr = nullptr;
START_SECTION(ElutionPeakDetection())
{
ptr = new ElutionPeakDetection();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~ElutionPeakDetection())
{
delete ptr;
}
END_SECTION
PeakMap input;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("ElutionPeakDetection_input1.mzML"), input);
std::vector<MassTrace> output_mt, splitted_mt, filtered_mt;
MassTraceDetection test_mtd;
Param mtd_def = MassTraceDetection().getDefaults();
test_mtd.setParameters(mtd_def);
test_mtd.run(input, output_mt);
ElutionPeakDetection test_epd;
Param epd_def = ElutionPeakDetection().getDefaults();
epd_def.setValue("width_filtering", "off");
epd_def.setValue("masstrace_snr_filtering", "false");
test_epd.setParameters(epd_def);
//String mt_labels[] = {"T6", "T7", "T9", "T3", "T4", "T8", "T5", "T2", "T1"};
//String split_labels[] = {"T6.1", "T6.2", "T6.3", "T6.4", "T7.1", "T7.2", "T7.3", "T7.4", "T7.5", "T9.1", "T9.2", "T9.3", "T3.1", "T3.2", "T3.3", "T3.4", "T3.5", "T3.6", "T3.7", "T3.8", "T3.9", "T3.10", "T3.11", "T3.12", "T3.13", "T4.1", "T4.2", "T4.3", "T8.1", "T8.2", "T5", "T2", "T1.1", "T1.2", "T1.3"};
//String filt_labels[] = {"T6.1", "T6.2", "T7.4", "T3.2", "T3.3", "T3.4", "T3.6", "T3.8", "T3.9", "T3.10", "T4.2", "T1.1", "T6.4", "T3.1", "T3.5", "T3.12", "T4.1", "T4.3", "T8.2", "T6.3", "T7.2", "T7.3", "T9.1", "T3.11", "T8.1", "T7.1", "T5", "T9.2", "T2", "T1.2", "T1.3", "T3.7"};
/* NOTE: The lowess smoothing was changed from using the GSL to a direct regression.
* The smoothing test work fine for the modification. The ElutionPeakPicker shows
* large differences and I (and Stefan) have no explanation for the reason.
*
* The test was adapted to use a SavitzkyGolay of polynomial-order 2 instead of a lowess smoothing
* using the GSL because the performance seems to be much more robust (at least when going with
* our unit tests). In addition, I tested how a lowess smoothing with regression performs. The
* differences of the test are given as comments. The maintainer must decide on how
* to handle the situation and which smoothing to keep. I had problems getting all unit
* test running when using lowess smoothing with regression.
*
*/
TOLERANCE_RELATIVE(1.01)
START_SECTION((void detectPeaks(std::vector< MassTrace > &, std::vector< MassTrace > &)))
{
TEST_EQUAL(output_mt.size(), 1);
if (!output_mt.empty())
{
TEST_EQUAL(output_mt[0].getLabel(), "T1");
test_epd.detectPeaks(output_mt, splitted_mt);
// mass traces split to local peaks
//TEST_EQUAL(splitted_mt.size(), 2); // lowess and GSL
TEST_EQUAL(splitted_mt.size(), 3); // SavitzkyGolay
//TEST_EQUAL(splitted_mt.size(), 6); // lowess with regression
// correct labeling if subtraces?
TEST_EQUAL(splitted_mt[0].getLabel(), "T1.1");//lowess and GSL / SavitzkyGolay / lowess with regression
TEST_EQUAL(splitted_mt[1].getLabel(), "T1.2");//lowess and GSL / SavitzkyGolay / lowess with regression
// TEST_EQUAL(splitted_mt[2].getLabel(), "T1.3");//lowess with regression
// TEST_EQUAL(splitted_mt[3].getLabel(), "T1.4");//lowess with regression
// TEST_EQUAL(splitted_mt[4].getLabel(), "T1.5");//lowess with regression
// TEST_EQUAL(splitted_mt[5].getLabel(), "T1.6");//lowess with regression
}
}
END_SECTION
START_SECTION((void detectPeaks(MassTrace &, std::vector< MassTrace > &)))
{
NOT_TESTABLE; // see above
}
END_SECTION
START_SECTION((void filterByPeakWidth(std::vector< MassTrace > &, std::vector< MassTrace > &)))
{
NOT_TESTABLE;
// test_epd.filterByPeakWidth(splitted_mt, filtered_mt);
// TEST_EQUAL(filtered_mt.size(), 32);
// for (Size i = 0; i < filtered_mt.size(); ++i)
// {
// TEST_EQUAL(filtered_mt[i].getLabel(), filt_labels[i]);
// }
}
END_SECTION
START_SECTION((void findLocalExtrema(const MassTrace &, const Size &, std::vector< Size > &, std::vector< Size > &)))
{
std::vector<Size> maxes, mins;
if (!output_mt.empty())
{
MassTrace mt(output_mt[0]);
std::vector<double> rts, ints;
for (MassTrace::const_iterator c_it = mt.begin(); c_it != mt.end(); ++c_it)
{
rts.push_back(c_it->getRT());
ints.push_back(c_it->getIntensity());
}
std::vector<double> smoothed_data;
double win_size = 20;
test_epd.smoothData(mt, win_size);
test_epd.findLocalExtrema(mt, win_size/2, maxes, mins);
// lowess and GSL
//TEST_EQUAL(maxes.size(), 5);
//TEST_EQUAL(mins.size(), 1);
// SavitzkyGolay
TEST_EQUAL(maxes.size(), 4);
TEST_EQUAL(mins.size(), 2);
// test window overlap
mt = output_mt[0];
test_epd.smoothData(mt, win_size);
// The two largest peaks in the elution profile are about 90 spectra appart
double distance_between_peaks = 90 - 20; // don't include other maximum but induce overlap
test_epd.findLocalExtrema(mt, distance_between_peaks, maxes, mins);
TEST_EQUAL(maxes.size(), 2);
TEST_EQUAL(mins.size(), 1);
// lowess with regression
//TEST_EQUAL(maxes.size(), 10);
//TEST_EQUAL(mins.size(), 6);
}
// std::cerr << maxes.size() << " " << mins.size() << std::endl;
}
END_SECTION
splitted_mt.clear();
test_epd.detectPeaks(output_mt, splitted_mt);
START_SECTION((double computeMassTraceNoise(const MassTrace &)))
{
TEST_EQUAL(output_mt.size(), 1);
ABORT_IF(output_mt.empty())
double est_noise(test_epd.computeMassTraceNoise(output_mt[0]));
//TEST_REAL_SIMILAR(est_noise, 515.297);//using lowess and GSL
TEST_REAL_SIMILAR(est_noise, 573.8585);//using SavitzkyGolay
//TEST_REAL_SIMILAR(est_noise, 49027.69);//using lowess with regression
}
END_SECTION
START_SECTION((double computeMassTraceSNR(const MassTrace &)))
{
ABORT_IF(splitted_mt.size() != 3);
double snr1(test_epd.computeMassTraceSNR(splitted_mt[0]));
double snr2(test_epd.computeMassTraceSNR(splitted_mt[1]));
double snr3(test_epd.computeMassTraceSNR(splitted_mt[2]));
// using lowess and GSL
//TEST_REAL_SIMILAR(snr1, 8.6058);
//TEST_REAL_SIMILAR(snr2, 8.946);
// using SavitzkyGolay
TEST_REAL_SIMILAR(snr1, 0.1907);
TEST_REAL_SIMILAR(snr2, 9.8855);
TEST_REAL_SIMILAR(snr3, 7.6432);
// using lowess with regression
//TEST_REAL_SIMILAR(snr1, 0.0497);
//TEST_REAL_SIMILAR(snr2, 0.1450);
}
END_SECTION
START_SECTION((double computeApexSNR(const MassTrace &)))
{
ABORT_IF(splitted_mt.size() != 3);
double snr1(test_epd.computeApexSNR(splitted_mt[0]));
double snr2(test_epd.computeApexSNR(splitted_mt[1]));
double snr3(test_epd.computeApexSNR(splitted_mt[2]));
// using lowess and GSL
//TEST_REAL_SIMILAR(snr1, 40.0159);
//TEST_REAL_SIMILAR(snr2, 58.5950);
// using SavitzkyGolay
TEST_REAL_SIMILAR(snr1, 2.0427);
TEST_REAL_SIMILAR(snr2, 37.7893);
TEST_REAL_SIMILAR(snr3, 52.9933);
// using lowess with regression
//TEST_REAL_SIMILAR(snr1, 6.5177);
//TEST_REAL_SIMILAR(snr2, 7.3813);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SpectrumHelper_test.cpp | .cpp | 14,397 | 361 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/KERNEL/SpectrumHelper.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(SpectrumHelper, "$Id$")
START_SECTION((MSSpectrum::FloatDataArrays::iterator getDataArrayByName(MSSpectrum::FloatDataArrays& a, const String& name)))
MSSpectrum ds;
MSSpectrum::FloatDataArray float_array;
float_array.push_back(56);
float_array.push_back(201);
float_array.push_back(31);
float_array.push_back(201);
float_array.push_back(201);
ds.getFloatDataArrays() = std::vector<MSSpectrum::FloatDataArray>(3, float_array);
ds.getFloatDataArrays()[0].setName("f1");
ds.getFloatDataArrays()[1].setName("f2");
ds.getFloatDataArrays()[2].setName("f3");
TEST_EQUAL(getDataArrayByName(ds.getFloatDataArrays(), "f2") == ds.getFloatDataArrays().end(), false);
TEST_EQUAL(getDataArrayByName(ds.getFloatDataArrays(), "NOT_THERE") == ds.getFloatDataArrays().end(), true);
TEST_EQUAL(getDataArrayByName(ds.getFloatDataArrays(), "f1") - ds.getFloatDataArrays().begin(), 0);
TEST_EQUAL(getDataArrayByName(ds.getFloatDataArrays(), "f2") - ds.getFloatDataArrays().begin(), 1);
TEST_EQUAL(getDataArrayByName(ds.getFloatDataArrays(), "f3") - ds.getFloatDataArrays().begin(), 2);
// test const version
const MSSpectrum::FloatDataArrays cfa(ds.getFloatDataArrays());
TEST_EQUAL(getDataArrayByName(cfa, "f2") == cfa.end(), false);
TEST_EQUAL(getDataArrayByName(cfa, "f1") - cfa.begin(), 0);
TEST_EQUAL(getDataArrayByName(cfa, "NOT_THERE") == cfa.end(), true);
END_SECTION
START_SECTION((MSSpectrum::StringDataArrays::iterator getDataArrayByName(MSSpectrum::StringDataArrays& a, const String& name)))
MSSpectrum ds;
MSSpectrum::StringDataArray string_array;
string_array.push_back("56");
string_array.push_back("201");
string_array.push_back("31");
string_array.push_back("201");
string_array.push_back("201");
ds.getStringDataArrays() = std::vector<MSSpectrum::StringDataArray>(3, string_array);
ds.getStringDataArrays()[0].setName("f1");
ds.getStringDataArrays()[1].setName("f2");
ds.getStringDataArrays()[2].setName("f3");
TEST_EQUAL(getDataArrayByName(ds.getStringDataArrays(), "f2") == ds.getStringDataArrays().end(), false);
TEST_EQUAL(getDataArrayByName(ds.getStringDataArrays(), "NOT_THERE") == ds.getStringDataArrays().end(), true);
TEST_EQUAL(getDataArrayByName(ds.getStringDataArrays(), "f1") - ds.getStringDataArrays().begin(), 0);
TEST_EQUAL(getDataArrayByName(ds.getStringDataArrays(), "f2") - ds.getStringDataArrays().begin(), 1);
TEST_EQUAL(getDataArrayByName(ds.getStringDataArrays(), "f3") - ds.getStringDataArrays().begin(), 2);
END_SECTION
START_SECTION((MSSpectrum::IntegerDataArrays::iterator getDataArrayByName(MSSpectrum::IntegerDataArrays& a, const String& name)))
MSSpectrum ds;
MSSpectrum::IntegerDataArray int_array;
int_array.push_back(56);
int_array.push_back(201);
int_array.push_back(31);
int_array.push_back(201);
int_array.push_back(201);
ds.getIntegerDataArrays() = std::vector<MSSpectrum::IntegerDataArray>(3, int_array);
ds.getIntegerDataArrays()[0].setName("f1");
ds.getIntegerDataArrays()[1].setName("f2");
ds.getIntegerDataArrays()[2].setName("f3");
TEST_EQUAL(getDataArrayByName(ds.getIntegerDataArrays(), "f2") == ds.getIntegerDataArrays().end(), false);
TEST_EQUAL(getDataArrayByName(ds.getIntegerDataArrays(), "NOT_THERE") == ds.getIntegerDataArrays().end(), true);
TEST_EQUAL(getDataArrayByName(ds.getIntegerDataArrays(), "f1") - ds.getIntegerDataArrays().begin(), 0);
TEST_EQUAL(getDataArrayByName(ds.getIntegerDataArrays(), "f2") - ds.getIntegerDataArrays().begin(), 1);
TEST_EQUAL(getDataArrayByName(ds.getIntegerDataArrays(), "f3") - ds.getIntegerDataArrays().begin(), 2);
END_SECTION
START_SECTION((MSChromatogram::FloatDataArrays::iterator getDataArrayByName(const MSChromatogram::FloatDataArrays& a, const String& name)))
MSChromatogram ds;
MSChromatogram::FloatDataArray float_array;
float_array.push_back(56);
float_array.push_back(201);
float_array.push_back(31);
float_array.push_back(201);
float_array.push_back(201);
ds.getFloatDataArrays() = std::vector<MSChromatogram::FloatDataArray>(3, float_array);
ds.getFloatDataArrays()[0].setName("f1");
ds.getFloatDataArrays()[1].setName("f2");
ds.getFloatDataArrays()[2].setName("f3");
TEST_EQUAL(getDataArrayByName(ds.getFloatDataArrays(), "f2") == ds.getFloatDataArrays().end(), false);
TEST_EQUAL(getDataArrayByName(ds.getFloatDataArrays(), "NOT_THERE") == ds.getFloatDataArrays().end(), true);
TEST_EQUAL(getDataArrayByName(ds.getFloatDataArrays(), "f1") - ds.getFloatDataArrays().begin(), 0);
TEST_EQUAL(getDataArrayByName(ds.getFloatDataArrays(), "f2") - ds.getFloatDataArrays().begin(), 1);
TEST_EQUAL(getDataArrayByName(ds.getFloatDataArrays(), "f3") - ds.getFloatDataArrays().begin(), 2);
END_SECTION
START_SECTION((MSChromatogram::StringDataArrays::iterator getDataArrayByName(MSChromatogram::StringDataArrays& a, const String& name)))
MSChromatogram ds;
MSChromatogram::StringDataArray string_array;
string_array.push_back("56");
string_array.push_back("201");
string_array.push_back("31");
string_array.push_back("201");
string_array.push_back("201");
ds.getStringDataArrays() = std::vector<MSChromatogram::StringDataArray>(3, string_array);
ds.getStringDataArrays()[0].setName("f1");
ds.getStringDataArrays()[1].setName("f2");
ds.getStringDataArrays()[2].setName("f3");
TEST_EQUAL(getDataArrayByName(ds.getStringDataArrays(), "f2") == ds.getStringDataArrays().end(), false);
TEST_EQUAL(getDataArrayByName(ds.getStringDataArrays(), "NOT_THERE") == ds.getStringDataArrays().end(), true);
TEST_EQUAL(getDataArrayByName(ds.getStringDataArrays(), "f1") - ds.getStringDataArrays().begin(), 0);
TEST_EQUAL(getDataArrayByName(ds.getStringDataArrays(), "f2") - ds.getStringDataArrays().begin(), 1);
TEST_EQUAL(getDataArrayByName(ds.getStringDataArrays(), "f3") - ds.getStringDataArrays().begin(), 2);
END_SECTION
START_SECTION((MSChromatogram::IntegerDataArrays::iterator getDataArrayByName(MSChromatogram::IntegerDataArrays& a, const String& name)))
MSChromatogram ds;
MSChromatogram::IntegerDataArray int_array;
int_array.push_back(56);
int_array.push_back(201);
int_array.push_back(31);
int_array.push_back(201);
int_array.push_back(201);
ds.getIntegerDataArrays() = std::vector<MSChromatogram::IntegerDataArray>(3, int_array);
ds.getIntegerDataArrays()[0].setName("f1");
ds.getIntegerDataArrays()[1].setName("f2");
ds.getIntegerDataArrays()[2].setName("f3");
TEST_EQUAL(getDataArrayByName(ds.getIntegerDataArrays(), "f2") == ds.getIntegerDataArrays().end(), false);
TEST_EQUAL(getDataArrayByName(ds.getIntegerDataArrays(), "NOT_THERE") == ds.getIntegerDataArrays().end(), true);
TEST_EQUAL(getDataArrayByName(ds.getIntegerDataArrays(), "f1") - ds.getIntegerDataArrays().begin(), 0);
TEST_EQUAL(getDataArrayByName(ds.getIntegerDataArrays(), "f2") - ds.getIntegerDataArrays().begin(), 1);
TEST_EQUAL(getDataArrayByName(ds.getIntegerDataArrays(), "f3") - ds.getIntegerDataArrays().begin(), 2);
END_SECTION
START_SECTION(void removePeaks(PeakContainerT& p, const double pos_start, const double pos_end))
{
MSSpectrum s;
MSChromatogram c;
DataArrays::IntegerDataArray ida;
for (Size i = 5; i < 15; ++i) // RTs: [5 14]
{
s.push_back(Peak1D(i, 0));
c.push_back(ChromatogramPeak(i, 0));
ida.push_back(i);
}
s.getIntegerDataArrays().push_back(ida);
c.getIntegerDataArrays().push_back(ida);
MSSpectrum s1 = s;
removePeaks(s1, 3, 6); // start rt (3) is lower than the minimum (5) within the spectrum
TEST_EQUAL(s1.size(), 2)
TEST_EQUAL(s1.getIntegerDataArrays()[0].size(), 2)
TEST_REAL_SIMILAR(s1[0].getPos(), 5)
TEST_REAL_SIMILAR(s1[1].getPos(), 6)
MSSpectrum s2 = s;
removePeaks(s2, 0, 4); // no peak within the requested range
TEST_EQUAL(s2.size(), 0)
TEST_EQUAL(s2.getIntegerDataArrays()[0].size(), 0)
MSChromatogram c1 = c;
removePeaks(c1, 12, 16); // end rt (16) is higher than the maximum (14) within the chromatogram
TEST_EQUAL(c1.size(), 3)
TEST_EQUAL(c1.getIntegerDataArrays()[0].size(), 3)
TEST_REAL_SIMILAR(c1[0].getPos(), 12)
TEST_REAL_SIMILAR(c1[1].getPos(), 13)
TEST_REAL_SIMILAR(c1[2].getPos(), 14)
MSChromatogram c2 = c;
removePeaks(c2, 9, 12); // all within the range
TEST_EQUAL(c2.size(), 4)
TEST_EQUAL(c2.getIntegerDataArrays()[0].size(), 4)
TEST_REAL_SIMILAR(c2[0].getPos(), 9)
TEST_REAL_SIMILAR(c2[1].getPos(), 10)
TEST_REAL_SIMILAR(c2[2].getPos(), 11)
TEST_REAL_SIMILAR(c2[3].getPos(), 12)
MSSpectrum s_empty;
removePeaks(s_empty, 9, 12);
TEST_EQUAL(s_empty.size(), 0)
}
END_SECTION
START_SECTION(void subtractMinimumIntensity(PeakContainerT& p))
{
MSSpectrum s;
MSChromatogram c;
for (Int i = -5; i < 5; ++i) // Intensities: [-5 4]
{
s.push_back(Peak1D(0, i));
c.push_back(ChromatogramPeak(0, i));
}
subtractMinimumIntensity(s);
TEST_REAL_SIMILAR(s[0].getIntensity(), 0)
TEST_REAL_SIMILAR(s[1].getIntensity(), 1)
TEST_REAL_SIMILAR(s[9].getIntensity(), 9)
subtractMinimumIntensity(c);
TEST_REAL_SIMILAR(c[0].getIntensity(), 0)
TEST_REAL_SIMILAR(c[1].getIntensity(), 1)
TEST_REAL_SIMILAR(c[9].getIntensity(), 9)
MSChromatogram c_empty;
subtractMinimumIntensity(c_empty);
TEST_EQUAL(c_empty.size(), 0)
s.clear(true);
c.clear(true);
for (Int i = 5; i < 15; ++i) // Intensities: [5 14]
{
s.push_back(Peak1D(0, i));
c.push_back(ChromatogramPeak(0, i));
}
subtractMinimumIntensity(s);
TEST_REAL_SIMILAR(s[0].getIntensity(), 0)
TEST_REAL_SIMILAR(s[1].getIntensity(), 1)
TEST_REAL_SIMILAR(s[9].getIntensity(), 9)
subtractMinimumIntensity(c);
TEST_REAL_SIMILAR(c[0].getIntensity(), 0)
TEST_REAL_SIMILAR(c[1].getIntensity(), 1)
TEST_REAL_SIMILAR(c[9].getIntensity(), 9)
}
END_SECTION
START_SECTION(void makePeakPositionUnique(PeakContainerT& p, const int m) )
{
MSSpectrum s;
MSChromatogram c;
MSSpectrum s_template;
MSChromatogram c_template;
s_template.push_back(Peak1D(1, 1));
s_template.push_back(Peak1D(2, 4));
s_template.push_back(Peak1D(2, 8));
s_template.push_back(Peak1D(3, 9));
s_template.push_back(Peak1D(4, 7));
s_template.push_back(Peak1D(2, 10));
c_template.push_back(ChromatogramPeak(1, 1));
c_template.push_back(ChromatogramPeak(2, 4));
c_template.push_back(ChromatogramPeak(2, 8));
c_template.push_back(ChromatogramPeak(3, 9));
c_template.push_back(ChromatogramPeak(4, 7));
c_template.push_back(ChromatogramPeak(2, 10));
s = s_template;
makePeakPositionUnique(s, IntensityAveragingMethod::MEDIAN);
TEST_REAL_SIMILAR(s[0].getIntensity(), 1)
TEST_REAL_SIMILAR(s[1].getIntensity(), 8)
TEST_REAL_SIMILAR(s[2].getIntensity(), 9)
TEST_REAL_SIMILAR(s[3].getIntensity(), 7)
c = c_template;
makePeakPositionUnique(c, IntensityAveragingMethod::MEDIAN);
TEST_REAL_SIMILAR(c[0].getIntensity(), 1)
TEST_REAL_SIMILAR(c[1].getIntensity(), 8)
TEST_REAL_SIMILAR(c[2].getIntensity(), 9)
TEST_REAL_SIMILAR(c[3].getIntensity(), 7)
s = s_template;
makePeakPositionUnique(s, IntensityAveragingMethod::MEAN);
TEST_REAL_SIMILAR(s[0].getIntensity(), 1)
TEST_REAL_SIMILAR(s[1].getIntensity(), (4+8+10)/3.0)
TEST_REAL_SIMILAR(s[2].getIntensity(), 9)
TEST_REAL_SIMILAR(s[3].getIntensity(), 7)
c = c_template;
makePeakPositionUnique(c, IntensityAveragingMethod::MEAN);
TEST_REAL_SIMILAR(c[0].getIntensity(), 1)
TEST_REAL_SIMILAR(c[1].getIntensity(), (4+8+10)/3.0)
TEST_REAL_SIMILAR(c[2].getIntensity(), 9)
TEST_REAL_SIMILAR(c[3].getIntensity(), 7)
s = s_template;
makePeakPositionUnique(s, IntensityAveragingMethod::SUM);
TEST_REAL_SIMILAR(s[0].getIntensity(), 1)
TEST_REAL_SIMILAR(s[1].getIntensity(), (4+8+10))
TEST_REAL_SIMILAR(s[2].getIntensity(), 9)
TEST_REAL_SIMILAR(s[3].getIntensity(), 7)
c = c_template;
makePeakPositionUnique(c, IntensityAveragingMethod::SUM);
TEST_REAL_SIMILAR(c[0].getIntensity(), 1)
TEST_REAL_SIMILAR(c[1].getIntensity(), (4+8+10))
TEST_REAL_SIMILAR(c[2].getIntensity(), 9)
TEST_REAL_SIMILAR(c[3].getIntensity(), 7)
s = s_template;
makePeakPositionUnique(s, IntensityAveragingMethod::MIN);
TEST_REAL_SIMILAR(s[0].getIntensity(), 1)
TEST_REAL_SIMILAR(s[1].getIntensity(), 4)
TEST_REAL_SIMILAR(s[2].getIntensity(), 9)
TEST_REAL_SIMILAR(s[3].getIntensity(), 7)
c = c_template;
makePeakPositionUnique(c, IntensityAveragingMethod::MIN);
TEST_REAL_SIMILAR(c[0].getIntensity(), 1)
TEST_REAL_SIMILAR(c[1].getIntensity(), 4)
TEST_REAL_SIMILAR(c[2].getIntensity(), 9)
TEST_REAL_SIMILAR(c[3].getIntensity(), 7)
s = s_template;
makePeakPositionUnique(s, IntensityAveragingMethod::MAX);
TEST_REAL_SIMILAR(s[0].getIntensity(), 1)
TEST_REAL_SIMILAR(s[1].getIntensity(), 10)
TEST_REAL_SIMILAR(s[2].getIntensity(), 9)
TEST_REAL_SIMILAR(s[3].getIntensity(), 7)
c = c_template;
makePeakPositionUnique(c, IntensityAveragingMethod::MAX);
TEST_REAL_SIMILAR(c[0].getIntensity(), 1)
TEST_REAL_SIMILAR(c[1].getIntensity(), 10)
TEST_REAL_SIMILAR(c[2].getIntensity(), 9)
TEST_REAL_SIMILAR(c[3].getIntensity(), 7)
MSSpectrum s_empty;
makePeakPositionUnique(s_empty);
TEST_EQUAL(s_empty.size(), 0)
MSChromatogram c_empty;
makePeakPositionUnique(c_empty);
TEST_EQUAL(c_empty.size(), 0)
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IsobaricIsotopeCorrector_test.cpp | .cpp | 6,585 | 173 | // 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/IsobaricIsotopeCorrector.h>
///////////////////////////
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/ANALYSIS/QUANTITATION/ItraqFourPlexQuantitationMethod.h>
#include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantifierStatistics.h>
using namespace OpenMS;
using namespace std;
ConsensusFeature getCFWithIntensites(double v[])
{
ConsensusFeature cf;
BaseFeature bf0, bf1, bf2, bf3;
bf0.setIntensity(v[0]);
bf1.setIntensity(v[1]);
bf2.setIntensity(v[2]);
bf3.setIntensity(v[3]);
cf.insert(0, bf0);cf.insert(1, bf1);cf.insert(2, bf2);cf.insert(3, bf3);
cf.setIntensity(v[0]+v[1]+v[2]+v[3]);
return cf;
}
START_TEST(IsobaricIsotopeCorrector, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//
ItraqFourPlexQuantitationMethod quant_meth;
START_SECTION((IsobaricQuantifierStatistics correctIsotopicImpurities(const ConsensusMap &consensus_map_in, ConsensusMap &consensus_map_out)))
{
{ // check the run including output
ConsensusXMLFile cm_file;
ConsensusMap cm_in, cm_out;
cm_file.load(OPENMS_GET_TEST_DATA_PATH("IsobaricIsotopeCorrector.consensusXML"),cm_in);
// copy in/output
cm_out = cm_in;
//
IsobaricQuantifierStatistics stats = IsobaricIsotopeCorrector::correctIsotopicImpurities(cm_in, cm_out, &quant_meth);
// 1. check the actual result
String cm_file_out;
NEW_TMP_FILE(cm_file_out);
cm_file.store(cm_file_out,cm_out);
WHITELIST("<?xml-stylesheet,id=\",href=\"file:////");
TEST_FILE_SIMILAR(cm_file_out,OPENMS_GET_TEST_DATA_PATH("IsobaricIsotopeCorrector_out.consensusXML"));
// 2. check the returned stats -> values are based on the org. impl.
TEST_EQUAL(stats.channel_count, 4)
TEST_EQUAL(stats.iso_number_ms2_negative, 8)
TEST_EQUAL(stats.iso_number_reporter_negative, 9)
TEST_EQUAL(stats.iso_number_reporter_different, 1)
TEST_REAL_SIMILAR(stats.iso_solution_different_intensity, 0.02489106611347)
TEST_REAL_SIMILAR(stats.iso_total_intensity_negative, 559.034896850586)
TEST_EQUAL(stats.number_ms2_total, cm_in.size())
// TEST_EQUAL(stats.number_ms2_empty, 0)
// TEST_EQUAL(stats.empty_channels[114], 0)
// TEST_EQUAL(stats.empty_channels[115], 0)
// TEST_EQUAL(stats.empty_channels[116], 0)
// TEST_EQUAL(stats.empty_channels[117], 0)
}
// 3. check stats in detail
{
ConsensusXMLFile cm_file;
ConsensusMap cm_in, cm_out;
cm_file.load(OPENMS_GET_TEST_DATA_PATH("IsobaricIsotopeCorrector.consensusXML"),cm_in);
cm_in.clear(false);
// copy in/output
cm_out = cm_in;
// first run (empty):
IsobaricQuantifierStatistics stats = IsobaricIsotopeCorrector::correctIsotopicImpurities(cm_in, cm_out, &quant_meth);
TEST_EQUAL(stats.channel_count, 4)
TEST_EQUAL(stats.iso_number_ms2_negative, 0)
TEST_EQUAL(stats.iso_number_reporter_negative, 0)
TEST_EQUAL(stats.iso_number_reporter_different, 0)
TEST_REAL_SIMILAR(stats.iso_solution_different_intensity, 0)
TEST_REAL_SIMILAR(stats.iso_total_intensity_negative, 0)
TEST_EQUAL(stats.number_ms2_total, cm_in.size())
// TEST_EQUAL(stats.number_ms2_empty, 0)
// TEST_EQUAL(stats.empty_channels[114], 0)
// TEST_EQUAL(stats.empty_channels[115], 0)
// TEST_EQUAL(stats.empty_channels[116], 0)
// TEST_EQUAL(stats.empty_channels[117], 0)
// add some target results
double v1[4] = {1.071, 95.341, 101.998, 96.900}; // naive yields: {-1,100,100,100}; NNLS: {0.00000 99.91414 100.00375 99.99990}
cm_in.push_back(getCFWithIntensites(v1));
cm_out = cm_in;
stats = IsobaricIsotopeCorrector::correctIsotopicImpurities(cm_in, cm_out, &quant_meth);
// check the corrected intensities
ABORT_IF(cm_out[0].getFeatures().size() != 4)
ConsensusFeature::HandleSetType::const_iterator it = cm_out[0].getFeatures().begin();
TEST_REAL_SIMILAR(it->getIntensity(), 0.00000)
++it;
TEST_REAL_SIMILAR(it->getIntensity(), 99.91414)
++it;
TEST_REAL_SIMILAR(it->getIntensity(), 100.00375)
++it;
TEST_REAL_SIMILAR(it->getIntensity(), 99.99990)
// test the stats
TEST_EQUAL(stats.channel_count, 4)
TEST_EQUAL(stats.iso_number_ms2_negative, 1)
TEST_EQUAL(stats.iso_number_reporter_negative, 1)
TEST_EQUAL(stats.iso_number_reporter_different, 0)
TEST_REAL_SIMILAR(stats.iso_solution_different_intensity, 0)
TEST_REAL_SIMILAR(stats.iso_total_intensity_negative, 299.9178)
TEST_EQUAL(stats.number_ms2_total, cm_in.size())
// TEST_EQUAL(stats.number_ms2_empty, 0)
// TEST_EQUAL(stats.empty_channels[114], 1)
// TEST_EQUAL(stats.empty_channels[115], 0)
// TEST_EQUAL(stats.empty_channels[116], 0)
// TEST_EQUAL(stats.empty_channels[117], 0)
// change some more... (second run)
double v2[4] = {0,0,0,0};
cm_in.push_back(getCFWithIntensites(v2));
cm_out = cm_in;
stats = IsobaricIsotopeCorrector::correctIsotopicImpurities(cm_in, cm_out, &quant_meth);
TEST_EQUAL(stats.channel_count, 4)
TEST_EQUAL(stats.iso_number_ms2_negative, 1)
TEST_EQUAL(stats.iso_number_reporter_negative, 1)
TEST_EQUAL(stats.iso_number_reporter_different, 0)
TEST_REAL_SIMILAR(stats.iso_solution_different_intensity, 0)
TEST_REAL_SIMILAR(stats.iso_total_intensity_negative, 299.9178)
TEST_EQUAL(stats.number_ms2_total, cm_in.size())
// TEST_EQUAL(stats.number_ms2_empty, 1)
// TEST_EQUAL(stats.empty_channels[114], 2)
// TEST_EQUAL(stats.empty_channels[115], 1)
// TEST_EQUAL(stats.empty_channels[116], 1)
// TEST_EQUAL(stats.empty_channels[117], 1)
}
// 4. test precondition
{
ConsensusXMLFile cm_file;
ConsensusMap cm_in, cm_out;
cm_file.load(OPENMS_GET_TEST_DATA_PATH("IsobaricIsotopeCorrector.consensusXML"),cm_in);
TEST_PRECONDITION_VIOLATED(IsobaricIsotopeCorrector::correctIsotopicImpurities(cm_in,cm_out, &quant_meth))
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/DimMapper_test.cpp | .cpp | 10,763 | 414 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/KERNEL/DimMapper.h>
///////////////////////////
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/ConsensusFeature.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/KERNEL/Peak2D.h>
#include <limits>
using namespace OpenMS;
using namespace std;
START_TEST(DimMapper, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION(DimRT())
{
DimRT rt;
TEST_TRUE(rt.clone()->getUnit() == DIM_UNIT::RT);
}
END_SECTION
START_SECTION(std::unique_ptr<DimBase> clone() const override)
{
DimRT rt;
TEST_TRUE(rt.clone()->getUnit() == DIM_UNIT::RT);
}
END_SECTION
START_SECTION(ValueType map(const Peak1D& p) const override)
{
DimRT rt;
TEST_EXCEPTION(Exception::InvalidRange, rt.map(Peak1D{1, 2}));
}
END_SECTION
START_SECTION(ValueType map(const Peak2D& p) const override)
{
DimRT rt;
TEST_EQUAL(rt.map(Peak2D({1, 2}, 3)), 1.0)
}
END_SECTION
START_SECTION(ValueTypes map(const MSSpectrum& spec) const override)
{
DimRT rt;
TEST_EXCEPTION(Exception::InvalidRange, rt.map(MSSpectrum()))
}
END_SECTION
START_SECTION(ValueType map(MSExperiment::ConstAreaIterator it) const override)
{
DimRT rt;
MSSpectrum spec;
spec.push_back({1, 2});
spec.setRT(5);
MSExperiment exp;
exp.addSpectrum(spec);
TEST_EQUAL(rt.map(exp.areaBeginConst(4, 6, 0, 2)), 5)
}
END_SECTION
START_SECTION(ValueType map(const BaseFeature& bf) const override)
{
DimRT rt;
TEST_EQUAL(rt.map(BaseFeature{Peak2D({1, 2}, 3)}), 1)
}
END_SECTION
START_SECTION(ValueType map(const PeptideIdentification& pi) const override)
{
DimRT rt;
PeptideIdentification pi;
pi.setRT(1);
TEST_EQUAL(rt.map(pi), 1)
}
END_SECTION
START_SECTION(RangeBase map(const RangeManager<RangeRT, RangeMZ, RangeIntensity, RangeMobility>& rm) const override)
{
DimRT rt;
RangeManager<RangeRT, RangeMZ, RangeIntensity, RangeMobility> rm;
rm.extendRT(1);
rm.extendRT(1.1);
rm.extendMZ(2);
rm.extendIntensity(3);
TEST_EQUAL(rt.map(rm), RangeBase(1, 1.1));
}
END_SECTION
START_SECTION(void setRange(const RangeBase& in, RangeManager<RangeRT, RangeMZ, RangeIntensity, RangeMobility>& out) const)
{
DimRT rt;
RangeManager<RangeRT, RangeMZ, RangeIntensity, RangeMobility> rm;
rm.extendRT(1);
rm.extendRT(1.1);
rm.extendMZ(2);
rm.extendIntensity(3);
auto rm_old = rm;
rt.setRange(RangeBase{10, 10.1}, rm);
rm_old.RangeRT::operator=(RangeBase{10, 10.1});
TEST_TRUE(rm == rm_old);
}
END_SECTION
using DimMapper3 = DimMapper<3>;
DimMapper3* ptr = nullptr;
DimMapper3* null_ptr = nullptr;
const DIM_UNIT unitsIMR[3] {DIM_UNIT::INT, DIM_UNIT::MZ, DIM_UNIT::RT};
const DIM_UNIT unitsRMI[3] {DIM_UNIT::RT, DIM_UNIT::MZ, DIM_UNIT::INT};
START_SECTION(DimMapper(const DIM_UNIT (&units)[N_DIM]))
{
ptr = new DimMapper3(unitsIMR);
TEST_NOT_EQUAL(ptr, null_ptr)
delete ptr;
}
END_SECTION
START_SECTION(DimMapper(const DimMapper& rhs))
{
DimMapper3 d1(unitsIMR);
auto d2(d1);
TEST_TRUE(d2 == d1);
}
END_SECTION
START_SECTION(DimMapper& operator=(const DimMapper& rhs))
{
DimMapper3 d1(unitsIMR);
DimMapper3 d2(unitsRMI);
TEST_EQUAL(d2 == d1, false);
d1 = d2;
TEST_TRUE(d2 == d1);
}
END_SECTION
START_SECTION(bool operator==(const DimMapper& rhs) const)
{
DimMapper3 d1(unitsIMR);
DimMapper3 d2(unitsIMR);
TEST_TRUE(d2 == d1);
DimMapper3 d3(unitsRMI);
TEST_TRUE(d3 != d1);
}
END_SECTION
START_SECTION(bool operator!=(const DimMapper& rhs) const)
{
DimMapper3 d1(unitsIMR);
DimMapper3 d2(unitsIMR);
TEST_FALSE(d2 != d1);
DimMapper3 d3(unitsRMI);
TEST_FALSE(d3 == d1);
}
END_SECTION
START_SECTION(template<typename T> Point map(const T& data))
{
DimMapper3 d1(unitsIMR);
Feature f1;
f1.setRT(1);
f1.setMZ(2);
f1.setIntensity(3);
TEST_EQUAL(d1.map(f1), DimMapper3::Point(3, 2, 1))
}
END_SECTION
using FullRange = RangeManager<RangeRT, RangeMZ, RangeIntensity, RangeMobility>;
//auto na = nan("");
//constexpr auto dmax = std::numeric_limits<double>::max();
START_SECTION(template<typename... Ranges> DRange<N_DIM> mapRange(const RangeManager<Ranges...>& ranges) const)
{
FullRange fr;
fr.extendMobility(4); // not considered
fr.extendRT(1);
fr.extendRT(1.1);
DimMapper3 d1(unitsIMR);
auto areaXY = d1.mapRange(fr);
// RT is Z-dimension:
DRange<3> resXY;
resXY.setDimMinMax(2, {1, 1.1});
TEST_EQUAL(areaXY, resXY)
}
END_SECTION
START_SECTION(template<typename... Ranges> void fromXY(const DRange<N_DIM>& in, const RangeManager<Ranges...>& output) const)
{
FullRange fr;
fr.extendMobility(-4); // not considered
fr.extendRT(12134);
DimMapper3 d1(unitsIMR);
// RT is Z-dimension:
DRange<3> areaXY(DPosition<3>(77, 99, 1), DPosition<3>(777, 999, 1.1));
d1.fromXY(areaXY, fr);
TEST_EQUAL(fr.getMinRT(), 1) // overwritten
TEST_EQUAL(fr.getMaxRT(), 1.1)
TEST_EQUAL(fr.getMinMZ(), 99) // overwritten
TEST_EQUAL(fr.getMaxMZ(), 999)
TEST_EQUAL(fr.getMinIntensity(), 77) // overwritten
TEST_EQUAL(fr.getMaxIntensity(), 777)
TEST_EQUAL(fr.getMinMobility(), -4) // not modified
TEST_EQUAL(fr.getMaxMobility(), -4)
}
END_SECTION
START_SECTION(template<typename... Ranges> void fromXY(const Point& in, RangeManager<Ranges...>& output) const)
{
FullRange fr;
fr.extendMobility(-4); // not considered
fr.extendRT(12134);
DimMapper3 d1(unitsIMR);
// RT is Z-dimension:
DRange<3> areaXY(DPosition<3>(77, 99, 1), DPosition<3>(777, 999, 1.1));
d1.fromXY(DimMapper3::Point{2, 3, 1}, fr);
TEST_EQUAL(fr.getMinRT(), 1) // overwritten
TEST_EQUAL(fr.getMaxRT(), 1)
TEST_EQUAL(fr.getMinMZ(), 3) // overwritten
TEST_EQUAL(fr.getMaxMZ(), 3)
TEST_EQUAL(fr.getMinIntensity(), 2) // overwritten
TEST_EQUAL(fr.getMaxIntensity(), 2)
TEST_EQUAL(fr.getMinMobility(), -4) // not modified
TEST_EQUAL(fr.getMaxMobility(), -4)
}
END_SECTION
START_SECTION(const DimBase& getDim(DIM d) const)
{
DimMapper3 d1(unitsIMR);
TEST_TRUE(d1.getDim(DIM::X).getUnit() == DIM_UNIT::INT)
TEST_TRUE(d1.getDim(DIM::Y).getUnit() == DIM_UNIT::MZ)
TEST_TRUE(d1.getDim(DIM::Z).getUnit() == DIM_UNIT::RT)
}
END_SECTION
DimMapper3 dm_IMR(unitsIMR);
DimMapper3 dm_RMI(unitsRMI);
using Area3 = Area<3>;
/////// TEST for Area class
START_SECTION(Area(const DimMapper<N_DIM>* const dims))
{
Area3 a(&dm_IMR);
NOT_TESTABLE // tested below
}
END_SECTION
START_SECTION(Area(const Area& range) = default)
{
Area3 a(&dm_IMR);
Area3 o(a);
TEST_TRUE(a == o)
}
END_SECTION
START_SECTION(Area& operator=(const Area& rhs) = default)
{
Area3 a(&dm_IMR);
auto ar = DRange<3>({1, 1, 1}, {2, 2, 2});
a.setArea(ar);
Area3 o(&dm_IMR);
TEST_TRUE(a != o)
o = a;
TEST_TRUE(a == o)
TEST_EQUAL(o.getAreaXY(), ar);
}
END_SECTION
START_SECTION(bool operator==(const Area& rhs) const)
{
FullRange fr;
fr.extendRT(1);
Area3 a(&dm_IMR);
Area3 o(&dm_IMR);
TEST_TRUE(a == o)
o = a;
TEST_TRUE(a == o)
a.setArea(fr);
TEST_TRUE(a != o)
o = a;
TEST_TRUE(a == o)
DRange<3> areaXY(DPosition<3>(77, 99, 1), DPosition<3>(777, 999, 1.1));
a.setArea(areaXY);
TEST_TRUE(a != o)
TEST_FALSE(a == o)
}
END_SECTION
START_SECTION(bool operator!=(const Area& rhs) const)
{
NOT_TESTABLE // tested above
}
END_SECTION
//constexpr auto min_value = -std::numeric_limits<DRange<3>::CoordinateType>::max();
//constexpr auto max_value = std::numeric_limits<DRange<3>::CoordinateType>::max();
START_SECTION(const Area& setArea(const UnitRange& data))
{
FullRange fr;
fr.RangeRT::operator=(RangeBase{1, 1.1});
fr.RangeMobility::operator=(RangeBase{4, 4.4}); // not considered by DimMapper
fr.RangeIntensity::operator=(RangeBase{2, 2.2});
Area3 a(&dm_IMR);
a.setArea(fr);
TEST_EQUAL(fr, a.getAreaUnit()) // unchanged; just what we put in
DRange<3> areaXY;
areaXY.setDimMinMax(2, {1, 1.1}); // RT is mapped to dim2
areaXY.setDimMinMax(0, {2, 2.2}); // Intensity is mapped to dim0
TEST_EQUAL(a.getAreaXY(), areaXY)
}
END_SECTION
START_SECTION(const Area& setArea(const AreaXYType& data))
{
DRange<3> areaXY;
areaXY.setDimMinMax(2, {1, 1.1}); // RT is mapped to dim2
areaXY.setDimMinMax(0, {2, 2.2}); // Intensity is mapped to dim0
Area3 a(&dm_IMR);
a.setArea(areaXY);
TEST_EQUAL(a.getAreaXY(), areaXY) // unchanged; just what we put in
FullRange fr;
fr.RangeRT::operator=(RangeBase{1, 1.1});
fr.RangeMobility::operator=(RangeBase{4, 4.4}); // not considered by DimMapper
fr.RangeIntensity::operator=(RangeBase{2, 2.2});
TEST_EQUAL((RangeRT)fr, (RangeRT)a.getAreaUnit())
TEST_EQUAL((RangeIntensity)fr, (RangeIntensity)a.getAreaUnit())
TEST_NOT_EQUAL(fr, a.getAreaUnit()) // due to mobility
}
END_SECTION
START_SECTION(const AreaXYType& getAreaXY() const)
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION(const UnitRange& getAreaUnit() const)
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION(Area cloneWith(const AreaXYType& data) const)
{
FullRange fr;
fr.RangeRT::operator=(RangeBase{1, 1.1});
fr.RangeMobility::operator=(RangeBase{4, 4.4}); // not considered by DimMapper
fr.RangeIntensity::operator=(RangeBase{2, 2.2});
Area3 a_old(&dm_IMR);
auto a = a_old.cloneWith(fr);
TEST_EQUAL(fr, a.getAreaUnit()) // unchanged; just what we put in
DRange<3> areaXY;
areaXY.setDimMinMax(2, {1, 1.1}); // RT is mapped to dim2
areaXY.setDimMinMax(0, {2, 2.2}); // Intensity is mapped to dim0
TEST_EQUAL(a.getAreaXY(), areaXY)
}
END_SECTION
START_SECTION(Area cloneWith(const UnitRange& data) const)
{
DRange<3> areaXY;
areaXY.setDimMinMax(2, {1, 1.1}); // RT is mapped to dim2
areaXY.setDimMinMax(0, {2, 2.2}); // Intensity is mapped to dim0
Area3 a_old(&dm_IMR);
auto a = a_old.cloneWith(areaXY);
TEST_EQUAL(a.getAreaXY(), areaXY) // unchanged; just what we put in
FullRange fr;
fr.RangeRT::operator=(RangeBase{1, 1.1});
fr.RangeMobility::operator=(RangeBase{4, 4.4}); // not considered by DimMapper
fr.RangeIntensity::operator=(RangeBase{2, 2.2});
TEST_EQUAL((RangeRT)fr, (RangeRT)a.getAreaUnit())
TEST_EQUAL((RangeIntensity)fr, (RangeIntensity)a.getAreaUnit())
TEST_NOT_EQUAL(fr, a.getAreaUnit()) // due to mobility
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/StandardTypes_test.cpp | .cpp | 1,594 | 56 | // 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/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
START_TEST(StandardTypes, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
START_SECTION(StandardTypes)
STATUS("Note: Here we only check whether the typedefs (as such) are fine.")
NOT_TESTABLE;
END_SECTION
// super duper macro
#define GOOD_TYPEDEF(Type) \
{ \
Type* ptr = 0; \
Type* nullPointer = 0; \
START_SECTION(Type()) \
ptr = new Type; \
TEST_NOT_EQUAL(ptr, nullPointer) \
END_SECTION \
START_SECTION(~Type()) \
delete ptr; \
END_SECTION \
}
GOOD_TYPEDEF(PeakSpectrum)
GOOD_TYPEDEF(PeakMap)
GOOD_TYPEDEF(PeakSpectrum)
GOOD_TYPEDEF(PeakMap)
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/TargetedExperimentHelper_test.cpp | .cpp | 21,122 | 676 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest$
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
///////////////////////////
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperimentHelper.h>
///////////////////////////
#include <unordered_set>
using namespace OpenMS;
using namespace std;
using namespace OpenMS::TargetedExperimentHelper;
START_TEST(TargetedExperimentHelper, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION(TargetedExperimentHelper::Configuration())
{
// Ensure that Configuration has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::Configuration(std::declval<TargetedExperimentHelper::Configuration&&>())), true)
auto ptr = new TargetedExperimentHelper::Configuration();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::CV())
{
// Ensure that CV has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::CV(std::declval<TargetedExperimentHelper::CV&&>())), true)
auto ptr = new TargetedExperimentHelper::CV("", "", "", "");
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::Protein())
{
// Ensure that Protein has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::Protein(std::declval<TargetedExperimentHelper::Protein&&>())), true)
auto ptr = new TargetedExperimentHelper::Protein();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::RetentionTime())
{
// Ensure that RetentionTime has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::RetentionTime(std::declval<TargetedExperimentHelper::RetentionTime&&>())), true)
auto ptr = new TargetedExperimentHelper::RetentionTime();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::PeptideCompound())
{
// Ensure that PeptideCompound has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::PeptideCompound(std::declval<TargetedExperimentHelper::PeptideCompound&&>())), true)
auto ptr = new TargetedExperimentHelper::PeptideCompound();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::Peptide())
{
// Ensure that Peptide has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::Peptide(std::declval<TargetedExperimentHelper::Peptide&&>())), true)
auto ptr = new TargetedExperimentHelper::Peptide();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::Compound())
{
// Ensure that Compound has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::Compound(std::declval<TargetedExperimentHelper::Compound&&>())), true)
auto ptr = new TargetedExperimentHelper::Compound();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::Contact())
{
// Ensure that Contact has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::Contact(std::declval<TargetedExperimentHelper::Contact&&>())), true)
auto ptr = new TargetedExperimentHelper::Contact();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::Publication())
{
// Ensure that Publication has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::Publication(std::declval<TargetedExperimentHelper::Publication&&>())), true)
auto ptr = new TargetedExperimentHelper::Publication();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::Instrument())
{
// Ensure that Instrument has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::Instrument(std::declval<TargetedExperimentHelper::Instrument&&>())), true)
auto ptr = new TargetedExperimentHelper::Instrument();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::Prediction())
{
// Ensure that Prediction has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::Prediction(std::declval<TargetedExperimentHelper::Prediction&&>())), true)
auto ptr = new TargetedExperimentHelper::Prediction();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::Interpretation())
{
// Ensure that Interpretation has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::Interpretation(std::declval<TargetedExperimentHelper::Interpretation&&>())), true)
auto ptr = new TargetedExperimentHelper::Interpretation();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
START_SECTION(TargetedExperimentHelper::TraMLProduct())
{
// Ensure that TraMLProduct has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(TargetedExperimentHelper::TraMLProduct(std::declval<TargetedExperimentHelper::TraMLProduct&&>())), true)
auto ptr = new TargetedExperimentHelper::TraMLProduct();
TEST_FALSE(ptr == nullptr)
delete ptr;
}
END_SECTION
TargetedExperimentHelper::Peptide* ptr = nullptr;
TargetedExperimentHelper::Peptide* null_ptr = nullptr;
START_SECTION(TargetedExperimentHelper::Peptide())
{
ptr = new TargetedExperimentHelper::Peptide();
TEST_NOT_EQUAL(ptr, null_ptr)
// Ensure that Peptide has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(Peptide(std::declval<Peptide&&>())), true)
}
END_SECTION
START_SECTION(~TargetedExperimentHelper::Peptide())
{
delete ptr;
}
END_SECTION
START_SECTION((TargetedExperiment::RetentionTime))
{
TargetedExperimentHelper::RetentionTime rt;
TEST_EQUAL(rt.isRTset(), false)
rt.setRT(5.0);
TEST_EQUAL(rt.isRTset(), true)
TEST_REAL_SIMILAR (rt.getRT(), 5.0)
}
END_SECTION
START_SECTION((TargetedExperiment::Peptide))
{
TargetedExperimentHelper::Peptide p;
TEST_EQUAL(p.hasRetentionTime(), false)
TEST_EQUAL(p.rts.size(), 0)
// add a RT
TargetedExperimentHelper::RetentionTime rt;
rt.setRT(5.0);
rt.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::SECOND;
rt.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::PREDICTED;
p.rts.push_back(rt);
// test the RT methods
TEST_EQUAL(p.rts.size(), 1)
TEST_EQUAL(p.rts[0] == rt, true)
TEST_EQUAL(p.rts[0].retention_time_unit == TargetedExperimentHelper::RetentionTime::RTUnit::SECOND, true)
TEST_EQUAL(p.rts[0].retention_time_type == TargetedExperimentHelper::RetentionTime::RTType::PREDICTED, true)
TEST_REAL_SIMILAR(p.rts[0].getRT(), 5.0)
// test the Peptide methods
TEST_EQUAL(p.hasRetentionTime(), true)
TEST_REAL_SIMILAR(p.getRetentionTime(), 5.0)
TEST_EQUAL(p.getRetentionTimeUnit() == TargetedExperimentHelper::RetentionTime::RTUnit::SECOND, true)
TEST_EQUAL(p.getRetentionTimeType() == TargetedExperimentHelper::RetentionTime::RTType::PREDICTED, true)
TEST_EQUAL(p.getPeptideGroupLabel(), "")
p.setPeptideGroupLabel("test1");
TEST_EQUAL(p.getPeptideGroupLabel(), "test1")
TEST_EQUAL(p.hasCharge(), false)
p.setChargeState(-1);
TEST_EQUAL(p.getChargeState(), -1)
p.setChargeState(2);
TEST_EQUAL(p.getChargeState(), 2)
}
END_SECTION
START_SECTION((TargetedExperiment::Compound))
{
TargetedExperimentHelper::Compound p;
TEST_EQUAL(p.hasRetentionTime(), false)
TEST_EQUAL(p.rts.size(), 0)
// add a RT
TargetedExperimentHelper::RetentionTime rt;
rt.setRT(5.0);
rt.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::SECOND;
rt.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::PREDICTED;
p.rts.push_back(rt);
// test the RT methods
TEST_EQUAL(p.rts.size(), 1)
TEST_EQUAL(p.rts[0] == rt, true)
TEST_EQUAL(p.rts[0].retention_time_unit == TargetedExperimentHelper::RetentionTime::RTUnit::SECOND, true)
TEST_EQUAL(p.rts[0].retention_time_type == TargetedExperimentHelper::RetentionTime::RTType::PREDICTED, true)
TEST_REAL_SIMILAR(p.rts[0].getRT(), 5.0)
// test the Compound methods
TEST_EQUAL(p.hasRetentionTime(), true)
TEST_REAL_SIMILAR(p.getRetentionTime(), 5.0)
TEST_EQUAL(p.getRetentionTimeUnit() == TargetedExperimentHelper::RetentionTime::RTUnit::SECOND, true)
TEST_EQUAL(p.getRetentionTimeType() == TargetedExperimentHelper::RetentionTime::RTType::PREDICTED, true)
// TEST_EQUAL(p.getPeptideGroupLabel(), "")
// p.setPeptideGroupLabel("test1");
// TEST_EQUAL(p.getPeptideGroupLabel(), "test1")
TEST_EQUAL(p.hasCharge(), false)
p.setChargeState(-1);
TEST_EQUAL(p.getChargeState(), -1)
p.setChargeState(2);
TEST_EQUAL(p.getChargeState(), 2)
}
END_SECTION
/////////////////////////////////////////////////////////////
// Hash function tests
/////////////////////////////////////////////////////////////
START_SECTION((std::hash<TargetedExperimentHelper::CV>))
{
TargetedExperimentHelper::CV cv1("id1", "fullname1", "version1", "URI1");
TargetedExperimentHelper::CV cv2("id1", "fullname1", "version1", "URI1");
TargetedExperimentHelper::CV cv3("id2", "fullname2", "version2", "URI2");
std::hash<TargetedExperimentHelper::CV> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(cv1), hasher(cv2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(cv1), hasher(cv3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::CV> cv_set;
cv_set.insert(cv1);
cv_set.insert(cv2);
cv_set.insert(cv3);
TEST_EQUAL(cv_set.size(), 2) // cv1 and cv2 are equal
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::Protein>))
{
TargetedExperimentHelper::Protein p1;
p1.id = "protein1";
p1.sequence = "ACDEFGH";
TargetedExperimentHelper::Protein p2;
p2.id = "protein1";
p2.sequence = "ACDEFGH";
TargetedExperimentHelper::Protein p3;
p3.id = "protein2";
p3.sequence = "IKJLMNPQRST";
std::hash<TargetedExperimentHelper::Protein> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(p1), hasher(p2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(p1), hasher(p3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::Protein> protein_set;
protein_set.insert(p1);
protein_set.insert(p2);
protein_set.insert(p3);
TEST_EQUAL(protein_set.size(), 2)
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::RetentionTime>))
{
TargetedExperimentHelper::RetentionTime rt1;
rt1.setRT(5.0);
rt1.software_ref = "software1";
rt1.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::SECOND;
rt1.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::PREDICTED;
TargetedExperimentHelper::RetentionTime rt2;
rt2.setRT(5.0);
rt2.software_ref = "software1";
rt2.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::SECOND;
rt2.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::PREDICTED;
TargetedExperimentHelper::RetentionTime rt3;
rt3.setRT(10.0);
rt3.software_ref = "software2";
rt3.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::MINUTE;
rt3.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::LOCAL;
std::hash<TargetedExperimentHelper::RetentionTime> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(rt1), hasher(rt2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(rt1), hasher(rt3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::RetentionTime> rt_set;
rt_set.insert(rt1);
rt_set.insert(rt2);
rt_set.insert(rt3);
TEST_EQUAL(rt_set.size(), 2)
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::PeptideCompound>))
{
TargetedExperimentHelper::PeptideCompound pc1;
pc1.id = "compound1";
pc1.setChargeState(2);
TargetedExperimentHelper::PeptideCompound pc2;
pc2.id = "compound1";
pc2.setChargeState(2);
TargetedExperimentHelper::PeptideCompound pc3;
pc3.id = "compound2";
pc3.setChargeState(3);
std::hash<TargetedExperimentHelper::PeptideCompound> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(pc1), hasher(pc2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(pc1), hasher(pc3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::PeptideCompound> pc_set;
pc_set.insert(pc1);
pc_set.insert(pc2);
pc_set.insert(pc3);
TEST_EQUAL(pc_set.size(), 2)
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::Compound>))
{
TargetedExperimentHelper::Compound c1;
c1.id = "compound1";
c1.molecular_formula = "C6H12O6";
c1.smiles_string = "OC[C@H]1OC(O)[C@H](O)[C@@H](O)[C@@H]1O";
c1.theoretical_mass = 180.063;
TargetedExperimentHelper::Compound c2;
c2.id = "compound1";
c2.molecular_formula = "C6H12O6";
c2.smiles_string = "OC[C@H]1OC(O)[C@H](O)[C@@H](O)[C@@H]1O";
c2.theoretical_mass = 180.063;
TargetedExperimentHelper::Compound c3;
c3.id = "compound2";
c3.molecular_formula = "H2O";
c3.smiles_string = "O";
c3.theoretical_mass = 18.015;
std::hash<TargetedExperimentHelper::Compound> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(c1), hasher(c2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(c1), hasher(c3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::Compound> compound_set;
compound_set.insert(c1);
compound_set.insert(c2);
compound_set.insert(c3);
TEST_EQUAL(compound_set.size(), 2)
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::Peptide>))
{
TargetedExperimentHelper::Peptide pep1;
pep1.id = "peptide1";
pep1.sequence = "ACDEFGHIK";
pep1.setPeptideGroupLabel("group1");
TargetedExperimentHelper::Peptide pep2;
pep2.id = "peptide1";
pep2.sequence = "ACDEFGHIK";
pep2.setPeptideGroupLabel("group1");
TargetedExperimentHelper::Peptide pep3;
pep3.id = "peptide2";
pep3.sequence = "LMNPQRSTVWY";
pep3.setPeptideGroupLabel("group2");
std::hash<TargetedExperimentHelper::Peptide> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(pep1), hasher(pep2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(pep1), hasher(pep3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::Peptide> peptide_set;
peptide_set.insert(pep1);
peptide_set.insert(pep2);
peptide_set.insert(pep3);
TEST_EQUAL(peptide_set.size(), 2)
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::Contact>))
{
TargetedExperimentHelper::Contact c1;
c1.id = "contact1";
TargetedExperimentHelper::Contact c2;
c2.id = "contact1";
TargetedExperimentHelper::Contact c3;
c3.id = "contact2";
std::hash<TargetedExperimentHelper::Contact> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(c1), hasher(c2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(c1), hasher(c3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::Contact> contact_set;
contact_set.insert(c1);
contact_set.insert(c2);
contact_set.insert(c3);
TEST_EQUAL(contact_set.size(), 2)
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::Publication>))
{
TargetedExperimentHelper::Publication p1;
p1.id = "pub1";
TargetedExperimentHelper::Publication p2;
p2.id = "pub1";
TargetedExperimentHelper::Publication p3;
p3.id = "pub2";
std::hash<TargetedExperimentHelper::Publication> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(p1), hasher(p2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(p1), hasher(p3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::Publication> pub_set;
pub_set.insert(p1);
pub_set.insert(p2);
pub_set.insert(p3);
TEST_EQUAL(pub_set.size(), 2)
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::Instrument>))
{
TargetedExperimentHelper::Instrument i1;
i1.id = "inst1";
TargetedExperimentHelper::Instrument i2;
i2.id = "inst1";
TargetedExperimentHelper::Instrument i3;
i3.id = "inst2";
std::hash<TargetedExperimentHelper::Instrument> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(i1), hasher(i2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(i1), hasher(i3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::Instrument> inst_set;
inst_set.insert(i1);
inst_set.insert(i2);
inst_set.insert(i3);
TEST_EQUAL(inst_set.size(), 2)
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::Prediction>))
{
TargetedExperimentHelper::Prediction pred1;
pred1.software_ref = "software1";
pred1.contact_ref = "contact1";
TargetedExperimentHelper::Prediction pred2;
pred2.software_ref = "software1";
pred2.contact_ref = "contact1";
TargetedExperimentHelper::Prediction pred3;
pred3.software_ref = "software2";
pred3.contact_ref = "contact2";
std::hash<TargetedExperimentHelper::Prediction> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(pred1), hasher(pred2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(pred1), hasher(pred3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::Prediction> pred_set;
pred_set.insert(pred1);
pred_set.insert(pred2);
pred_set.insert(pred3);
TEST_EQUAL(pred_set.size(), 2)
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::Interpretation>))
{
TargetedExperimentHelper::Interpretation interp1;
interp1.ordinal = 1;
interp1.rank = 1;
interp1.iontype = Residue::BIon;
TargetedExperimentHelper::Interpretation interp2;
interp2.ordinal = 1;
interp2.rank = 1;
interp2.iontype = Residue::BIon;
TargetedExperimentHelper::Interpretation interp3;
interp3.ordinal = 2;
interp3.rank = 2;
interp3.iontype = Residue::YIon;
std::hash<TargetedExperimentHelper::Interpretation> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(interp1), hasher(interp2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(interp1), hasher(interp3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::Interpretation> interp_set;
interp_set.insert(interp1);
interp_set.insert(interp2);
interp_set.insert(interp3);
TEST_EQUAL(interp_set.size(), 2)
}
END_SECTION
START_SECTION((std::hash<TargetedExperimentHelper::TraMLProduct>))
{
TargetedExperimentHelper::TraMLProduct prod1;
prod1.setMZ(500.5);
prod1.setChargeState(2);
TargetedExperimentHelper::TraMLProduct prod2;
prod2.setMZ(500.5);
prod2.setChargeState(2);
TargetedExperimentHelper::TraMLProduct prod3;
prod3.setMZ(600.6);
prod3.setChargeState(3);
std::hash<TargetedExperimentHelper::TraMLProduct> hasher;
// Equal objects should have equal hashes
TEST_EQUAL(hasher(prod1), hasher(prod2))
// Different objects should (very likely) have different hashes
TEST_NOT_EQUAL(hasher(prod1), hasher(prod3))
// Test usability in unordered_set
std::unordered_set<TargetedExperimentHelper::TraMLProduct> prod_set;
prod_set.insert(prod1);
prod_set.insert(prod2);
prod_set.insert(prod3);
TEST_EQUAL(prod_set.size(), 2)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/LinearResampler_test.cpp | .cpp | 3,603 | 149 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Eva Lange $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/PROCESSING/RESAMPLING/LinearResampler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/StandardTypes.h>
///////////////////////////
START_TEST(LinearResampler, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
LinearResampler* lr_ptr = nullptr;
LinearResampler* lr_nullPointer = nullptr;
START_SECTION((LinearResampler()))
lr_ptr = new LinearResampler;
TEST_NOT_EQUAL(lr_ptr, lr_nullPointer);
END_SECTION
START_SECTION((~LinearResampler()))
delete lr_ptr;
END_SECTION
START_SECTION((template<typename PeakType> void raster(MSSpectrum& spectrum)))
{
MSSpectrum spec;
spec.resize(5);
spec[0].setMZ(0);
spec[0].setIntensity(3.0f);
spec[1].setMZ(0.5);
spec[1].setIntensity(6.0f);
spec[2].setMZ(1.);
spec[2].setIntensity(8.0f);
spec[3].setMZ(1.6);
spec[3].setIntensity(2.0f);
spec[4].setMZ(1.8);
spec[4].setIntensity(1.0f);
LinearResampler lr;
Param param;
param.setValue("spacing",0.5);
lr.setParameters(param);
lr.raster(spec);
double sum = 0.0;
for (Size i=0; i<spec.size(); ++i)
{
sum += spec[i].getIntensity();
}
TEST_REAL_SIMILAR(sum, 20);
}
/////////// test raster with a spacing of 0.75
{
MSSpectrum spec;
spec.resize(5);
spec[0].setMZ(0);
spec[0].setIntensity(3.0f);
spec[1].setMZ(0.5);
spec[1].setIntensity(6.0f);
spec[2].setMZ(1.);
spec[2].setIntensity(8.0f);
spec[3].setMZ(1.6);
spec[3].setIntensity(2.0f);
spec[4].setMZ(1.8);
spec[4].setIntensity(1.0f);
// A spacing of 0.75 will lead to a recalculation of intensities, each
// resampled point gets intensities from raw data points that are at most +/-
// spacing away.
LinearResampler lr;
Param param;
param.setValue("spacing",0.75);
lr.setParameters(param);
lr.raster(spec);
double sum = 0.0;
for (Size i=0; i<spec.size(); ++i)
{
sum += spec[i].getIntensity();
}
TEST_REAL_SIMILAR(sum, 20);
TEST_REAL_SIMILAR(spec[0].getIntensity(), 3+2);
TEST_REAL_SIMILAR(spec[1].getIntensity(), 4+2.0/3*8);
TEST_REAL_SIMILAR(spec[2].getIntensity(), 1.0/3*8+2+1.0/3);
TEST_REAL_SIMILAR(spec[3].getIntensity(), 2.0 / 3);
}
END_SECTION
START_SECTION(( template <typename PeakType > void rasterExperiment(MSExperiment<PeakType>& exp)))
{
MSSpectrum spec;
spec.resize(5);
spec[0].setMZ(0);
spec[0].setIntensity(3.0f);
spec[1].setMZ(0.5);
spec[1].setIntensity(6.0f);
spec[2].setMZ(1.);
spec[2].setIntensity(8.0f);
spec[3].setMZ(1.6);
spec[3].setIntensity(2.0f);
spec[4].setMZ(1.8);
spec[4].setIntensity(1.0f);
PeakMap exp;
exp.addSpectrum(spec);
exp.addSpectrum(spec);
LinearResampler lr;
Param param;
param.setValue("spacing",0.5);
lr.setParameters(param);
lr.rasterExperiment(exp);
for (Size s=0; s<exp.size(); ++s)
{
double sum = 0.0;
for (Size i=0; i<exp[s].size(); ++i)
{
sum += exp[s][i].getIntensity();
}
TEST_REAL_SIMILAR(sum, 20);
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/TransformationModelLinear_test.cpp | .cpp | 6,441 | 206 | // 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, Stephan Aiche $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLinear.h>
///////////////////////////
START_TEST(TransformationModelLinear, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
TransformationModelLinear* ptr = nullptr;
TransformationModelLinear* nullPointer = nullptr;
TransformationModel::DataPoints data, empty;
TransformationModel::DataPoint point;
point.first = 0.0;
point.second = 1.0;
data.push_back(point);
point.first = 1.0;
point.second = 2.0;
data.push_back(point);
point.first = 1.0;
point.second = 4.0;
data.push_back(point);
START_SECTION((TransformationModelLinear(const DataPoints &, const Param &)))
{
TEST_EXCEPTION(Exception::IllegalArgument, TransformationModelLinear lm(empty, Param())); // need data
ptr = new TransformationModelLinear(data, Param());
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION((~TransformationModelLinear()))
{
delete ptr;
}
END_SECTION
START_SECTION((virtual double evaluate(double value) const))
{
ptr = new TransformationModelLinear(data, Param());
TEST_REAL_SIMILAR(ptr->evaluate(-0.5), 0.0);
TEST_REAL_SIMILAR(ptr->evaluate(0.0), 1.0);
TEST_REAL_SIMILAR(ptr->evaluate(0.5), 2.0);
TEST_REAL_SIMILAR(ptr->evaluate(1.0), 3.0);
TEST_REAL_SIMILAR(ptr->evaluate(1.5), 4.0);
delete ptr;
}
END_SECTION
START_SECTION((void getParameters(Param & params) const))
{
TransformationModel::DataPoint point;
point.first = 2.0;
point.second = 2.0;
data.push_back(point);
Param p_in;
//test weightings
p_in.setValue("symmetric_regression", "true");
p_in.setValue("x_weight", "ln(x)");
p_in.setValue("y_weight", "ln(y)");
p_in.setValue("x_datum_min", 10e-5);
p_in.setValue("x_datum_max", 1e15);
p_in.setValue("y_datum_min", 10e-8);
p_in.setValue("y_datum_max", 1e15);
TransformationModelLinear lm0(data, p_in);
Param p_out = p_in;
p_out.setValue("slope", 0.095036911971605034);
p_out.setValue("intercept", 0.89550911545438994);
TEST_EQUAL(lm0.getParameters(), p_out);
//add additional data and test without weightings
p_in.setValue("x_weight", "x");
p_in.setValue("y_weight", "y");
p_in.setValue("x_datum_min", 10e-5);
p_in.setValue("x_datum_max", 1e15);
p_in.setValue("y_datum_min", 10e-8);
p_in.setValue("y_datum_max", 1e15);
TransformationModelLinear lm(data, p_in);
p_out = p_in;
p_out.setValue("slope", 0.5);
p_out.setValue("intercept", 1.75);
TEST_EQUAL(lm.getParameters(), p_out);
//test with empty data
p_in.clear();
p_in.setValue("slope", 12.3);
p_in.setValue("intercept", -45.6);
p_in.setValue("x_weight", "x");
p_in.setValue("y_weight", "y");
p_in.setValue("x_datum_min", 10e-5);
p_in.setValue("x_datum_max", 1e15);
p_in.setValue("y_datum_min", 10e-8);
p_in.setValue("y_datum_max", 1e15);
TransformationModelLinear lm2(empty, p_in);
TEST_EQUAL(lm2.getParameters(), p_in);
}
END_SECTION
START_SECTION(([EXTRA] void getParameters(double&, double&, String&, String&, double&, double&, double&, double&)))
{
Param param;
param.setValue("slope", 12.3);
param.setValue("intercept", -45.6);
String x_weight_test, y_weight_test;
x_weight_test = "x";
y_weight_test = "ln(y)";
param.setValue("x_weight", x_weight_test);
param.setValue("y_weight", y_weight_test);
param.setValue("x_datum_min", 1e-15);
param.setValue("x_datum_max", 1e15);
param.setValue("y_datum_min", 1e-15);
param.setValue("y_datum_max", 1e15);
TransformationModelLinear lm(empty, param);
double slope, intercept, x_datum_min, x_datum_max, y_datum_min, y_datum_max;
String x_weight, y_weight;
lm.getParameters(slope, intercept, x_weight, y_weight, x_datum_min, x_datum_max, y_datum_min, y_datum_max);
TEST_REAL_SIMILAR(param.getValue("slope"), slope);
TEST_REAL_SIMILAR(param.getValue("intercept"), intercept);
TEST_EQUAL(param.getValue("x_weight"), x_weight);
TEST_EQUAL(param.getValue("y_weight"), y_weight);
TEST_REAL_SIMILAR(param.getValue("x_datum_min"), x_datum_min);
TEST_REAL_SIMILAR(param.getValue("x_datum_max"), x_datum_max);
TEST_REAL_SIMILAR(param.getValue("y_datum_min"), y_datum_min);
TEST_REAL_SIMILAR(param.getValue("y_datum_max"), y_datum_max);
}
END_SECTION
START_SECTION((TransformationModelLinear(const DataPoints &, const Param &)))
{
// weighting/unweighting test 1
// set-up the parameters
Param param;
String x_weight_test, y_weight_test;
x_weight_test = "ln(x)";
y_weight_test = "ln(y)";
param.setValue("x_weight", x_weight_test);
param.setValue("y_weight", y_weight_test);
param.setValue("x_datum_min", 1e-15);
param.setValue("x_datum_max", 1e8);
param.setValue("y_datum_min", 1e-8);
param.setValue("y_datum_max", 1e15);
// set-up the data and test
TransformationModel::DataPoints data1;
data1.clear();
TransformationModel::DataPoint point;
point.first = 1.0;
point.second = 2.0;
data1.push_back(point);
point.first = 2.0;
point.second = 4.0;
data1.push_back(point);
point.first = 4.0;
point.second = 8.0;
data1.push_back(point);
// test evaluate
TransformationModelLinear lm(data1, param);
TEST_REAL_SIMILAR(lm.evaluate(2), 4);
// test evaluate using the inverted model
lm.invert();
TEST_REAL_SIMILAR(lm.evaluate(4), 2);
// weighting/unweighting test 2
// set-up the parameters
x_weight_test = "1/x";
y_weight_test = "y";
param.setValue("x_weight", x_weight_test);
param.setValue("y_weight", y_weight_test);
// test evaluate
TransformationModelLinear lm1(data1, param);
TEST_REAL_SIMILAR(lm1.evaluate(2),5.285714286);
// test evaluate using the inverted model
lm1.invert();
TEST_REAL_SIMILAR(lm1.evaluate(5.285714286),2);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MzCalibration_test.cpp | .cpp | 8,892 | 239 | // 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/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/DataProcessing.h>
#include <OpenMS/QC/MzCalibration.h>
///////////////////////////
START_TEST(MzCalibration, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
MzCalibration* ptr = nullptr;
MzCalibration* nullPointer = nullptr;
START_SECTION(MzCalibration())
ptr = new MzCalibration();
TEST_NOT_EQUAL(ptr, nullPointer);
END_SECTION
START_SECTION(~MzCalibration())
delete ptr;
END_SECTION
START_SECTION(QCBase::Status requirements() const override)
{
MzCalibration mzCal;
TEST_EQUAL(mzCal.requirements() == (QCBase::Status() | QCBase::Requires::POSTFDRFEAT), true);
}
END_SECTION
// PeakMap
PeakMap exp;
MSSpectrum spec;
Precursor pre;
std::vector<MSSpectrum> spectra;
pre.setMetaValue("mz_raw", 5);
spec.setMSLevel(2);
spec.setPrecursors({pre});
spec.setRT(0);
spec.setNativeID("XTandem::1");
spectra.push_back(spec);
pre.setMetaValue("mz_raw", 6);
spec.setPrecursors({pre});
spec.setRT(0.5);
spec.setNativeID("XTandem::2");
spectra.push_back(spec);
pre.setMetaValue("mz_raw", 7);
spec.setPrecursors({pre});
spec.setRT(1);
spec.setNativeID("XTandem::3");
spectra.push_back(spec);
exp.setSpectra(spectra);
MSExperiment exp_no_calibration = exp;
// adding processing info
DataProcessing p;
p.setProcessingActions({OpenMS::DataProcessing::CALIBRATION});
std::shared_ptr<DataProcessing> p_(new DataProcessing(p));
for (Size i = 0; i < exp.size(); ++i)
{
exp[i].getDataProcessing().push_back(p_);
}
for (Size i = 0; i < exp.getNrChromatograms(); ++i)
{
exp.getChromatogram(i).getDataProcessing().push_back(p_);
}
QCBase::SpectraMap spectra_map(exp);
// FeatureMap
FeatureMap fmap_ref;
PeptideHit peptide_hit;
std::vector<PeptideHit> peptide_hits;
PeptideIdentification peptide_ID;
PeptideIdentificationList identifications;
PeptideIdentificationList unassignedIDs;
Feature feature1;
peptide_hit.setSequence(AASequence::fromString("AAAA"));
peptide_hit.setCharge(2);
peptide_hits.push_back(peptide_hit);
peptide_ID.setHits(peptide_hits);
peptide_ID.setRT(0);
peptide_ID.setMZ(5.5);
peptide_ID.setSpectrumReference( "XTandem::1");
identifications.push_back(peptide_ID);
peptide_hits.clear();
peptide_hit.setSequence(AASequence::fromString("WWWW"));
peptide_hit.setCharge(3);
peptide_hits.push_back(peptide_hit);
peptide_ID.setHits(peptide_hits);
peptide_ID.setRT(1);
peptide_ID.setSpectrumReference( "XTandem::3");
identifications.push_back(peptide_ID);
peptide_hits.clear();
feature1.setPeptideIdentifications(identifications);
fmap_ref.push_back(feature1);
// unassigned PeptideHits
peptide_hit.setSequence(AASequence::fromString("YYYY"));
peptide_hit.setCharge(2);
peptide_hits.push_back(peptide_hit);
peptide_ID.setHits(peptide_hits);
peptide_hits.clear();
peptide_ID.setRT(0.5);
peptide_ID.setSpectrumReference( "XTandem::2");
unassignedIDs.push_back(peptide_ID);
fmap_ref.setUnassignedPeptideIdentifications(unassignedIDs);
MzCalibration cal;
// tests compute function
START_SECTION(void compute(FeatureMap& features, const MSExperiment& exp, const QCBase::SpectraMap map_to_spectrum))
{
FeatureMap fmap = fmap_ref;
cal.compute(fmap, exp, spectra_map);
// things that shouldn't change
ABORT_IF(fmap.size() != 1);
ABORT_IF(fmap[0].getPeptideIdentifications().size() != 2);
ABORT_IF(fmap[0].getPeptideIdentifications()[0].getHits().size() != 1);
ABORT_IF(fmap[0].getPeptideIdentifications()[1].getHits().size() != 1);
ABORT_IF(fmap.getUnassignedPeptideIdentifications().size() != 1);
ABORT_IF(fmap.getUnassignedPeptideIdentifications()[0].getHits().size() != 1);
// things that should now be there
for (const Feature& f : fmap)
{
for (const PeptideIdentification& pepID : f.getPeptideIdentifications())
{
ABORT_IF(!pepID.getHits()[0].metaValueExists("mz_raw"));
ABORT_IF(!pepID.getHits()[0].metaValueExists("mz_ref"));
ABORT_IF(!pepID.getHits()[0].metaValueExists("uncalibrated_mz_error_ppm"));
ABORT_IF(!pepID.getHits()[0].metaValueExists("calibrated_mz_error_ppm"));
}
}
for (const PeptideIdentification& upepID : fmap.getUnassignedPeptideIdentifications())
{
ABORT_IF(!upepID.getHits()[0].metaValueExists("mz_raw"));
ABORT_IF(!upepID.getHits()[0].metaValueExists("mz_ref"));
}
// test with valid input
TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("mz_raw"), 5);
TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[1].getHits()[0].getMetaValue("mz_raw"), 7);
// test unassigned
TEST_REAL_SIMILAR(fmap.getUnassignedPeptideIdentifications()[0].getHits()[0].getMetaValue("mz_raw"), 6);
// test refMZ
double ref = AASequence::fromString("AAAA").getMonoWeight(OpenMS::Residue::Full, 2) / 2;
TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("mz_ref"), ref);
TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[1].getHits()[0].getMetaValue("mz_ref"), AASequence::fromString("WWWW").getMonoWeight(OpenMS::Residue::Full, 3) / 3);
TEST_REAL_SIMILAR(fmap.getUnassignedPeptideIdentifications()[0].getHits()[0].getMetaValue("mz_ref"), AASequence::fromString("YYYY").getMonoWeight(OpenMS::Residue::Full, 2) / 2);
// test mz_error
TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("uncalibrated_mz_error_ppm"), (5 - ref) / ref * 1000000);
TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("calibrated_mz_error_ppm"), (5.5 - ref) / ref * 1000000);
// test empty MSExperiment
MSExperiment exp_empty {};
QCBase::SpectraMap spectra_map_empty(exp_empty);
fmap = fmap_ref; // reset FeatureMap
cal.compute(fmap, exp_empty, spectra_map_empty);
TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("uncalibrated_mz_error_ppm"), (5.5 - ref) / ref * 1000000);
// test with exp where no calibration was performed
fmap = fmap_ref;
cal.compute(fmap, exp_no_calibration, spectra_map);
TEST_REAL_SIMILAR(fmap[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("uncalibrated_mz_error_ppm"), (5.5 - ref) / ref * 1000000);
// test empty FeatureMap
FeatureMap fmap_empty {};
cal.compute(fmap_empty, exp, spectra_map);
TEST_EQUAL(fmap_empty.isMetaEmpty(), true);
// test feature is empty
Feature feature_empty {};
fmap_empty.push_back(feature_empty);
cal.compute(fmap_empty, exp, spectra_map);
TEST_EQUAL(fmap_empty.isMetaEmpty(), true);
// test empty PeptideIdentification
fmap_empty.clear();
PeptideIdentification peptide_ID_empty {};
identifications.push_back(peptide_ID_empty);
feature1.setPeptideIdentifications(identifications);
fmap_empty.push_back(feature1);
cal.compute(fmap_empty, exp, spectra_map);
TEST_EQUAL(fmap_empty.isMetaEmpty(), true);
// test empty hit
fmap_empty.clear();
peptide_ID.setHits(std::vector<PeptideHit> {});
identifications.clear();
identifications.push_back(peptide_ID);
feature1.setPeptideIdentifications(identifications);
fmap_empty.push_back(feature1);
cal.compute(fmap_empty, exp, spectra_map);
TEST_EQUAL(fmap_empty.isMetaEmpty(), true);
// test wrong MS-Level exception
fmap = fmap_ref; // reset FeatureMap
fmap[0].getPeptideIdentifications()[0].setSpectrumReference( "XTandem::4");
exp.getSpectra()[0].setNativeID("XTandem::4");
exp.getSpectra()[0].setMSLevel(1);
spectra_map.calculateMap(exp);
TEST_EXCEPTION_WITH_MESSAGE(Exception::IllegalArgument, cal.compute(fmap, exp, spectra_map), "The matching spectrum of the mzML is not an MS2 Spectrum.");
// test exception PepID without 'spectrum_reference'
fmap = fmap_ref; // reset FeatureMap
PeptideIdentification pep_no_spec_ref;
PeptideHit dummy_hit;
dummy_hit.setSequence(AASequence::fromString("MMMMM"));
dummy_hit.setCharge(2);
pep_no_spec_ref.setHits({dummy_hit});
fmap[0].setPeptideIdentifications({pep_no_spec_ref});
TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidParameter, cal.compute(fmap, exp, spectra_map), "No spectrum reference annotated at peptide identification!");
}
END_SECTION
START_SECTION(const String& getName() const)
{
TEST_EQUAL(cal.getName(), "MzCalibration");
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/EmgScoring_test.cpp | .cpp | 2,690 | 97 | // 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 "OpenSwathTestHelper.h"
#include <OpenMS/FEATUREFINDER/EmgScoring.h>
#include <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/ANALYSIS/MRM/ReactionMonitoringTransition.h>
///////////////////////////
using namespace OpenMS;
START_TEST(EmgScoring, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
EmgScoring* ptr = nullptr;
EmgScoring* nullPointer = nullptr;
START_SECTION(EmgScoring())
{
ptr = new EmgScoring();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~EmgScoring())
{
delete ptr;
}
END_SECTION
START_SECTION(Param getDefaults())
{
EmgScoring emgscore;
Param p = emgscore.getDefaults();
TEST_NOT_EQUAL(&p, nullPointer)
}
END_SECTION
START_SECTION(void setFitterParam(Param param))
{
EmgScoring emgscore;
Param p = emgscore.getDefaults();
TEST_NOT_EQUAL(&p, nullPointer)
emgscore.setFitterParam(p);
}
END_SECTION
START_SECTION(( template < typename SpectrumType, class TransitionT > double calcElutionFitScore(MRMFeature &mrmfeature, MRMTransitionGroup< SpectrumType, TransitionT > &transition_group)))
{
// test a set of feature (belonging to the same peptide)
double elution_model_fit_score;
EmgScoring emgscore;
MRMFeature feature = OpenSWATH_Test::createMockFeature();
OpenSWATH_Test::MRMTransitionGroupType transition_group = OpenSWATH_Test::createMockTransitionGroup();
elution_model_fit_score = emgscore.calcElutionFitScore(feature, transition_group);
TEST_REAL_SIMILAR(elution_model_fit_score, 0.924365639)
}
END_SECTION
START_SECTION( double elutionModelFit(ConvexHull2D::PointArrayType current_section, bool smooth_data) )
{
// test a single feature
double elution_model_fit_score;
EmgScoring emgscore;
MRMFeature feature = OpenSWATH_Test::createMockFeature();
Feature f = feature.getFeature("tr1");
elution_model_fit_score = emgscore.elutionModelFit(f.getConvexHulls()[0].getHullPoints() , false);
TEST_REAL_SIMILAR(elution_model_fit_score, 0.981013417243958)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/CVTerm_test.cpp | .cpp | 9,303 | 363 | // 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/CVTerm.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(CVTerm, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
CVTerm* ptr = nullptr;
CVTerm* nullPointer = nullptr;
START_SECTION(CVTerm())
{
ptr = new CVTerm();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(virtual ~CVTerm())
{
delete ptr;
}
END_SECTION
START_SECTION((bool operator==(const CVTerm &rhs) const ))
{
CVTerm term1, term2;
TEST_TRUE(term1 == term2)
term1.setAccession("acc");
TEST_EQUAL(term1 == term2, false)
term2.setAccession("acc");
TEST_TRUE(term1 == term2)
term1.setName("name");
TEST_EQUAL(term1 == term2, false)
term2.setName("name");
TEST_TRUE(term1 == term2)
term1.setCVIdentifierRef("cv_id_ref");
TEST_EQUAL(term1 == term2, false)
term2.setCVIdentifierRef("cv_id_ref");
TEST_TRUE(term1 == term2)
term1.setValue(DataValue(0.4));
TEST_EQUAL(term1 == term2, false)
term2.setValue(DataValue(0.4));
TEST_TRUE(term1 == term2)
term1.setUnit(CVTerm::Unit("u_acc", "u_name", "u_cv_ref"));
TEST_EQUAL(term1 == term2, false)
term2.setUnit(CVTerm::Unit("u_acc", "u_name", "u_cv_ref"));
TEST_TRUE(term1 == term2)
}
END_SECTION
START_SECTION((bool operator!=(const CVTerm &rhs) const ))
{
CVTerm term1, term2;
TEST_EQUAL(term1 != term2, false)
term1.setAccession("acc");
TEST_FALSE(term1 == term2)
term2.setAccession("acc");
TEST_EQUAL(term1 != term2, false)
term1.setName("name");
TEST_FALSE(term1 == term2)
term2.setName("name");
TEST_EQUAL(term1 != term2, false)
term1.setCVIdentifierRef("cv_id_ref");
TEST_FALSE(term1 == term2)
term2.setCVIdentifierRef("cv_id_ref");
TEST_EQUAL(term1 != term2, false)
term1.setValue(DataValue(0.4));
TEST_FALSE(term1 == term2)
term2.setValue(DataValue(0.4));
TEST_EQUAL(term1 != term2, false)
term1.setUnit(CVTerm::Unit("u_acc", "u_name", "u_cv_ref"));
TEST_FALSE(term1 == term2)
term2.setUnit(CVTerm::Unit("u_acc", "u_name", "u_cv_ref"));
TEST_EQUAL(term1 != term2, false)
}
END_SECTION
START_SECTION((bool hasValue() const ))
{
CVTerm term;
TEST_EQUAL(term.hasValue(), false)
term.setValue(DataValue(0.5));
TEST_EQUAL(term.hasValue(), true)
}
END_SECTION
START_SECTION((bool hasUnit() const ))
{
CVTerm term;
TEST_EQUAL(term.hasUnit(), false)
term.setUnit(CVTerm::Unit("u_acc", "u_name", "u_cv_ref"));
TEST_EQUAL(term.hasUnit(), true)
}
END_SECTION
START_SECTION((void setAccession(const String &accession)))
{
CVTerm term;
TEST_STRING_EQUAL(term.getAccession(), "")
term.setAccession("acc");
TEST_STRING_EQUAL(term.getAccession(), "acc")
}
END_SECTION
START_SECTION((const String& getAccession() const ))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((void setName(const String &name)))
{
CVTerm term;
TEST_STRING_EQUAL(term.getName(), "")
term.setName("name");
TEST_STRING_EQUAL(term.getName(), "name")
}
END_SECTION
START_SECTION((const String& getName() const ))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((void setCVIdentifierRef(const String &cv_identifier_ref)))
{
CVTerm term;
TEST_STRING_EQUAL(term.getCVIdentifierRef(), "")
term.setCVIdentifierRef("cv_id_ref");
TEST_STRING_EQUAL(term.getCVIdentifierRef(), "cv_id_ref")
}
END_SECTION
START_SECTION((const String& getCVIdentifierRef() const ))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((void setValue(const DataValue &value)))
{
CVTerm term;
TEST_EQUAL(term.getValue() == DataValue::EMPTY, true)
DataValue value(300.0);
term.setValue(value);
TEST_REAL_SIMILAR((double)term.getValue(), 300.0)
DataValue value2("bla");
term.setValue(value2);
TEST_STRING_EQUAL(term.getValue().toString(), "bla")
}
END_SECTION
START_SECTION((const DataValue& getValue() const ))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((void setUnit(const Unit &unit)))
{
CVTerm term;
TEST_STRING_EQUAL(term.getUnit().accession, "")
TEST_STRING_EQUAL(term.getUnit().name, "")
TEST_STRING_EQUAL(term.getUnit().cv_ref, "")
CVTerm::Unit unit("u_acc", "u_name", "u_cv_ref");
term.setUnit(unit);
TEST_STRING_EQUAL(term.getUnit().accession, "u_acc")
TEST_STRING_EQUAL(term.getUnit().name, "u_name")
TEST_STRING_EQUAL(term.getUnit().cv_ref, "u_cv_ref")
}
END_SECTION
START_SECTION((const Unit& getUnit() const ))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((CVTerm(const String &accession, const String &name, const String &cv_identifier_ref, const String &value, const Unit &unit)))
{
CVTerm::Unit unit("u_acc", "u_name", "u_cv_ref");
CVTerm term("acc", "name", "cv_id_ref", "value", unit);
TEST_STRING_EQUAL(term.getAccession(), "acc")
TEST_STRING_EQUAL(term.getName(), "name")
TEST_STRING_EQUAL(term.getCVIdentifierRef(), "cv_id_ref")
TEST_STRING_EQUAL(term.getValue(), "value")
TEST_STRING_EQUAL(term.getUnit().accession, "u_acc")
TEST_STRING_EQUAL(term.getUnit().name, "u_name")
TEST_STRING_EQUAL(term.getUnit().cv_ref, "u_cv_ref")
}
END_SECTION
START_SECTION((CVTerm(const CVTerm &rhs)))
{
CVTerm term1;
term1.setAccession("acc");
term1.setName("name");
term1.setCVIdentifierRef("cv_id_ref");
term1.setValue(DataValue(0.4));
term1.setUnit(CVTerm::Unit("u_acc", "u_name", "u_cv_ref"));
CVTerm term2(term1);
TEST_STRING_EQUAL(term2.getAccession(), "acc")
TEST_STRING_EQUAL(term2.getName(), "name")
TEST_STRING_EQUAL(term2.getCVIdentifierRef(), "cv_id_ref")
TEST_EQUAL(term2.getValue() == DataValue(0.4), true)
TEST_EQUAL(term2.getUnit() == CVTerm::Unit("u_acc", "u_name", "u_cv_ref"), true)
}
END_SECTION
START_SECTION((CVTerm& operator=(const CVTerm &rhs)))
{
CVTerm term1, term2;
TEST_TRUE(term1 == term2)
term1.setAccession("acc");
TEST_EQUAL(term1 == term2, false)
term2 = term1;
TEST_TRUE(term1 == term2)
term1.setName("name");
TEST_EQUAL(term1 == term2, false)
term2 = term1;
TEST_TRUE(term1 == term2)
term1.setCVIdentifierRef("cv_id_ref");
TEST_EQUAL(term1 == term2, false)
term2 = term1;
TEST_TRUE(term1 == term2)
term1.setValue(DataValue(0.4));
TEST_EQUAL(term1 == term2, false)
term2 = term1;
TEST_TRUE(term1 == term2)
term1.setUnit(CVTerm::Unit("u_acc", "u_name", "u_cv_ref"));
TEST_EQUAL(term1 == term2, false)
term2 = term1;
TEST_TRUE(term1 == term2)
}
END_SECTION
CVTerm::Unit* ptr_unit = nullptr;
CVTerm::Unit* nullPointer_unit = nullptr;
START_SECTION(([CVTerm::Unit] Unit()))
{
ptr_unit = new CVTerm::Unit();
TEST_NOT_EQUAL(ptr_unit, nullPointer_unit)
}
END_SECTION
START_SECTION(([CVTerm::Unit] Unit(const String &p_accession, const String &p_name, const String &p_cv_ref)))
{
CVTerm::Unit u("ACCESSION", "p_name", "p_cv_ref");
TEST_EQUAL(u.accession, "ACCESSION")
TEST_EQUAL(u.cv_ref, "p_cv_ref")
TEST_EQUAL(u.name, "p_name")
}
END_SECTION
START_SECTION(([CVTerm::Unit] Unit(const Unit &rhs)))
{
CVTerm::Unit u("ACCESSION", "p_name", "p_cv_ref");
TEST_EQUAL(u.accession, "ACCESSION")
TEST_EQUAL(u.cv_ref, "p_cv_ref")
TEST_EQUAL(u.name, "p_name")
CVTerm::Unit cu(u);
TEST_EQUAL(cu.accession, u.accession)
TEST_EQUAL(cu.cv_ref, u.cv_ref)
TEST_EQUAL(cu.name, u.name)
}
END_SECTION
START_SECTION(([CVTerm::Unit] virtual ~Unit()))
{
delete ptr_unit;
}
END_SECTION
START_SECTION(([CVTerm::Unit] Unit& operator=(const Unit &rhs)))
{
CVTerm::Unit u("ACCESSION", "p_name", "p_cv_ref");
TEST_EQUAL(u.accession, "ACCESSION")
TEST_EQUAL(u.cv_ref, "p_cv_ref")
TEST_EQUAL(u.name, "p_name")
CVTerm::Unit cu;
cu = u;
TEST_EQUAL(cu.accession, u.accession)
TEST_EQUAL(cu.cv_ref, u.cv_ref)
TEST_EQUAL(cu.name, u.name)
}
END_SECTION
START_SECTION(([CVTerm::Unit] bool operator==(const Unit &rhs) const ))
{
CVTerm::Unit u("ACCESSION", "p_name", "p_cv_ref");
CVTerm::Unit cu("ACCESSION", "p_name", "p_cv_ref");
CVTerm::Unit nu("ACCESSION2", "p_name", "p_cv_ref");
CVTerm::Unit nu2("ACCESSION", "p_name2", "p_cv_ref");
CVTerm::Unit nu3("ACCESSION", "p_name", "p_cv_ref2");
TEST_TRUE(u == cu)
TEST_TRUE(u == u)
TEST_EQUAL(u==nu, false)
TEST_EQUAL(u==nu2, false)
TEST_EQUAL(u==nu3, false)
TEST_EQUAL(cu==nu, false)
}
END_SECTION
START_SECTION(([CVTerm::Unit] bool operator!=(const Unit &rhs) const ))
{
CVTerm::Unit u("ACCESSION", "p_name", "p_cv_ref");
CVTerm::Unit cu("ACCESSION", "p_name", "p_cv_ref");
CVTerm::Unit nu("ACCESSION2", "p_name", "p_cv_ref");
CVTerm::Unit nu2("ACCESSION", "p_name2", "p_cv_ref");
CVTerm::Unit nu3("ACCESSION", "p_name", "p_cv_ref2");
TEST_EQUAL(u!=cu, false)
TEST_EQUAL(u!=u, false)
TEST_FALSE(u == nu)
TEST_FALSE(u == nu2)
TEST_FALSE(u == nu3)
TEST_FALSE(cu == nu)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IDFilter_test.cpp | .cpp | 34,766 | 914 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Nico Pfeifer, Mathias Walzer, Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <string>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/CHEMISTRY/ProteaseDigestion.h>
#include <OpenMS/PROCESSING/ID/IDFilter.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
///////////////////////////
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wshadow"
#endif
// must be defined up here or it won't compile:
struct IsEven
{
typedef int argument_type;
bool operator()(int i) const
{
return (i % 2 == 0);
}
} is_even;
START_TEST(IDFilter, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
// load input data
// @TODO: use an example with more than one peptide ID
vector<ProteinIdentification> global_proteins;
PeptideIdentificationList global_peptides;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDFilter_test.idXML"),
global_proteins, global_peptides);
global_peptides[0].sort(); // makes it easier to compare results
IDFilter* ptr = nullptr;
IDFilter* nullPointer = nullptr;
START_SECTION((IDFilter()))
ptr = new IDFilter();
TEST_NOT_EQUAL(ptr, nullPointer);
END_SECTION
START_SECTION((~IDFilter()))
delete ptr;
END_SECTION
START_SECTION((template <class Container, class Predicate> static void removeMatchingItems(Container& items, const Predicate& pred)))
{
vector<int> numbers(6);
for (Size i = 0; i < 6; ++i)
{
numbers[i] = i;
}
IDFilter::removeMatchingItems(numbers, is_even);
TEST_EQUAL(numbers.size(), 3);
TEST_EQUAL(numbers[0], 1);
TEST_EQUAL(numbers[1], 3);
TEST_EQUAL(numbers[2], 5);
}
END_SECTION
START_SECTION((template <class Container, class Predicate> static void keepMatchingItems(Container& items, const Predicate& pred)))
{
vector<int> numbers(6);
for (Size i = 0; i < 6; ++i)
{
numbers[i] = i;
}
IDFilter::keepMatchingItems(numbers, is_even);
TEST_EQUAL(numbers.size(), 3);
TEST_EQUAL(numbers[0], 0);
TEST_EQUAL(numbers[1], 2);
TEST_EQUAL(numbers[2], 4);
}
END_SECTION
START_SECTION((template <class IdentificationType> static Size countHits(const vector<IdentificationType>& ids)))
{
PeptideIdentificationList peptides(4);
peptides[0].getHits().resize(1);
peptides[1].getHits().resize(3);
// no hits in peptides[2]
peptides[3].getHits().resize(2);
TEST_EQUAL(IDFilter::countHits(peptides), 6);
}
END_SECTION
START_SECTION((template <class IdentificationType> static bool getBestHit(const vector<IdentificationType>& identifications, bool assume_sorted, typename IdentificationType::HitType& best_hit)))
{
PeptideIdentificationList peptides = global_peptides;
PeptideHit best_hit;
IDFilter::getBestHit(peptides, true, best_hit);
TEST_REAL_SIMILAR(best_hit.getScore(), 40);
TEST_EQUAL(best_hit.getSequence().toString(), "FINFGVNVEVLSRFQTK");
peptides[0].setHigherScoreBetter(false);
IDFilter::getBestHit(peptides, false, best_hit);
TEST_REAL_SIMILAR(best_hit.getScore(), 10);
TEST_EQUAL(best_hit.getSequence().toString(),
"MSLLSNM(Oxidation)ISIVKVGYNAR");
ProteinHit best_hit2;
IDFilter::getBestHit(global_proteins, false, best_hit2);
TEST_REAL_SIMILAR(best_hit2.getScore(), 32.3);
TEST_EQUAL(best_hit2.getAccession(), "Q824A5");
}
END_SECTION
START_SECTION((static void extractPeptideSequences(const PeptideIdentificationList& peptides, set<String>& sequences, bool ignore_mods = false)))
{
set<String> seqs;
IDFilter::extractPeptideSequences(global_peptides, seqs);
TEST_EQUAL(seqs.size(), 11);
vector<String> expected = ListUtils::create<String>("AITSDFANQAKTVLQNFK,DLEPGTDYEVTVSTLFGR,EGASTDFAALRTFLAEDGK,FINFGVNVEVLSRFQTK,LHASGITVTEIPVTATNFK,MRSLGYVAVISAVATDTDK,MSLLSNM(Oxidation)ISIVKVGYNAR,MSLLSNMISIVKVGYNAR,TGCDTWGQGTLVTVSSASTK,THPYGHAIVAGIERYPSK,TLCHHDATFDNLVWTPK");
vector<String> expected_unmodified = ListUtils::create<String>("AITSDFANQAKTVLQNFK,DLEPGTDYEVTVSTLFGR,EGASTDFAALRTFLAEDGK,FINFGVNVEVLSRFQTK,LHASGITVTEIPVTATNFK,MRSLGYVAVISAVATDTDK,MSLLSNMISIVKVGYNAR,MSLLSNMISIVKVGYNAR,TGCDTWGQGTLVTVSSASTK,THPYGHAIVAGIERYPSK,TLCHHDATFDNLVWTPK");
Size counter = 0;
for (set<String>::iterator it = seqs.begin(); it != seqs.end(); ++it,
++counter)
{
TEST_EQUAL(*it, expected[counter]);
}
seqs.clear();
IDFilter::extractPeptideSequences(global_peptides, seqs, true);
TEST_EQUAL(seqs.size(), 10);
counter = 0;
for (set<String>::iterator it = seqs.begin(); it != seqs.end(); ++it,
++counter)
{
if (counter == 6) counter++; // skip the modified sequence
TEST_EQUAL(*it, expected_unmodified[counter]);
}
}
END_SECTION
START_SECTION((class PeptideDigestionFilter::operator(PeptideHit& hit)))
{
ProteaseDigestion digestion;
digestion.setEnzyme("Trypsin");
IDFilter::PeptideDigestionFilter filter(digestion, 0, 1);
vector<PeptideHit>hits, test_hits;
// No cleavage
hits.push_back(PeptideHit(0, 0, 0, AASequence::fromString("(MOD:00051)DFPIANGER")));
hits.push_back(PeptideHit(0, 0, 0, AASequence::fromString("DFPIANGER")));
hits.push_back(PeptideHit(0, 0, 0, AASequence::fromString("DFPIAN(Deamidated)GER")));
// 1 - missed cleavage exception K before P
hits.push_back(PeptideHit(0, 0, 0, AASequence::fromString("DFKPIARN(Deamidated)GER")));
// 2 missed cleavages
hits.push_back(PeptideHit(0, 0, 0, AASequence::fromString("(MOD:00051)DFPKIARNGER")));
hits.push_back(PeptideHit(0, 0, 0, AASequence::fromString("DFPKIARNGER")));
test_hits = hits;
filter.filterPeptideSequences(test_hits);
TEST_EQUAL(test_hits.size(), 4);
for (UInt i = 0; i < test_hits.size(); i++)
{
TEST_EQUAL(test_hits[i].getSequence(), hits[i].getSequence());
}
IDFilter::PeptideDigestionFilter filter2(digestion, 0, 2);
test_hits = hits;
filter2.filterPeptideSequences(test_hits);
TEST_EQUAL(test_hits.size(), hits.size());
for (UInt i = 0; i < test_hits.size(); i++)
{
TEST_EQUAL(test_hits[i].getSequence(), hits[i].getSequence());
}
// Removing sequences
hits.clear();
hits.push_back(PeptideHit(0, 0, 0, AASequence::fromString("K(Dimethyl)FPIAUGR")));
test_hits = hits;
digestion.setEnzyme("Asp-N_ambic");
//Should have exactly zero missed cleavages
IDFilter::PeptideDigestionFilter filter3(digestion, 0, 0);
filter3.filterPeptideSequences(test_hits);
TEST_EQUAL(test_hits.size(), hits.size());
for (UInt i = 0; i < test_hits.size(); i++)
{
TEST_EQUAL(test_hits[i].getSequence(), hits[i].getSequence());
}
}
END_SECTION
START_SECTION((static void removeUnreferencedProteins(vector<ProteinIdentification>& proteins, PeptideIdentificationList& peptides)))
{
vector<ProteinIdentification> proteins;
PeptideIdentificationList peptides;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDFilter_test4.idXML"),
proteins, peptides);
IDFilter::removeUnreferencedProteins(proteins, peptides);
vector<ProteinHit>& hits = proteins[0].getHits();
TEST_EQUAL(hits.size(), 3);
TEST_EQUAL(hits[0].getAccession(), "Q824A5");
TEST_EQUAL(hits[1].getAccession(), "S53854");
TEST_EQUAL(hits[2].getAccession(), "Q872T5");
}
END_SECTION
START_SECTION((static void removeDanglingProteinReferences(PeptideIdentificationList& peptides, const vector<ProteinIdentification>& proteins, bool remove_peptides_without_reference = false)))
{
vector<ProteinIdentification> proteins = global_proteins;
PeptideIdentificationList peptides = global_peptides;
vector<PeptideHit>& peptide_hits = peptides[0].getHits();
// create a peptide hit that matches to two proteins:
peptide_hits[3].addPeptideEvidence(peptide_hits[4].getPeptideEvidences()[0]);
TEST_EQUAL(peptide_hits[3].getPeptideEvidences().size(), 2);
TEST_EQUAL(peptide_hits[4].getPeptideEvidences().size(), 1);
proteins[0].getHits().resize(2);
IDFilter::removeDanglingProteinReferences(peptides, proteins);
TEST_EQUAL(peptide_hits.size(), 11);
for (Size i = 0; i < peptide_hits.size(); ++i)
{
if ((i == 3) || (i == 4))
{
TEST_EQUAL(peptide_hits[i].getPeptideEvidences().size(), 1);
TEST_EQUAL(peptide_hits[i].getPeptideEvidences()[0].
getProteinAccession(), "Q824A5");
}
else
{
TEST_EQUAL(peptide_hits[i].getPeptideEvidences().size(), 0);
}
}
// remove peptide hits without any reference to an existing proteins:
IDFilter::removeDanglingProteinReferences(peptides, proteins, true);
TEST_EQUAL(peptide_hits.size(), 2);
}
END_SECTION
START_SECTION((bool updateProteinGroups(vector<ProteinIdentification::ProteinGroup>& groups, const vector<ProteinHit>& hits)))
{
vector<ProteinIdentification::ProteinGroup> groups(2);
groups[0].accessions.push_back("A");
groups[0].probability = 0.1;
groups[1].accessions.push_back("B");
groups[1].accessions.push_back("C");
groups[1].probability = 0.2;
vector<ProteinHit> hits(3);
hits[0].setAccession("C");
hits[1].setAccession("B");
hits[2].setAccession("A");
vector<ProteinIdentification::ProteinGroup> groups_copy = groups;
// no protein to remove:
bool valid = IDFilter::updateProteinGroups(groups_copy, hits);
TEST_EQUAL(valid, true);
TEST_EQUAL(groups_copy.size(), 2);
TEST_TRUE(groups_copy == groups);
// remove full protein group:
hits.pop_back();
valid = IDFilter::updateProteinGroups(groups_copy, hits);
TEST_EQUAL(valid, true);
TEST_EQUAL(groups_copy.size(), 1);
TEST_EQUAL(groups_copy[0].accessions.size(), 2);
TEST_EQUAL(groups_copy[0].accessions[0], "B");
TEST_EQUAL(groups_copy[0].accessions[1], "C");
TEST_EQUAL(groups_copy[0].probability, 0.2);
// remove part of a protein group:
hits.pop_back();
valid = IDFilter::updateProteinGroups(groups_copy, hits);
TEST_EQUAL(valid, false);
TEST_EQUAL(groups_copy.size(), 1);
TEST_EQUAL(groups_copy[0].accessions.size(), 1);
TEST_EQUAL(groups_copy[0].accessions[0], "C");
TEST_EQUAL(groups_copy[0].probability, 0.2);
}
END_SECTION
START_SECTION((template <class IdentificationType> static void removeEmptyIdentifications(vector<IdentificationType>& ids)))
{
vector<ProteinIdentification> proteins(2);
proteins[1].getHits().resize(1);
IDFilter::removeEmptyIdentifications(proteins);
TEST_EQUAL(proteins.size(), 1);
TEST_EQUAL(proteins[0].getHits().size(), 1);
PeptideIdentificationList peptides(2);
peptides[0].getHits().resize(1);
IDFilter::removeEmptyIdentifications(peptides);
TEST_EQUAL(peptides.size(), 1);
TEST_EQUAL(peptides[0].getHits().size(), 1);
}
END_SECTION
START_SECTION((template <class IdentificationType> static void filterHitsByScore(vector<IdentificationType>& ids, double threshold_score)))
{
PeptideIdentificationList peptides = global_peptides;
vector<PeptideHit>& peptide_hits = peptides[0].getHits();
TEST_EQUAL(peptide_hits.size(), 11);
IDFilter::filterHitsByScore(peptides, 33);
TEST_EQUAL(peptide_hits.size(), 5);
TEST_REAL_SIMILAR(peptide_hits[0].getScore(), 40);
TEST_EQUAL(peptide_hits[0].getSequence().toString(),
"FINFGVNVEVLSRFQTK");
TEST_REAL_SIMILAR(peptide_hits[1].getScore(), 40);
TEST_EQUAL(peptide_hits[1].getSequence().toString(),
"MSLLSNMISIVKVGYNAR");
TEST_REAL_SIMILAR(peptide_hits[2].getScore(), 39);
TEST_EQUAL(peptide_hits[2].getSequence().toString(),
"THPYGHAIVAGIERYPSK");
TEST_REAL_SIMILAR(peptide_hits[3].getScore(), 34.85);
TEST_EQUAL(peptide_hits[3].getSequence().toString(),
"LHASGITVTEIPVTATNFK");
TEST_REAL_SIMILAR(peptide_hits[4].getScore(), 33.85);
TEST_EQUAL(peptide_hits[4].getSequence().toString(),
"MRSLGYVAVISAVATDTDK");
IDFilter::filterHitsByScore(peptides, 41);
TEST_EQUAL(peptides[0].getScoreType(), "Mascot");
TEST_EQUAL(peptide_hits.size(), 0);
}
END_SECTION
START_SECTION((template <class IdentificationType> static void keepNBestHits(vector<IdentificationType>& ids, Size n)))
{
PeptideIdentificationList peptides = global_peptides;
vector<PeptideHit>& peptide_hits = peptides[0].getHits();
IDFilter::keepNBestHits(peptides, 3);
TEST_EQUAL(peptides[0].getScoreType(), "Mascot");
TEST_EQUAL(peptide_hits.size(), 3);
TEST_REAL_SIMILAR(peptide_hits[0].getScore(), 40);
TEST_EQUAL(peptide_hits[0].getSequence().toString(),
"FINFGVNVEVLSRFQTK");
TEST_REAL_SIMILAR(peptide_hits[1].getScore(), 40);
TEST_EQUAL(peptide_hits[1].getSequence().toString(),
"MSLLSNMISIVKVGYNAR");
TEST_REAL_SIMILAR(peptide_hits[2].getScore(), 39);
TEST_EQUAL(peptide_hits[2].getSequence().toString(),
"THPYGHAIVAGIERYPSK");
}
END_SECTION
START_SECTION((template <class IdentificationType> static void filterHitsByRank(vector<IdentificationType>& ids, Size min_rank, Size max_rank)))
{
vector<ProteinIdentification> proteins = global_proteins;
PeptideIdentificationList peptides = global_peptides;
IDFilter::filterHitsByRank(peptides, 1, 5);
TEST_EQUAL(peptides[0].getHits().size(), 6); // two rank 1 hits (same score)
IDFilter::filterHitsByRank(proteins, 3, 10);
TEST_EQUAL(proteins[0].getHits().size(), 2);
}
END_SECTION
START_SECTION((template <class IdentificationType> static void removeDecoyHits(vector<IdentificationType>& ids)))
{
vector<ProteinIdentification> proteins(1);
proteins[0].getHits().resize(5);
proteins[0].getHits()[0].setMetaValue("target_decoy", "target");
proteins[0].getHits()[1].setMetaValue("target_decoy", "decoy");
// no meta value on hit 2
proteins[0].getHits()[3].setMetaValue("isDecoy", "true");
proteins[0].getHits()[4].setMetaValue("isDecoy", "false");
IDFilter::removeDecoyHits(proteins);
TEST_EQUAL(proteins[0].getHits().size(), 3);
TEST_EQUAL(proteins[0].getHits()[0].getMetaValue("target_decoy"),
"target");
TEST_EQUAL(proteins[0].getHits()[1].metaValueExists("target_decoy"), false);
TEST_EQUAL(proteins[0].getHits()[1].metaValueExists("isDecoy"), false);
TEST_EQUAL(proteins[0].getHits()[2].getMetaValue("isDecoy"), "false");
PeptideIdentificationList peptides(1);
peptides[0].getHits().resize(6);
peptides[0].getHits()[0].setMetaValue("target_decoy", "target");
peptides[0].getHits()[1].setMetaValue("target_decoy", "decoy");
peptides[0].getHits()[2].setMetaValue("target_decoy", "target+decoy");
// no meta value on hit 3
peptides[0].getHits()[4].setMetaValue("isDecoy", "true");
peptides[0].getHits()[5].setMetaValue("isDecoy", "false");
IDFilter::removeDecoyHits(peptides);
TEST_EQUAL(peptides[0].getHits().size(), 4);
TEST_EQUAL(peptides[0].getHits()[0].getMetaValue("target_decoy"),
"target");
TEST_EQUAL(peptides[0].getHits()[1].getMetaValue("target_decoy"),
"target+decoy");
TEST_EQUAL(peptides[0].getHits()[2].metaValueExists("target_decoy"), false);
TEST_EQUAL(peptides[0].getHits()[2].metaValueExists("isDecoy"), false);
TEST_EQUAL(peptides[0].getHits()[3].getMetaValue("isDecoy"), "false");
}
END_SECTION
START_SECTION((template <class IdentificationType> static void removeHitsMatchingProteins(vector<IdentificationType>& ids, const set<String> accessions)))
{
set<String> accessions;
accessions.insert("Q824A5");
accessions.insert("Q872T5");
vector<ProteinIdentification> proteins = global_proteins;
IDFilter::removeHitsMatchingProteins(proteins, accessions);
TEST_EQUAL(proteins[0].getScoreType(), "Mascot");
TEST_EQUAL(proteins[0].getHits().size(), 2);
TEST_EQUAL(proteins[0].getHits()[0].getAccession(), "AAD30739");
TEST_EQUAL(proteins[0].getHits()[1].getAccession(), "S53854");
PeptideIdentificationList peptides = global_peptides;
IDFilter::removeHitsMatchingProteins(peptides, accessions);
TEST_EQUAL(peptides[0].getScoreType(), "Mascot");
TEST_EQUAL(peptides[0].getHits().size(), 9);
// check some examples:
TEST_EQUAL(peptides[0].getHits()[0].getSequence().toString(),
"FINFGVNVEVLSRFQTK");
TEST_EQUAL(peptides[0].getHits()[3].getSequence().toString(),
"EGASTDFAALRTFLAEDGK");
TEST_EQUAL(peptides[0].getHits()[8].getSequence().toString(),
"MSLLSNM(Oxidation)ISIVKVGYNAR");
}
END_SECTION
START_SECTION((template <class IdentificationType> static void keepHitsMatchingProteins(vector<IdentificationType>& ids, const set<String> accessions)))
{
set<String> accessions;
accessions.insert("Q824A5");
accessions.insert("Q872T5");
vector<ProteinIdentification> proteins = global_proteins;
IDFilter::keepHitsMatchingProteins(proteins, accessions);
TEST_EQUAL(proteins[0].getScoreType(), "Mascot");
TEST_EQUAL(proteins[0].getHits().size(), 2);
TEST_EQUAL(proteins[0].getHits()[0].getAccession(), "Q824A5");
TEST_EQUAL(proteins[0].getHits()[1].getAccession(), "Q872T5");
PeptideIdentificationList peptides = global_peptides;
IDFilter::keepHitsMatchingProteins(peptides, accessions);
TEST_EQUAL(peptides[0].getScoreType(), "Mascot");
TEST_EQUAL(peptides[0].getHits().size(), 2);
TEST_EQUAL(peptides[0].getHits()[0].getSequence().toString(),
"LHASGITVTEIPVTATNFK");
TEST_EQUAL(peptides[0].getHits()[1].getSequence().toString(),
"MRSLGYVAVISAVATDTDK");
}
END_SECTION
START_SECTION((static void keepBestPeptideHits(PeptideIdentificationList& peptides, bool strict = false)))
{
PeptideIdentificationList peptides = global_peptides;
vector<PeptideHit>& peptide_hits = peptides[0].getHits();
// not strict:
IDFilter::keepBestPeptideHits(peptides);
TEST_EQUAL(peptides[0].getScoreType(), "Mascot");
TEST_EQUAL(peptide_hits.size(), 2);
TEST_REAL_SIMILAR(peptide_hits[0].getScore(), 40);
TEST_EQUAL(peptide_hits[0].getSequence().toString(),
"FINFGVNVEVLSRFQTK");
TEST_REAL_SIMILAR(peptide_hits[1].getScore(), 40);
TEST_EQUAL(peptide_hits[1].getSequence().toString(),
"MSLLSNMISIVKVGYNAR");
// strict:
IDFilter::keepBestPeptideHits(peptides, true);
TEST_EQUAL(peptides[0].getScoreType(), "Mascot");
TEST_EQUAL(peptide_hits.size(), 0);
}
END_SECTION
START_SECTION((static void filterPeptidesByLength(PeptideIdentificationList& peptides, Size min_length, Size max_length = UINT_MAX)))
{
PeptideIdentificationList peptides = global_peptides;
AASequence eighter = AASequence::fromString("OKTAMERR");
AASequence niner = AASequence::fromString("NONAMERRR");
AASequence tener = AASequence::fromString("DECAMERRRR");
peptides[0].insertHit(PeptideHit(99.99, 1, 2, eighter));
peptides[0].insertHit(PeptideHit(99.99, 1, 2, niner));
peptides[0].insertHit(PeptideHit(99.99, 1, 2, tener));
TEST_EQUAL(peptides[0].getHits().size(), 14);
PeptideIdentificationList peptides2 = peptides;
vector<PeptideHit>& peptide_hits = peptides2[0].getHits();
IDFilter::filterPeptidesByLength(peptides2, 10);
TEST_EQUAL(peptide_hits.size(), 12)
for (Size i = 0; i < peptide_hits.size(); ++i)
{
TEST_EQUAL(peptide_hits[i].getSequence().size() >= 10, true);
}
peptides2 = peptides;
IDFilter::filterPeptidesByLength(peptides2, 9, 10);
TEST_EQUAL(peptide_hits.size(), 2);
for (Size i = 0; i < peptide_hits.size(); ++i)
{
TEST_EQUAL(peptide_hits[i].getSequence().size() >= 9, true);
TEST_EQUAL(peptide_hits[i].getSequence().size() <= 10, true);
}
peptides2 = peptides;
IDFilter::filterPeptidesByLength(peptides2, 9, 8);
TEST_EQUAL(peptide_hits.size(), 13)
for (Size i = 0; i < peptide_hits.size(); ++i)
{
TEST_EQUAL(peptide_hits[i].getSequence().size() >= 9, true);
}
}
END_SECTION
START_SECTION((static void filterPeptidesByCharge(PeptideIdentificationList& peptides, Size min_charge, Size max_charge)))
{
PeptideIdentificationList peptides = global_peptides;
vector<PeptideHit>& hits = peptides[0].getHits();
hits[3].setCharge(3);
hits[4].setCharge(4);
hits[6].setCharge(3);
hits[8].setCharge(1);
hits[10].setCharge(5);
IDFilter::filterPeptidesByCharge(peptides, 3, 4);
TEST_EQUAL(hits.size(), 3);
TEST_EQUAL(hits[0].getCharge(), 3);
TEST_EQUAL(hits[1].getCharge(), 4);
TEST_EQUAL(hits[2].getCharge(), 3);
}
END_SECTION
START_SECTION((static void filterPeptidesByRT(PeptideIdentificationList& peptides, double min_rt, double max_rt)))
{
PeptideIdentificationList peptides(5);
peptides[1].setRT(1);
peptides[2].setRT(2);
peptides[3].setRT(2.5);
peptides[4].setRT(1.5);
IDFilter::filterPeptidesByRT(peptides, 1.0, 1.9);
TEST_EQUAL(peptides.size(), 2);
TEST_EQUAL(peptides[0].getRT(), 1.0);
TEST_EQUAL(peptides[1].getRT(), 1.5);
}
END_SECTION
START_SECTION((static void filterPeptidesByMZ(PeptideIdentificationList& peptides, double min_mz, double max_mz)))
{
PeptideIdentificationList peptides(5);
peptides[1].setMZ(111.1);
peptides[2].setMZ(222.2);
peptides[3].setMZ(225.5);
peptides[4].setMZ(115.5);
IDFilter::filterPeptidesByMZ(peptides, 112.0, 223.3);
TEST_EQUAL(peptides.size(), 2);
TEST_EQUAL(peptides[0].getMZ(), 222.2);
TEST_EQUAL(peptides[1].getMZ(), 115.5);
}
END_SECTION
START_SECTION((static void filterPeptidesByMZError(PeptideIdentificationList& peptides, double mass_error, bool unit_ppm)))
{
PeptideIdentificationList peptides = global_peptides;
peptides[0].setMZ(1000.0);
IDFilter::filterPeptidesByMZError(peptides, 1, false); // in Da
TEST_EQUAL(peptides[0].getHits().size(), 7);
for (vector<PeptideHit>::iterator it = peptides[0].getHits().begin();
it != peptides[0].getHits().end(); ++it)
{
double mz = it->getSequence().getMonoWeight(Residue::Full, 2) / 2.0;
TEST_EQUAL((mz >= 999.0) && (mz <= 1001.0), true);
}
IDFilter::filterPeptidesByMZError(peptides, 100.0, true); // in PPM
TEST_EQUAL(peptides[0].getHits().size(), 4);
}
END_SECTION
START_SECTION((static void filterPeptidesByRTPredictPValue(PeptideIdentificationList& peptides, const String& metavalue_key, double threshold = 0.05)))
{
vector<ProteinIdentification> proteins;
PeptideIdentificationList peptides;
{ // RT prediction:
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDFilter_test2.idXML"),
proteins, peptides);
IDFilter::filterPeptidesByRTPredictPValue(peptides, "predicted_RT_p_value",
0.08);
vector<PeptideHit>& hits = peptides[0].getHits();
TEST_EQUAL(hits.size(), 4);
TEST_EQUAL(hits[0].getSequence().toString(), "LHASGITVTEIPVTATNFK");
TEST_EQUAL(hits[1].getSequence().toString(), "DLEPGTDYEVTVSTLFGR");
TEST_EQUAL(hits[2].getSequence().toString(), "FINFGVNVEVLSRFQTK");
TEST_EQUAL(hits[3].getSequence().toString(), "MSLLSNMISIVKVGYNAR");
}
{ // first dim. RT prediction:
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDFilter_test3.idXML"),
proteins, peptides);
IDFilter::filterPeptidesByRTPredictPValue(peptides,
"predicted_RT_p_value_first_dim",
0.08);
vector<PeptideHit>& hits = peptides[0].getHits();
TEST_EQUAL(hits.size(), 4);
TEST_EQUAL(hits[0].getSequence().toString(), "LHASGITVTEIPVTATNFK");
TEST_EQUAL(hits[1].getSequence().toString(), "DLEPGTDYEVTVSTLFGR");
TEST_EQUAL(hits[2].getSequence().toString(), "FINFGVNVEVLSRFQTK");
TEST_EQUAL(hits[3].getSequence().toString(), "MSLLSNMISIVKVGYNAR");
}
}
END_SECTION
START_SECTION((static void removePeptidesWithMatchingModifications(PeptideIdentificationList& peptides, const set<String>& modifications)))
{
PeptideIdentificationList peptides = global_peptides;
set<String> mods;
mods.insert("Carbamidomethyl (C)"); // not present in the data
IDFilter::removePeptidesWithMatchingModifications(peptides, mods);
TEST_TRUE(peptides == global_peptides); // no changes
mods.clear(); // filter any mod.
IDFilter::removePeptidesWithMatchingModifications(peptides, mods);
TEST_EQUAL(peptides[0].getHits().size(), 10);
for (vector<PeptideHit>::iterator it = peptides[0].getHits().begin();
it != peptides[0].getHits().end(); ++it)
{
TEST_EQUAL(it->getSequence().isModified(), false);
}
peptides = global_peptides;
mods.insert("Oxidation (M)"); // present in the data
IDFilter::removePeptidesWithMatchingModifications(peptides, mods);
TEST_EQUAL(peptides[0].getHits().size(), 10);
for (vector<PeptideHit>::iterator it = peptides[0].getHits().begin();
it != peptides[0].getHits().end(); ++it)
{
TEST_EQUAL(it->getSequence().isModified(), false);
}
}
END_SECTION
START_SECTION((static void removePeptidesWithMatchingRegEx(PeptideIdentificationList& peptides, const String& regex)))
{
PeptideIdentificationList peptides = global_peptides;
String re{"[BJXZ]"};
IDFilter::removePeptidesWithMatchingRegEx(peptides, re);
TEST_TRUE(peptides == global_peptides); // no changes
PeptideHit aaa_hit1;
aaa_hit1.setSequence(AASequence::fromString("BBBBB"));
PeptideHit aaa_hit2;
aaa_hit2.setSequence(AASequence::fromString("JJJJJ"));
PeptideHit aaa_hit3;
aaa_hit3.setSequence(AASequence::fromString("XXXXX"));
peptides[0].getHits().push_back(aaa_hit1);
peptides[0].getHits().push_back(aaa_hit2);
peptides[0].getHits().push_back(aaa_hit3);
TEST_EQUAL(peptides == global_peptides, false); // added aaa peptides
TEST_EQUAL(peptides[0].getHits().size(), 14);
IDFilter::removePeptidesWithMatchingRegEx(peptides, re);
/// aaa peptides should now be removed
TEST_TRUE(peptides == global_peptides);
TEST_EQUAL(peptides[0].getHits().size(), 11);
}
END_SECTION
START_SECTION((static void keepPeptidesWithMatchingModifications(PeptideIdentificationList& peptides, const set<String>& modifications)))
{
PeptideIdentificationList peptides = global_peptides;
set<String> mods;
mods.insert("Oxidation (M)");
IDFilter::keepPeptidesWithMatchingModifications(peptides, mods);
TEST_EQUAL(peptides[0].getHits().size(), 1);
TEST_EQUAL(peptides[0].getHits()[0].getSequence().toString(),
"MSLLSNM(Oxidation)ISIVKVGYNAR");
// terminal mods:
AASequence seq = AASequence::fromString("(Acetyl)PEPTIDER.(Arg-loss)");
peptides[0].getHits().resize(2);
peptides[0].getHits()[1].setSequence(seq);
mods.insert("Acetyl (N-term)");
IDFilter::keepPeptidesWithMatchingModifications(peptides, mods);
TEST_EQUAL(peptides[0].getHits().size(), 2);
mods.clear();
mods.insert("Arg-loss (C-term R)");
IDFilter::keepPeptidesWithMatchingModifications(peptides, mods);
TEST_EQUAL(peptides[0].getHits().size(), 1);
// mod. not present in the data:
mods.clear();
mods.insert("Carbamidomethyl (C)");
IDFilter::keepPeptidesWithMatchingModifications(peptides, mods);
TEST_EQUAL(peptides[0].getHits().size(), 0);
}
END_SECTION
START_SECTION((static void removePeptidesWithMatchingSequences(PeptideIdentificationList& peptides, const PeptideIdentificationList& bad_peptides, bool ignore_mods = false)))
{
PeptideIdentificationList peptides = global_peptides;
vector<PeptideHit>& peptide_hits = peptides[0].getHits();
PeptideIdentificationList bad_peptides(1);
vector<PeptideHit>& bad_hits = bad_peptides[0].getHits();
bad_hits.resize(8);
bad_hits[0].setSequence(AASequence::fromString("LHASGITVTEIPVTATNFK"));
bad_hits[1].setSequence(AASequence::fromString("MRSLGYVAVISAVATDTDK"));
bad_hits[2].setSequence(AASequence::fromString("EGASTDFAALRTFLAEDGK"));
bad_hits[3].setSequence(AASequence::fromString("DLEPGTDYEVTVSTLFGR"));
bad_hits[4].setSequence(AASequence::fromString("FINFGVNVEVLSRFQTK"));
bad_hits[5].setSequence(AASequence::fromString("MSLLSNMISIVKVGYNAR"));
bad_hits[6].setSequence(AASequence::fromString("THPYGHAIVAGIERYPSK"));
bad_hits[7].setSequence(AASequence::fromString("AITSDFANQAKTVLQNFK"));
// modification-aware filtering:
IDFilter::removePeptidesWithMatchingSequences(peptides, bad_peptides, false);
TEST_EQUAL(peptides[0].getScoreType(), "Mascot");
TEST_EQUAL(peptide_hits.size(), 3);
TEST_EQUAL(peptide_hits[0].getSequence(),
AASequence::fromString("TGCDTWGQGTLVTVSSASTK"));
TEST_REAL_SIMILAR(peptide_hits[0].getScore(), 10.93);
TEST_EQUAL(peptide_hits[1].getSequence(),
AASequence::fromString("TLCHHDATFDNLVWTPK"));
TEST_REAL_SIMILAR(peptide_hits[1].getScore(), 10.37);
TEST_EQUAL(peptide_hits[2].getSequence(),
AASequence::fromString("MSLLSNM(Oxidation)ISIVKVGYNAR"));
TEST_REAL_SIMILAR(peptide_hits[2].getScore(), 10);
// modification-unaware filtering:
IDFilter::removePeptidesWithMatchingSequences(peptides, bad_peptides, true);
TEST_EQUAL(peptides[0].getScoreType(), "Mascot");
TEST_EQUAL(peptide_hits.size(), 2);
TEST_EQUAL(peptide_hits[0].getSequence().toString(),
"TGCDTWGQGTLVTVSSASTK");
TEST_REAL_SIMILAR(peptide_hits[0].getScore(), 10.93);
TEST_EQUAL(peptide_hits[1].getSequence().toString(),
"TLCHHDATFDNLVWTPK");
TEST_REAL_SIMILAR(peptide_hits[1].getScore(), 10.37);
}
END_SECTION
START_SECTION((static void keepPeptidesWithMatchingSequences(PeptideIdentificationList& peptides, const PeptideIdentificationList& good_peptides, bool ignore_mods = false)))
{
PeptideIdentificationList peptides = global_peptides;
vector<PeptideHit>& peptide_hits = peptides[0].getHits();
PeptideIdentificationList good_peptides(1);
vector<PeptideHit>& good_hits = good_peptides[0].getHits();
good_hits.resize(3);
good_hits[0].setSequence(AASequence::fromString("TGCDTWGQGTLVTVSSASTK"));
good_hits[1].setSequence(AASequence::fromString("TLCHHDATFDNLVWTPK"));
good_hits[2].setSequence(AASequence::fromString("MSLLSNM(Oxidation)ISIVKVGYNAR"));
// modification-unaware filtering:
IDFilter::keepPeptidesWithMatchingSequences(peptides, good_peptides, true);
TEST_EQUAL(peptides[0].getScoreType(), "Mascot");
TEST_EQUAL(peptide_hits.size(), 4);
TEST_EQUAL(peptide_hits[0].getSequence().toString(),
"MSLLSNMISIVKVGYNAR");
TEST_REAL_SIMILAR(peptide_hits[0].getScore(), 40);
TEST_EQUAL(peptide_hits[1].getSequence().toString(),
"TGCDTWGQGTLVTVSSASTK");
TEST_REAL_SIMILAR(peptide_hits[1].getScore(), 10.93);
TEST_EQUAL(peptide_hits[2].getSequence().toString(),
"TLCHHDATFDNLVWTPK");
TEST_REAL_SIMILAR(peptide_hits[2].getScore(), 10.37);
TEST_EQUAL(peptide_hits[3].getSequence().toString(),
"MSLLSNM(Oxidation)ISIVKVGYNAR");
TEST_REAL_SIMILAR(peptide_hits[3].getScore(), 10);
// modification-aware filtering:
IDFilter::keepPeptidesWithMatchingSequences(peptides, good_peptides, false);
TEST_EQUAL(peptides[0].getScoreType(), "Mascot");
TEST_EQUAL(peptide_hits.size(), 3);
TEST_EQUAL(peptide_hits[0].getSequence().toString(),
"TGCDTWGQGTLVTVSSASTK");
TEST_REAL_SIMILAR(peptide_hits[0].getScore(), 10.93);
TEST_EQUAL(peptide_hits[1].getSequence().toString(),
"TLCHHDATFDNLVWTPK");
TEST_REAL_SIMILAR(peptide_hits[1].getScore(), 10.37);
TEST_EQUAL(peptide_hits[2].getSequence().toString(),
"MSLLSNM(Oxidation)ISIVKVGYNAR");
TEST_REAL_SIMILAR(peptide_hits[2].getScore(), 10);
}
END_SECTION
START_SECTION((static void keepUniquePeptidesPerProtein(PeptideIdentificationList& peptides)))
{
PeptideIdentificationList peptides(1);
vector<PeptideHit>& hits = peptides[0].getHits();
hits.resize(4);
hits[0].setMetaValue("protein_references", "non-unique");
hits[1].setMetaValue("protein_references", "unmatched");
// no meta value for hit 2
hits[3].setMetaValue("protein_references", "unique");
IDFilter::keepUniquePeptidesPerProtein(peptides);
TEST_EQUAL(hits.size(), 1);
TEST_EQUAL(hits[0].getMetaValue("protein_references"), "unique");
}
END_SECTION
START_SECTION((static void removeDuplicatePeptideHits(PeptideIdentificationList& peptides, bool seq_only)))
{
PeptideIdentificationList peptides(1, global_peptides[0]);
vector<PeptideHit>& hits = peptides[0].getHits();
hits.clear();
PeptideHit hit;
hit.setSequence(AASequence::fromString("DFPIANGER"));
hit.setCharge(1);
hit.setScore(0.3);
hits.push_back(hit);
hit.setCharge(2);
hits.push_back(hit);
hit.setScore(0.5);
hits.push_back(hit);
hit.setSequence(AASequence::fromString("DFPIANGEK"));
hits.push_back(hit);
hits.push_back(hit);
hits.push_back(hit);
hit.setCharge(5);
hits.push_back(hit);
TEST_EQUAL(hits.size(), 7);
IDFilter::removeDuplicatePeptideHits(peptides);
TEST_EQUAL(hits.size(), 5);
TEST_EQUAL(hits[3].getSequence().toString(), "DFPIANGEK");
TEST_EQUAL(hits[3].getCharge(), 2);
TEST_EQUAL(hits[4].getSequence().toString(), "DFPIANGEK");
TEST_EQUAL(hits[4].getCharge(), 5);
IDFilter::removeDuplicatePeptideHits(peptides, true);
TEST_EQUAL(hits.size(), 2);
TEST_EQUAL(hits[0].getSequence().toString(), "DFPIANGER");
TEST_EQUAL(hits[0].getScore(), 0.3);
TEST_EQUAL(hits[1].getSequence().toString(), "DFPIANGEK");
}
END_SECTION
START_SECTION((static void keepNBestSpectra(PeptideIdentificationList& peptides, Size n)))
{
vector<ProteinIdentification> proteins;
PeptideIdentificationList peptides;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDFilter_test5.idXML"),
proteins, peptides);
cout << peptides[0].getHits()[0].getSequence().toString() << endl;
cout << peptides[1].getHits()[0].getSequence().toString() << endl;
IDFilter::keepNBestSpectra(peptides, 2); // keep best two spectra (those with best hits)
TEST_EQUAL(peptides.size(), 2);
vector<PeptideHit> peptide_hits = peptides[0].getHits();
TEST_EQUAL(peptide_hits.size(), 2);
peptide_hits = peptides[1].getHits();
TEST_EQUAL(peptide_hits.size(), 2);
cout << peptides[0].getHits()[0].getSequence().toString() << endl;
cout << peptides[1].getHits()[0].getSequence().toString() << endl;
TEST_REAL_SIMILAR(peptides[0].getHits()[0].getScore(), 1000);
TEST_REAL_SIMILAR(peptides[1].getHits()[0].getScore(), 40);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
#ifdef __clang__
#pragma clang diagnostic pop
#endif | C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ClusterHierarchical_test.cpp | .cpp | 5,820 | 269 | // 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/ClusterHierarchical.h>
#include <OpenMS/ML/CLUSTERING/SingleLinkage.h>
#include <OpenMS/KERNEL/BinnedSpectrum.h>
#include <OpenMS/COMPARISON/BinnedSharedPeakCount.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/FORMAT/DTAFile.h>
#include <vector>
#include <algorithm>
///////////////////////////
using namespace OpenMS;
using namespace std;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#endif
class LowlevelComparator
{
public:
double operator()(const Size first, const Size second) const
{
Size x,y;
x = min(second,first);
y = max(first,second);
switch (x)
{
case 0:
switch(y)
{
default:
return 0;
break;
case 1:
return 1-0.5;
break;
case 2:
return 1-0.8;
break;
case 3:
return 1-0.6;
break;
case 4:
return 1-0.8;
break;
case 5:
return 1-0.7;
break;
}
break;
case 1:
switch(y)
{
default:
return 0;
break;
case 2:
return 1-0.3;
break;
case 3:
return 1-0.8;
break;
case 4:
return 1-0.8;
break;
case 5:
return 1-0.8;
break;
}
break;
case 2:
switch(y)
{
default:
return 0;
break;
case 3:
return 1-0.8;
break;
case 4:
return 1-0.8;
break;
case 5:
return 1-0.8;
break;
}
break;
case 3:
switch(y)
{
default:
return 0;
break;
case 4:
return 1-0.4;
break;
case 5:
return 1-0.8;
break;
}
break;
case 4:
switch(y)
{
default:
return 0;
break;
case 5:
return 1-0.8;
break;
}
break;
default:
return 666;
break;
}
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
START_TEST(ClusterHierarchical, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
ClusterHierarchical* ptr = nullptr;
ClusterHierarchical* nullPointer = nullptr;
START_SECTION(ClusterHierarchical())
{
ptr = new ClusterHierarchical();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~ClusterHierarchical())
{
delete ptr;
}
END_SECTION
START_SECTION((ClusterHierarchical(const ClusterHierarchical &source)))
{
ClusterHierarchical ch;
ch.setThreshold(66.6);
ClusterHierarchical copy(ch);
TEST_EQUAL(copy.getThreshold(), 66.6);
}
END_SECTION
START_SECTION((double getThreshold()))
{
ClusterHierarchical ch;
ch.setThreshold(0.666);
TEST_EQUAL(ch.getThreshold(),0.666);
}
END_SECTION
START_SECTION((void setThreshold(double x)))
{
ClusterHierarchical ch;
ch.setThreshold(0.666);
TEST_EQUAL(ch.getThreshold(),0.666);
}
END_SECTION
START_SECTION((template <typename Data, typename SimilarityComparator> void cluster(std::vector< Data > &data, const SimilarityComparator &comparator, const ClusterFunctor &clusterer, std::vector<BinaryTreeNode>& cluster_tree, DistanceMatrix<float>& original_distance)))
{
vector<Size> d(6,0);
for (Size i = 0; i<d.size(); ++i)
{
d[i]=i;
}
ClusterHierarchical ch;
LowlevelComparator lc;
SingleLinkage sl;
vector< BinaryTreeNode > result;
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));
DistanceMatrix<float> matrix;
ch.cluster<Size,LowlevelComparator>(d,lc,sl,result, matrix);
TEST_EQUAL(tree.size(), result.size());
for (Size i = 0; i < tree.size(); ++i)
{
TOLERANCE_ABSOLUTE(0.0001);
TEST_EQUAL(tree[i].left_child, result[i].left_child);
TEST_EQUAL(tree[i].right_child, result[i].right_child);
TEST_REAL_SIMILAR(tree[i].distance, result[i].distance);
}
}
END_SECTION
START_SECTION((void cluster(std::vector<PeakSpectrum>& data, const BinnedSpectrumCompareFunctor& comparator, double sz, UInt sp, const ClusterFunctor& clusterer, std::vector<BinaryTreeNode>& cluster_tree, DistanceMatrix<float>& original_distance)))
{
PeakSpectrum s1, s2, s3;
Peak1D peak;
DTAFile().load(OPENMS_GET_TEST_DATA_PATH("PILISSequenceDB_DFPIANGER_1.dta"), s1);
s2 = s1;
s3 = s1;
s2.pop_back();
s3.pop_back();
peak.setMZ(666.66);
peak.setIntensity(999.99f);
s2.push_back(peak);
s2.sortByPosition();
s3.push_back(peak);
s3.sortByPosition();
vector<PeakSpectrum> d(3);
d[0] = s1; d[1] = s2; d[2] = s3;
ClusterHierarchical ch;
BinnedSharedPeakCount bspc;
SingleLinkage sl;
vector< BinaryTreeNode > result;
vector< BinaryTreeNode > tree;
tree.push_back(BinaryTreeNode(1,2,0.0));
tree.push_back(BinaryTreeNode(0,1,0.00849858f));
DistanceMatrix<float> matrix;
ch.cluster(d,bspc,1.5,2,BinnedSpectrum::DEFAULT_BIN_OFFSET_LOWRES,sl,result, matrix);
TEST_EQUAL(tree.size(), result.size());
for (Size i = 0; i < tree.size(); ++i)
{
TOLERANCE_ABSOLUTE(0.0001);
TEST_EQUAL(tree[i].left_child, result[i].left_child);
TEST_EQUAL(tree[i].right_child, result[i].right_child);
TEST_REAL_SIMILAR(tree[i].distance, result[i].distance);
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/PeptideIndexing_test.cpp | .cpp | 18,802 | 411 | // 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 <QtCore/QStringList>
///////////////////////////
#include <OpenMS/ANALYSIS/ID/PeptideIndexing.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
std::vector<FASTAFile::FASTAEntry> toFASTAVec(const QStringList& sl_prot, const QStringList& identifier = QStringList())
{
std::vector<FASTAFile::FASTAEntry> proteins;
for (int i = 0; i < sl_prot.size(); ++i)
{
String id = i < identifier.size() ? identifier[i] : String(i); // use identifier if given; or create automatically
proteins.push_back(FASTAFile::FASTAEntry(id, "", sl_prot[int(i)]));
}
return proteins;
}
PeptideIdentificationList toPepVec(const QStringList& sl_pep)
{
PeptideIdentificationList pep_vec;
for (int i = 0; i < sl_pep.size(); ++i)
{
PeptideHit hit;
hit.setSequence(AASequence::fromString(sl_pep[int(i)]));
std::vector<PeptideHit> hits;
hits.push_back(hit);
PeptideIdentification pi;
pi.setHits(hits);
pep_vec.push_back(pi);
}
return pep_vec;
}
START_TEST(PeptideIndexing, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PeptideIndexing* ptr = 0;
PeptideIndexing* null_ptr = 0;
START_SECTION(PeptideIndexing())
{
ptr = new PeptideIndexing();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(virtual ~PeptideIndexing())
{
delete ptr;
}
END_SECTION
START_SECTION((ExitCodes run(std::vector<FASTAFile::FASTAEntry>& proteins, std::vector<ProteinIdentification>& prot_ids, PeptideIdentificationList& pep_ids)))
{
// regression test: https://github.com/OpenMS/OpenMS/issues/3447
{
PeptideIndexing indexer;
Param p = indexer.getParameters();
p.setValue("decoy_string", "DECOY_");
indexer.setParameters(p);
std::vector<FASTAFile::FASTAEntry> proteins = toFASTAVec(QStringList() << "AAAKEEEKTTTK");
std::vector<ProteinIdentification> prot_ids;
PeptideIdentificationList pep_ids = toPepVec(QStringList() << "EEEK(Label:13C(6))");
indexer.run(proteins, prot_ids, pep_ids);
TEST_EQUAL(pep_ids[0].getHits()[0].extractProteinAccessionsSet().size(), 1); // one exact hit
indexer.run(proteins, prot_ids, pep_ids);
TEST_EQUAL(pep_ids[0].getHits()[0].extractProteinAccessionsSet().size(), 1); // one exact hit
}
PeptideIndexing pi;
Param p = pi.getParameters();
PeptideIndexing::ExitCodes r;
// easy case:
std::vector<FASTAFile::FASTAEntry> proteins = toFASTAVec(QStringList() << "*MLT*EAXK"); // 1 X!! ; extra * chars (should be ignored)
std::vector<ProteinIdentification> prot_ids;
PeptideIdentificationList pep_ids = toPepVec(QStringList() << "MLTEAEK"); // requires 1 ambAA
p.setValue("aaa_max", 0);
p.setValue("decoy_string", "DECOY_");
pi.setParameters(p);
r = pi.run(proteins, prot_ids, pep_ids);
TEST_EQUAL(pep_ids[0].getHits()[0].extractProteinAccessionsSet().size(), 0); // no hit or one hit!
p.setValue("aaa_max", 1);
pi.setParameters(p);
r = pi.run(proteins, prot_ids, pep_ids);
TEST_EQUAL(pep_ids[0].getHits()[0].extractProteinAccessionsSet().size(), 1); // one hit! -- no ambAA's to spare
p.setValue("aaa_max", 10);
pi.setParameters(p);
r = pi.run(proteins, prot_ids, pep_ids);
TEST_EQUAL(pep_ids[0].getHits()[0].extractProteinAccessionsSet().size(), 1); // one hit! -- plenty of ambAA's to spare
// 2 AmbAA's...
proteins = toFASTAVec(QStringList() << "B*EBE*"); // DB with 2 ambiguous AA's; and extra * chars (should be ignored)
pep_ids = toPepVec(QStringList() << "NENE" << "NEDE" << "DENE" << "DEDE"); // each is a hit, if >= 2 ambAA's are allowed;
for (int i_aa = 0; i_aa < 5; ++i_aa)
{
p.setValue("aaa_max", i_aa);
pi.setParameters(p);
std::vector<FASTAFile::FASTAEntry> proteins_local = proteins;
PeptideIdentificationList pep_ids_local = pep_ids;
r = pi.run(proteins_local, prot_ids, pep_ids_local);
for (Size i = 0; i < pep_ids.size(); ++i)
{
set<String> protein_accessions = pep_ids_local[i].getHits()[0].extractProteinAccessionsSet();
TEST_EQUAL(protein_accessions.size(), i_aa >= 2 ? 1 : 0); // no hit or one hit!
}
}
std::cerr << "\n\n testing larger protein with CASIQK...\n\n";
proteins = toFASTAVec(QStringList() << "SSLDIVLHDTYYVVAHFHYVLSMGAVFAIMGGFIHWFPLFSGYTLDQTYAKIHFTIMFIGVNLTFFPXXXXXXXXXXRRXSDYPDAYTTWNILSSVGSFISLTAVMLMIFXIXEXXASXXKXLMXXXXSXXXXXXXXXXXXXHTFEEPVYMKS");
// ^
// exists does not exist...... CASIQK
pep_ids = toPepVec(QStringList() << "CASIQK" << "ASIQKFGER" << "KDAVAASIQK" << "KPASIQKR");
p.setValue("enzyme:specificity", "none");
p.setValue("missing_decoy_action", "warn");
pi.setParameters(p);
for (int i_aa = 0; i_aa < 5; ++i_aa)
{
p.setValue("aaa_max", i_aa);
pi.setParameters(p);
std::vector<FASTAFile::FASTAEntry> proteins_local = proteins;
PeptideIdentificationList pep_ids_local = pep_ids;
pi.run(proteins_local, prot_ids, pep_ids_local);
for (Size i = 0; i < pep_ids.size(); ++i)
{
set<String> protein_accessions = pep_ids_local[i].getHits()[0].extractProteinAccessionsSet();
bool is_CASIQK = (i == 0);
bool allow_at_least_3_ambAA = (i_aa >= 3);
std::cerr << "TEST: ambAA=" << i_aa << ", hit#:" << i << " ==> prots: " << protein_accessions.size() << "==" << (is_CASIQK & allow_at_least_3_ambAA ? 1 : 0) << "?\n";
TEST_EQUAL(protein_accessions.size(), is_CASIQK & allow_at_least_3_ambAA ? 1 : 0);
}
}
// empty FASTA (proteins) --> FAIL
proteins = toFASTAVec(QStringList());
pep_ids = toPepVec(QStringList() << "SOME" << "PEPTIDES");
r = pi.run(proteins, prot_ids, pep_ids);
TEST_EQUAL(r, PeptideIndexing::ExitCodes::DATABASE_EMPTY);
// empty idXML (peptides) --> FAIL
proteins = toFASTAVec(QStringList("PROTEINSEQ"));
pep_ids = toPepVec(QStringList());
r = pi.run(proteins, prot_ids, pep_ids);
TEST_EQUAL(r, PeptideIndexing::ExitCodes::PEPTIDE_IDS_EMPTY);
// duplicate accession -- will not be detected and the peptide will have two protein hits.
// However, extractProteinAccessionsSet() returns a set<>, i.e. only one hit.
p.setValue("aaa_max", 2);
pi.setParameters(p);
proteins = toFASTAVec(QStringList() << "BEBE" << "PROTEIN" << "BEBE", QStringList() << "P_BEBE" << "P_PROTEIN" << "P_BEBE"); //
pep_ids = toPepVec(QStringList() << "NENE" << "NEDE" << "DENE" << "DEDE"); // 4 hits;
r = pi.run(proteins, prot_ids, pep_ids);
TEST_EQUAL(proteins.size(), 3) // all three present
// I/L conversion
p.setValue("aaa_max", 2); // testing I / L conversion, with additional ambAA's to saturate the max_aaa = 2 constraint to ensure that internally 'J' is not used for 'I' or 'L'
p.setValue("IL_equivalent", "false"); // NOT default
pi.setParameters(p);
proteins = toFASTAVec(QStringList() << "BEBEI" << "BEBEL"); //
pep_ids = toPepVec(QStringList() << "NENEL" << "NEDEL" << "DENEI" << "DEDEI"); // each PSM hits either one or two proteins, depending on I/L setting;
r = pi.run(proteins, prot_ids, pep_ids);
for (Size i = 0; i < pep_ids.size(); ++i) TEST_EQUAL(pep_ids[i].getHits()[0].extractProteinAccessionsSet().size(), 1); // one hit!
// ... separate
p.setValue("IL_equivalent", "true"); // default
pi.setParameters(p);
r = pi.run(proteins, prot_ids, pep_ids);
for (Size i = 0; i < 4; ++i) TEST_EQUAL(pep_ids[i].getHits()[0].extractProteinAccessionsSet().size(), 2); // two hits!
TEST_EQUAL(pep_ids[0].getHits()[0].getSequence().toUnmodifiedString(), "NENEL"); // make sure the PEPTIDE(!) sequence itself is unchanged
TEST_EQUAL(pep_ids[2].getHits()[0].getSequence().toUnmodifiedString(), "DENEI"); // make sure the PEPTIDE(!) sequence itself is unchanged
// insertion / deletion
p.setValue("aaa_max", 2);
p.setValue("IL_equivalent", "true"); // default
pi.setParameters(p);
proteins = toFASTAVec(QStringList() << "BEBE"); //
pep_ids = toPepVec(QStringList() << "NEKNE" << "NEE"); // 1 insertion, 1 deletion;
r = pi.run(proteins, prot_ids, pep_ids);
for (Size i = 0; i < pep_ids.size(); ++i) TEST_EQUAL(pep_ids[i].getHits()[0].extractProteinAccessionsSet().size(), 0); // no hits
// auto mode for decoy strings and position
std::vector<ProteinIdentification> prot_ids_2;
PeptideIdentificationList pep_ids_2;
{
// simple prefix
PeptideIndexing pi_2;
Param p_2 = pi_2.getParameters();
std::vector<FASTAFile::FASTAEntry> proteins_2 = toFASTAVec(QStringList() << "PEPTIDEXXX" << "PEPTLDEXXX", QStringList() << "Protein1" << "DECOY_Protein2");
pi_2.run(proteins_2, prot_ids_2, pep_ids_2);
TEST_STRING_EQUAL(pi_2.getDecoyString(), "DECOY_");
TEST_EQUAL(pi_2.isPrefix(), true);
}
{
// simple prefix without special characters
PeptideIndexing pi_3;
Param p_3 = pi_3.getParameters();
std::vector<FASTAFile::FASTAEntry> proteins_3 = toFASTAVec(QStringList() << "PEPTIDEXXX" << "PEPTLDEXXX", QStringList() << "Protein1" << "DECOYProtein2");
pi_3.run(proteins_3, prot_ids_2, pep_ids_2);
TEST_STRING_EQUAL(pi_3.getDecoyString(), "DECOY");
TEST_EQUAL(pi_3.isPrefix(), true);
}
{
// wrong suffix
PeptideIndexing pi_4;
Param p_4 = pi_4.getParameters();
std::vector<FASTAFile::FASTAEntry> proteins_4 = toFASTAVec(QStringList() << "PEPTIDEXXX" << "PEPTLDEXXX", QStringList() << "Protein1" << "Protein2DECOY_");
pi_4.run(proteins_4, prot_ids_2, pep_ids_2);
TEST_STRING_EQUAL(pi_4.getDecoyString(), "DECOY_"); //here DECOY_ is the default when finding an affix fails
TEST_EQUAL(pi_4.isPrefix(), true); // prefix is default too
}
{
// simple suffix
PeptideIndexing pi_42;
Param p_42 = pi_42.getParameters();
std::vector<FASTAFile::FASTAEntry> proteins_42 = toFASTAVec(QStringList() << "PEPTIDEXXX" << "PEPTLDEXXX", QStringList() << "Protein1" << "Protein2_DECOY");
pi_42.run(proteins_42, prot_ids_2, pep_ids_2);
TEST_STRING_EQUAL(pi_42.getDecoyString(), "_DECOY");
TEST_EQUAL(pi_42.isPrefix(), false);
}
{
// complex prefix with one false friend
PeptideIndexing pi_5;
Param p_5 = pi_5.getParameters();
std::vector<FASTAFile::FASTAEntry> proteins_5 = toFASTAVec(QStringList() << "PEPTIDEXXX" << "PEPTLDEXXX" << "PEPTLDEXXX" << "PEPTLDEXXX" << "PEPTLDEXXX" << "PEPTLDEXXX",
QStringList() << "Protein1" << "__id_decoy__Protein2" << "Protein3" <<"Protein4rev" << "__id_decoy__Protein5" << "__id_decoy__Protein6");
pi_5.run(proteins_5, prot_ids_2, pep_ids_2);
TEST_STRING_EQUAL(pi_5.getDecoyString(), "__id_decoy__");
TEST_EQUAL(pi_5.isPrefix(), true);
}
{
// test for self containing decoys: rev vs reverse should output the longer decoy -> reverse?
PeptideIndexing pi_6;
std::vector<FASTAFile::FASTAEntry> proteins_6 = toFASTAVec(QStringList() << "PEPTIDEXXX" << "PEPTLDEXXX", QStringList() << "Protein1" << "reverse_Protein");
pi_6.run(proteins_6, prot_ids_2, pep_ids_2);
TEST_STRING_EQUAL(pi_6.getDecoyString(), "reverse_");
TEST_EQUAL(pi_6.isPrefix(), true);
}
{
// impossible to determine automatically -> exit code: DECOYSTRING_EMPTY?
PeptideIndexing pi_7;
std::vector<FASTAFile::FASTAEntry> proteins_7 = toFASTAVec(QStringList() << "PEPTIDEXXX" << "PEPTLDEXXX", QStringList() << "rev_Protein1" << "reverse_Protein");
pi_7.run(proteins_7, prot_ids_2, pep_ids_2);
TEST_STRING_EQUAL(pi_7.getDecoyString(), "DECOY_");
TEST_EQUAL(pi_7.isPrefix(), true);
}
{
// test if ambiguous AA's can occur in peptides and are matched without using AAAs or MMs
PeptideIndexing pi_8;
Param p_8 = pi_8.getParameters();
p_8.setValue("aaa_max", 0);
p_8.setValue("mm_max", 0);
pi_8.setParameters(p_8);
std::vector<FASTAFile::FASTAEntry> proteins_8 = toFASTAVec(QStringList() << "PEPTIDERXXXBEBEAR"
<< "PEPTLDEXXXXBEEEAR",
QStringList() << "Protein1" << "otherProtein");
pep_ids = toPepVec(QStringList() << "PEPTIDER" // matches Protein1;
<< "XXXBEBEAR"); // matches Protein1;
pi_8.run(proteins_8, prot_ids_2, pep_ids);
for (auto& pep : pep_ids)
{
TEST_EQUAL(pep.getHits().size(), 1)
const auto r = pep.getHits()[0].extractProteinAccessionsSet();
TEST_EQUAL(r.size(), 1); // one hit!
TEST_EQUAL(*r.begin(), "Protein1"); // one hit!
}
}
{
// test no-cleavage (e.g. matching a peptide FASTA DB exactly)
PeptideIndexing pi_8;
Param p_8 = pi_8.getParameters();
p_8.setValue("aaa_max", 0);
p_8.setValue("mm_max", 0);
p_8.setValue("enzyme:name", "no cleavage");
p_8.setValue("allow_nterm_protein_cleavage", "false");
pi_8.setParameters(p_8);
std::vector<FASTAFile::FASTAEntry> proteins_8 = toFASTAVec(QStringList() << "MKDPLMMLK"
<< "KDPLMMLK",
QStringList() << "Protein1" << "otherProtein");
pep_ids = toPepVec(QStringList() << "KDPLMMLK" << "MKD");
pi_8.run(proteins_8, prot_ids_2, pep_ids);
TEST_EQUAL(pep_ids[0].getHits().size(), 1)
const auto r = pep_ids[0].getHits()[0].extractProteinAccessionsSet();
TEST_EQUAL(r.size(), 1); // one hit!
TEST_EQUAL(*r.begin(), "otherProtein"); // one hit!
TEST_EQUAL(pep_ids[1].getHits()[0].extractProteinAccessionsSet().size(), 0) // no hit for "MKD"
}
{
// test no-cleavage (e.g. matching a peptide FASTA DB exactly) but with ASP/PRO cleavage enabled
PeptideIndexing pi_8;
Param p_8 = pi_8.getParameters();
p_8.setValue("aaa_max", 0);
p_8.setValue("mm_max", 0);
p_8.setValue("enzyme:name", "no cleavage");
p_8.setValue("allow_nterm_protein_cleavage", "false");
pi_8.setParameters(p_8);
std::vector<FASTAFile::FASTAEntry> proteins_8 = toFASTAVec(QStringList() << "MKDPLMMLK" // should not hit, due to !allow_nterm_protein_cleavage
<< "KDPLMMLK", // target
QStringList() << "Protein1"
<< "otherProtein");
prot_ids_2.resize(1);
prot_ids_2[0].setSearchEngine("XTANDEM"); // enable random ASP/PRO cleavage in PeptideIndexing
pep_ids = toPepVec(QStringList() << "KDPLMMLK" // one hit
<< "KD"); // one hit due to D/P cleavage
pi_8.run(proteins_8, prot_ids_2, pep_ids);
for (auto& pep : pep_ids)
{
TEST_EQUAL(pep.getHits().size(), 1)
const auto r = pep.getHits()[0].extractProteinAccessionsSet();
TEST_EQUAL(r.size(), 1); // one hit!
TEST_EQUAL(*r.begin(), "otherProtein"); // one hit!
}
}
}
END_SECTION
START_SECTION((Test PeptideIndexer settings stored as metavalues in SearchParameters))
{
// Test that PeptideIndexer settings are stored as metavalues in SearchParameters
PeptideIndexing pi;
Param p = pi.getParameters();
p.setValue("decoy_string", "DECOY_");
p.setValue("decoy_string_position", "prefix");
p.setValue("enzyme:name", "Trypsin");
p.setValue("enzyme:specificity", "full");
p.setValue("aaa_max", 2);
p.setValue("mismatches_max", 1);
p.setValue("IL_equivalent", "true");
p.setValue("allow_nterm_protein_cleavage", "false");
p.setValue("unmatched_action", "warn");
p.setValue("missing_decoy_action", "warn");
pi.setParameters(p);
std::vector<FASTAFile::FASTAEntry> proteins = toFASTAVec(QStringList() << "PEPTIDER" << "DECOY_SEQUENCE");
// Create a ProteinIdentification with an identifier that matches the PeptideIdentifications
std::vector<ProteinIdentification> prot_ids(1);
prot_ids[0].setIdentifier("test_run");
// Create PeptideIdentifications with matching identifier
PeptideIdentificationList pep_ids = toPepVec(QStringList() << "PEPTIDER");
for (auto& pep_id : pep_ids)
{
pep_id.setIdentifier("test_run");
}
PeptideIndexing::ExitCodes r = pi.run(proteins, prot_ids, pep_ids);
TEST_EQUAL(r, PeptideIndexing::ExitCodes::EXECUTION_OK);
// Check that metavalues are set correctly in SearchParameters
const ProteinIdentification::SearchParameters& search_params = prot_ids[0].getSearchParameters();
TEST_EQUAL(search_params.metaValueExists("PeptideIndexer:decoy_string"), true);
TEST_EQUAL(search_params.getMetaValue("PeptideIndexer:decoy_string"), "DECOY_");
TEST_EQUAL(search_params.metaValueExists("PeptideIndexer:decoy_string_position"), true);
TEST_EQUAL(search_params.getMetaValue("PeptideIndexer:decoy_string_position"), "prefix");
TEST_EQUAL(search_params.metaValueExists("PeptideIndexer:enzyme"), true);
TEST_EQUAL(search_params.getMetaValue("PeptideIndexer:enzyme"), "Trypsin");
TEST_EQUAL(search_params.metaValueExists("PeptideIndexer:enzyme_specificity"), true);
TEST_EQUAL(search_params.getMetaValue("PeptideIndexer:enzyme_specificity"), "full");
TEST_EQUAL(search_params.metaValueExists("PeptideIndexer:aaa_max"), true);
TEST_EQUAL(search_params.getMetaValue("PeptideIndexer:aaa_max"), 2);
TEST_EQUAL(search_params.metaValueExists("PeptideIndexer:mismatches_max"), true);
TEST_EQUAL(search_params.getMetaValue("PeptideIndexer:mismatches_max"), 1);
TEST_EQUAL(search_params.metaValueExists("PeptideIndexer:IL_equivalent"), true);
TEST_EQUAL(search_params.getMetaValue("PeptideIndexer:IL_equivalent"), "true");
TEST_EQUAL(search_params.metaValueExists("PeptideIndexer:allow_nterm_protein_cleavage"), true);
TEST_EQUAL(search_params.getMetaValue("PeptideIndexer:allow_nterm_protein_cleavage"), "false");
TEST_EQUAL(search_params.metaValueExists("PeptideIndexer:unmatched_action"), true);
TEST_EQUAL(search_params.getMetaValue("PeptideIndexer:unmatched_action"), "warn");
TEST_EQUAL(search_params.metaValueExists("PeptideIndexer:missing_decoy_action"), true);
TEST_EQUAL(search_params.getMetaValue("PeptideIndexer:missing_decoy_action"), "warn");
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MRMFeatureFilter_test.cpp | .cpp | 142,738 | 3,186 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/KERNEL/MRMFeature.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/FORMAT/QcMLFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFilter.h>
using namespace OpenMS;
using namespace std;
START_TEST(MRMFeatureFilter, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MRMFeatureFilter* ptr = nullptr;
MRMFeatureFilter* nullPointer = nullptr;
START_SECTION(MRMFeatureFilter())
{
ptr = new MRMFeatureFilter();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~MRMFeatureFilter())
{
delete ptr;
}
END_SECTION
//START_SECTION(template <typename T> bool checkRange(T const& value, T const& value_l, T const& value_u))
//{
// MRMFeatureFilter mrmff;
// // tests
// TEST_EQUAL(mrmff.checkRange(2.0, 1.0, 2.0), true);
// TEST_EQUAL(mrmff.checkRange(0.0, 1.0, 2.0), false);
// TEST_EQUAL(mrmff.checkRange(3.0, 1.0, 2.0), false);
// TEST_EQUAL(mrmff.checkRange(2, 1, 2), true);
// TEST_EQUAL(mrmff.checkRange(0, 1, 2), false);
// TEST_EQUAL(mrmff.checkRange(3, 1, 2), false);
//}
//END_SECTION
//
//START_SECTION(template <typename T> void updateRange(T const& value, T & value_l, T & value_u))
//{
// MRMFeatureFilter mrmff;
// double value_l = 0;
// double value_u = 12;
// // tests
// mrmff.updateRange(6.0, value_l, value_u);
// TEST_EQUAL(value_l, 0);
// TEST_EQUAL(value_u, 12);
// mrmff.updateRange(13.0, value_l, value_u);
// TEST_EQUAL(value_l, 0);
// TEST_EQUAL(value_u, 13);
// mrmff.updateRange(-1.0, value_l, value_u);
// TEST_EQUAL(value_l, -1);
// TEST_EQUAL(value_u, 13);
//}
//END_SECTION
//
//START_SECTION(template <typename T> void setRange(T const& value, T & value_l, T & value_u))
//{
// MRMFeatureFilter mrmff;
// double value_l = 2;
// double value_u = 12;
// // tests
// mrmff.setRange(6.0, value_l, value_u);
// TEST_EQUAL(value_l, 0);
// TEST_EQUAL(value_u, 6);
// value_l = 2;
// value_u = 12;
// mrmff.setRange(13.0, value_l, value_u);
// TEST_EQUAL(value_l, 2);
// TEST_EQUAL(value_u, 13);
// mrmff.setRange(-1.0, value_l, value_u);
// TEST_EQUAL(value_l, -1);
// TEST_EQUAL(value_u, 0);
//}
//END_SECTION
//
//START_SECTION(template <typename T> void initRange(T const& value, T & value_l, T & value_u))
//{
// MRMFeatureFilter mrmff;
// double value_l = 2;
// double value_u = 12;
// // tests
// mrmff.initRange(6.0, value_l, value_u);
// TEST_EQUAL(value_l, 6);
// TEST_EQUAL(value_u, 6);
//}
//END_SECTION
START_SECTION(double calculateIonRatio(const Feature & component_1, const Feature & component_2, const String & feature_name) const)
{
MRMFeatureFilter mrmff;
String feature_name = "peak_apex_int";
double inf = std::numeric_limits<double>::infinity();
// dummy features
OpenMS::Feature component_1, component_2;
component_1.setMetaValue(feature_name, 5.0);
component_1.setMetaValue("native_id","component1");
component_2.setMetaValue(feature_name, 5.0);
component_2.setMetaValue("native_id","component2");
// tests
TEST_REAL_SIMILAR(mrmff.calculateIonRatio(component_1,component_2,feature_name),1.0);
component_2.setMetaValue(feature_name, 0.0);
TEST_REAL_SIMILAR(mrmff.calculateIonRatio(component_1,component_2,feature_name),inf);
// dummy features
OpenMS::Feature component_3, component_4;
component_3.setMetaValue("peak_area", 5.0);
component_3.setMetaValue("native_id","component3");
component_4.setMetaValue("peak_area", 5.0);
component_4.setMetaValue("native_id","component4");
TEST_REAL_SIMILAR(mrmff.calculateIonRatio(component_1,component_4,feature_name),5.0);
TEST_REAL_SIMILAR(mrmff.calculateIonRatio(component_3,component_4,feature_name),0.0);
// feature_name == "intensity"
// feature_name == "intensity"
Feature component_5, component_6, component_7, component_8;
feature_name = "intensity";
component_5.setMetaValue("native_id", "component5");
component_6.setMetaValue("native_id", "component6");
component_5.setIntensity(3.0);
component_6.setIntensity(4.0);
TEST_REAL_SIMILAR(mrmff.calculateIonRatio(component_5, component_6, feature_name), 0.75);
TEST_REAL_SIMILAR(mrmff.calculateIonRatio(component_6, component_5, feature_name), 1.33333333333333);
component_7.setMetaValue("native_id", "component7");
TEST_REAL_SIMILAR(mrmff.calculateIonRatio(component_5, component_7, feature_name), inf);
TEST_REAL_SIMILAR(mrmff.calculateIonRatio(component_5, component_8, feature_name), 3.0);
}
END_SECTION
START_SECTION(bool checkMetaValue(
const Feature & component,
const String & meta_value_key,
const double & meta_value_l,
const double & meta_value_u,
bool & key_exists
) const)
{
MRMFeatureFilter mrmff;
bool metavalue_exists;
//make test feature
String feature_name = "peak_apex_int";
OpenMS::Feature component_1;
component_1.setMetaValue(feature_name, 5.0);
component_1.setMetaValue("native_id","component1");
// test parameters
double meta_value_l(4.0), meta_value_u(6.0);
TEST_EQUAL(mrmff.checkMetaValue(component_1, feature_name, meta_value_l, meta_value_u, metavalue_exists), true); // pass case
TEST_EQUAL(metavalue_exists, true);
component_1.setMetaValue(feature_name, 6.0);
TEST_EQUAL(mrmff.checkMetaValue(component_1, feature_name, meta_value_l, meta_value_u,metavalue_exists), true); // edge pass case
TEST_EQUAL(metavalue_exists, true);
component_1.setMetaValue(feature_name, 3.0);
TEST_EQUAL(mrmff.checkMetaValue(component_1, feature_name, meta_value_l, meta_value_u, metavalue_exists), false); // fail case
TEST_EQUAL(metavalue_exists, true);
TEST_EQUAL(mrmff.checkMetaValue(component_1, "peak_area", meta_value_l, meta_value_u, metavalue_exists), true); // not found case
TEST_EQUAL(metavalue_exists, false);
}
END_SECTION
START_SECTION(void updateMetaValue(
const Feature & component,
const String & meta_value_key,
double & meta_value_l,
double & meta_value_u,
bool & key_exists
) const)
{
MRMFeatureFilter mrmff;
bool metavalue_exists;
//make test feature
String feature_name = "peak_apex_int";
OpenMS::Feature component_1;
component_1.setMetaValue(feature_name, 5.0);
component_1.setMetaValue("native_id", "component1");
// test parameters
double meta_value_l(4.0), meta_value_u(6.0);
mrmff.updateMetaValue(component_1, feature_name, meta_value_l, meta_value_u, metavalue_exists);
TEST_EQUAL(meta_value_l, 4); // no change case
TEST_EQUAL(meta_value_u, 6); // no change case
TEST_EQUAL(metavalue_exists, true);
component_1.setMetaValue(feature_name, 7.0);
mrmff.updateMetaValue(component_1, feature_name, meta_value_l, meta_value_u, metavalue_exists);
TEST_EQUAL(meta_value_l, 4); // no change case
TEST_EQUAL(meta_value_u, 7); // change case
TEST_EQUAL(metavalue_exists, true);
component_1.setMetaValue(feature_name, 3.0);
mrmff.updateMetaValue(component_1, feature_name, meta_value_l, meta_value_u, metavalue_exists);
TEST_EQUAL(meta_value_l, 3); // change case
TEST_EQUAL(meta_value_u, 7); // no change case
TEST_EQUAL(metavalue_exists, true);
mrmff.updateMetaValue(component_1, "peak_area", meta_value_l, meta_value_u, metavalue_exists);
TEST_EQUAL(meta_value_l, 3); // no change case
TEST_EQUAL(meta_value_u, 7); // no change case
TEST_EQUAL(metavalue_exists, false); // not found case
}
END_SECTION
START_SECTION(void setMetaValue(
const Feature & component,
const String & meta_value_key,
double & meta_value_l,
double & meta_value_u,
bool & key_exists
) const)
{
MRMFeatureFilter mrmff;
bool metavalue_exists;
//make test feature
String feature_name = "peak_apex_int";
OpenMS::Feature component_1;
component_1.setMetaValue(feature_name, 5.0);
component_1.setMetaValue("native_id", "component1");
// test parameters
double meta_value_l(4.0), meta_value_u(6.0);
mrmff.setMetaValue(component_1, feature_name, meta_value_l, meta_value_u, metavalue_exists);
TEST_EQUAL(meta_value_l, 0);
TEST_EQUAL(meta_value_u, 5);
TEST_EQUAL(metavalue_exists, true);
component_1.setMetaValue(feature_name, 7.0);
meta_value_l = 4.0; meta_value_u = 6.0;
mrmff.setMetaValue(component_1, feature_name, meta_value_l, meta_value_u, metavalue_exists);
TEST_EQUAL(meta_value_l, 0);
TEST_EQUAL(meta_value_u, 7);
TEST_EQUAL(metavalue_exists, true);
component_1.setMetaValue(feature_name, -1.0);
mrmff.setMetaValue(component_1, feature_name, meta_value_l, meta_value_u, metavalue_exists);
TEST_EQUAL(meta_value_l, -1);
TEST_EQUAL(meta_value_u, 0);
TEST_EQUAL(metavalue_exists, true);
mrmff.setMetaValue(component_1, "peak_area", meta_value_l, meta_value_u, metavalue_exists);
TEST_EQUAL(meta_value_l, -1); // no change case
TEST_EQUAL(meta_value_u, 0); // no change case
TEST_EQUAL(metavalue_exists, false); // not found case
}
END_SECTION
START_SECTION(void initMetaValue(
const Feature & component,
const String & meta_value_key,
double & meta_value_l,
double & meta_value_u,
bool & key_exists
) const)
{
MRMFeatureFilter mrmff;
bool metavalue_exists;
//make test feature
String feature_name = "peak_apex_int";
OpenMS::Feature component_1;
component_1.setMetaValue(feature_name, 5.0);
component_1.setMetaValue("native_id", "component1");
// test parameters
double meta_value_l(4.0), meta_value_u(6.0);
mrmff.initMetaValue(component_1, feature_name, meta_value_l, meta_value_u, metavalue_exists);
TEST_EQUAL(meta_value_l, 5);
TEST_EQUAL(meta_value_u, 5);
TEST_EQUAL(metavalue_exists, true);
meta_value_l = 4.0; meta_value_u = 6.0;
mrmff.initMetaValue(component_1, "peak_area", meta_value_l, meta_value_u, metavalue_exists);
TEST_EQUAL(meta_value_l, 4); // no change case
TEST_EQUAL(meta_value_u, 6); // no change case
TEST_EQUAL(metavalue_exists, false); // not found case
}
END_SECTION
START_SECTION(countLabelsAndTransitionTypes(const Feature & component_group, const TargetedExperiment & transitions) const)
{
MRMFeatureFilter mrmff;
// make the feature
OpenMS::Feature component_1, subordinate;
std::vector<OpenMS::Feature> subordinates;
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setMetaValue("LabelType","Heavy");
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setMetaValue("LabelType","Light");
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id","component1.2.Light");
subordinate.setMetaValue("LabelType","Light");
subordinates.push_back(subordinate);
// component_1.setPeptideRef("component_group1");
component_1.setSubordinates(subordinates);
// // transition group 2
// // transition 1
// subordinate.setMetaValue("native_id","component2.1.Heavy")
// subordinate.setMetaValue("LabelType","Heavy");
// subordinates.push_back(subordinate);
// // transition 2
// subordinate.setMetaValue("native_id","component2.1.Light")
// subordinate.setMetaValue("LabelType","Light");
// subordinates.push_back(subordinate);
// make the targeted experiment
TargetedExperiment transitions;
ReactionMonitoringTransition transition;
// transition group 1
// transition 1
transition.setNativeID("component1.1.Heavy");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component1.1.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 3
transition.setNativeID("component1.2.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(false);
transitions.addTransition(transition);
// transition group 2
// transition 1
transition.setNativeID("component2.1.Heavy");
transition.setPeptideRef("component_group2");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component2.1.Light");
transition.setPeptideRef("component_group2");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
std::map<String,int> test1 = mrmff.countLabelsAndTransitionTypes(component_1, transitions);
TEST_EQUAL(test1["n_heavy"], 1);
TEST_EQUAL(test1["n_light"], 2);
TEST_EQUAL(test1["n_quantifying"], 2);
TEST_EQUAL(test1["n_identifying"], 0);
TEST_EQUAL(test1["n_detecting"], 3);
TEST_EQUAL(test1["n_transitions"], 3);
}
END_SECTION
START_SECTION(void FilterFeatureMap(FeatureMap& features, MRMFeatureQC& filter_criteria,
const TargetedExperiment & transitions))
{
/** FilterFeatureMap Test 1: basic ability to flag or filter transitions or transition groups */
MRMFeatureFilter mrmff;
//make the FeatureMap
FeatureMap components;
OpenMS::Feature component_1, subordinate;
std::vector<OpenMS::Feature> subordinates;
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id","component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",500); //should fail
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
// transition group 2
// transition 1
subordinate.setMetaValue("native_id","component2.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",1000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component2.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",1000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group2");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
// make the targeted experiment
TargetedExperiment transitions;
ReactionMonitoringTransition transition;
// transition group 1
// transition 1
transition.setNativeID("component1.1.Heavy");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component1.1.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 3
transition.setNativeID("component1.2.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(false);
transitions.addTransition(transition);
// transition group 2
// transition 1
transition.setNativeID("component2.1.Heavy");
transition.setPeptideRef("component_group2");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component2.1.Light");
transition.setPeptideRef("component_group2");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
//make the QCs
MRMFeatureQC qc_criteria;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
std::pair<double,double> lbub(501, 4e6);
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 1;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 2;
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 2;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 2;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 3;
cgqcs.n_transitions_l = 2;
cgqcs.n_transitions_u = 3;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0.5;
cgqcs.ion_ratio_u = 10.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
// transition group 2
cgqcs.component_group_name = "component_group2";
cgqcs.n_heavy_l = 1;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 2; //should fail
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 2;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 2;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 3;
cgqcs.n_transitions_l = 3; //should fail
cgqcs.n_transitions_u = 3;
cgqcs.ion_ratio_pair_name_1 = "component2.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component2.2.Light";
cgqcs.ion_ratio_l = 0.5;
cgqcs.ion_ratio_u = 10.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component2.1.Heavy";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
// transition 2
cqcs.component_name = "component2.1.Light";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
//test flag mode
Param params;
params.setValue("flag_or_filter", "flag");
mrmff.setParameters(params);
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_pass"), false);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message").toStringList()[0], "peak_apex_int");
TEST_EQUAL(components[1].getMetaValue("QC_transition_group_pass"), false);
TEST_EQUAL(components[1].getMetaValue("QC_transition_group_message").toStringList().size(), 2);
TEST_STRING_EQUAL(components[1].getMetaValue("QC_transition_group_message").toStringList()[0], "n_light");
TEST_STRING_EQUAL(components[1].getMetaValue("QC_transition_group_message").toStringList()[1], "n_transitions");
TEST_EQUAL(components[1].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[1].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_score"), 0.75);
TEST_REAL_SIMILAR(components[1].getMetaValue("QC_transition_group_score"), 0.777777777777778);
TEST_REAL_SIMILAR(components[1].getSubordinates()[0].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[1].getSubordinates()[1].getMetaValue("QC_transition_score"), 1.0);
//test filter mode
params.setValue("flag_or_filter", "filter");
mrmff.setParameters(params);
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
TEST_EQUAL(components.size(), 1);
TEST_EQUAL(components[0].getSubordinates().size(), 2);
}
END_SECTION
START_SECTION(void FilterFeatureMap(FeatureMap& features, MRMFeatureQC& filter_criteria,
const TargetedExperiment & transitions))
{
/** FilterFeatureMap Test 2: tests for individual checks on each transition and transition group */
MRMFeatureFilter mrmff;
//make the FeatureMap
FeatureMap components;
OpenMS::Feature component_1, subordinate;
std::vector<OpenMS::Feature> subordinates;
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id","component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
// make the targeted experiment
TargetedExperiment transitions;
ReactionMonitoringTransition transition;
// transition group 1
// transition 1
transition.setNativeID("component1.1.Heavy");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component1.1.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 3
transition.setNativeID("component1.2.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(false);
transitions.addTransition(transition);
//make the QCs
MRMFeatureQC qc_criteria;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
std::pair<double,double> lbub(500, 4e6);
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 1;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 1;
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 2;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 2;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 3;
cgqcs.n_transitions_l = 3;
cgqcs.n_transitions_u = 3;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0.5;
cgqcs.ion_ratio_u = 2.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
cqcs.meta_value_qc["peak_area"] = lbub;
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
//test all possible comparisons
Param params;
params.setValue("flag_or_filter", "flag");
mrmff.setParameters(params);
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
// control
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_pass"), true);
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_score"), 1.0);
components.clear();
// RT
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id","component1.2.Light");
subordinate.setRT(6.0); // should fail
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_pass"), false);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message").toStringList()[0], "retention_time");
components.clear();
// Intensity
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id","component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(0.0); // should fail
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_pass"), false);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message").toStringList()[0], "intensity");
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_score"), 0.75);
components.clear();
// OverallQuality
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id","component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(0.0); //should fail
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_pass"), false);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message").toStringList()[0], "overall_quality");
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_score"), 0.75);
components.clear();
// MetaValue
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",500);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id","component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",400); //should fail
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_pass"), false);
// TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message"), "metaValue[peak_apex_int]");
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_message").toStringList()[0], "peak_apex_int");
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_score"), 0.75);
components.clear();
// n_heavy
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id","component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_pass"), false);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getMetaValue("QC_transition_group_message").toStringList()[0], "n_heavy");
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_pass"), true);
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_score"), 0.892857142857143);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_score"), 1.0);
components.clear();
// n_light
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id","component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_pass"), false);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getMetaValue("QC_transition_group_message").toStringList()[0], "n_light");
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_pass"), true);
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_score"), 0.892857142857143);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_score"), 1.0);
components.clear();
// n_transitions
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_pass"), false);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getMetaValue("QC_transition_group_message").toStringList()[0], "n_transitions");
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_score"), 0.888888888888889);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_score"), 1.0);
components.clear();
// ion_ratio_pair
// transition group 1
// transition 1
subordinate.setMetaValue("native_id","component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Heavy");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id","component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id","component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType","Light");
subordinate.setMetaValue("peak_apex_int",500);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
mrmff.FilterFeatureMap(components, qc_criteria, transitions);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_pass"), false);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getMetaValue("QC_transition_group_message").toStringList()[0], "ion_ratio_pair[component1.1.Light/component1.2.Light]");
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_pass"), true);
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_score"), 0.964285714285714);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_score"), 1.0);
components.clear();
}
END_SECTION
START_SECTION(void EstimateDefaultMRMFeatureQCValues(const std::vector<FeatureMap>& samples, MRMFeatureQC& filter_template, const TargetedExperiment& transitions))
{
MRMFeatureFilter mrmff;
//make the FeatureMap
std::vector<FeatureMap> samples;
FeatureMap components;
OpenMS::Feature component_1, subordinate;
std::vector<OpenMS::Feature> subordinates;
// sample 1
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 500);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setRT(2.5);
component_1.setIntensity(15000);
component_1.setOverallQuality(300);
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
samples.push_back(components);
components.clear();
// sample 2
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(3.0);
subordinate.setIntensity(1000);
subordinate.setOverallQuality(200);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 1000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(3);
subordinate.setIntensity(1000);
subordinate.setOverallQuality(400);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 2000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(3.1);
subordinate.setIntensity(2000);
subordinate.setOverallQuality(300);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 800);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setRT(3);
component_1.setIntensity(5000);
component_1.setOverallQuality(200);
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
samples.push_back(components);
components.clear();
// sample 3
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(2);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(2);
subordinate.setIntensity(4000);
subordinate.setOverallQuality(150);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 6000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(2);
subordinate.setIntensity(1000);
subordinate.setOverallQuality(300);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 100);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setRT(2);
component_1.setIntensity(15000);
component_1.setOverallQuality(500);
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
samples.push_back(components);
components.clear();
// make the targeted experiment
TargetedExperiment transitions;
ReactionMonitoringTransition transition;
// transition group 1
// transition 1
transition.setNativeID("component1.1.Heavy");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component1.1.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 3
transition.setNativeID("component1.2.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(false);
transitions.addTransition(transition);
// make the expected QCs values
std::vector<MRMFeatureQC> filter_values;
MRMFeatureQC qc_criteria1, qc_criteria2;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 0;
cgqcs.n_heavy_u = 0;
cgqcs.n_light_l = 0;
cgqcs.n_light_u = 0;
cgqcs.n_detecting_l = 0;
cgqcs.n_detecting_u = 0;
cgqcs.n_quantifying_l = 0;
cgqcs.n_quantifying_u = 0;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 0;
cgqcs.n_transitions_l = 0;
cgqcs.n_transitions_u = 0;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1;
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 0);
cqcs.meta_value_qc["peak_area"] = std::make_pair(0, 0); // should not change
qc_criteria1.component_group_qcs.push_back(cgqcs);
qc_criteria1.component_qcs.push_back(cqcs);
qc_criteria2 = qc_criteria1;
// Test calculateFilterValuesMean without initialization of values
mrmff.EstimateDefaultMRMFeatureQCValues(samples, qc_criteria1, transitions, false);
// transition group 1
TEST_STRING_EQUAL(qc_criteria1.component_group_qcs.at(0).component_group_name, "component_group1");
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_heavy_l, 0); // lower limits are not changed
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_heavy_u, 1);
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_light_l, 0);
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_light_u, 2);
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_detecting_l, 0);
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_detecting_u, 3);
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_quantifying_l, 0);
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_quantifying_u, 2);
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_identifying_l, 0);
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_identifying_u, 0);
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_transitions_l, 0);
TEST_EQUAL(qc_criteria1.component_group_qcs.at(0).n_transitions_u, 3);
TEST_STRING_EQUAL(qc_criteria1.component_group_qcs.at(0).ion_ratio_pair_name_1, "component1.1.Light");
TEST_STRING_EQUAL(qc_criteria1.component_group_qcs.at(0).ion_ratio_pair_name_2, "component1.2.Light");
TEST_REAL_SIMILAR(qc_criteria1.component_group_qcs.at(0).ion_ratio_l, 0);
TEST_REAL_SIMILAR(qc_criteria1.component_group_qcs.at(0).ion_ratio_u, 60);
TEST_STRING_EQUAL(qc_criteria1.component_group_qcs.at(0).ion_ratio_feature_name, "peak_apex_int");
// transition 1
TEST_STRING_EQUAL(qc_criteria1.component_qcs.at(0).component_name, "component1.1.Heavy");
TEST_REAL_SIMILAR(qc_criteria1.component_qcs.at(0).retention_time_l, 0);
TEST_REAL_SIMILAR(qc_criteria1.component_qcs.at(0).retention_time_u, 3);
TEST_REAL_SIMILAR(qc_criteria1.component_qcs.at(0).intensity_l, 0);
TEST_REAL_SIMILAR(qc_criteria1.component_qcs.at(0).intensity_u, 5000);
TEST_REAL_SIMILAR(qc_criteria1.component_qcs.at(0).overall_quality_l, 0);
TEST_REAL_SIMILAR(qc_criteria1.component_qcs.at(0).overall_quality_u, 200);
TEST_REAL_SIMILAR(qc_criteria1.component_qcs.at(0).meta_value_qc["peak_apex_int"].first, 0);
TEST_REAL_SIMILAR(qc_criteria1.component_qcs.at(0).meta_value_qc["peak_apex_int"].second, 5000);
TEST_REAL_SIMILAR(qc_criteria1.component_qcs.at(0).meta_value_qc["peak_area"].first, 0);
TEST_REAL_SIMILAR(qc_criteria1.component_qcs.at(0).meta_value_qc["peak_area"].second, 0);
// Test calculateFilterValuesMean
std::vector<MRMFeatureQC> filter_values_test;
mrmff.EstimateDefaultMRMFeatureQCValues(samples, qc_criteria2, transitions, true);
// transition group 1
TEST_STRING_EQUAL(qc_criteria2.component_group_qcs.at(0).component_group_name, "component_group1");
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_heavy_l, 1);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_heavy_u, 1);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_light_l, 2);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_light_u, 2);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_detecting_l, 3);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_detecting_u, 3);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_quantifying_l, 2);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_quantifying_u, 2);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_identifying_l, 0);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_identifying_u, 0);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_transitions_l, 3);
TEST_EQUAL(qc_criteria2.component_group_qcs.at(0).n_transitions_u, 3);
TEST_STRING_EQUAL(qc_criteria2.component_group_qcs.at(0).ion_ratio_pair_name_1, "component1.1.Light");
TEST_STRING_EQUAL(qc_criteria2.component_group_qcs.at(0).ion_ratio_pair_name_2, "component1.2.Light");
TEST_REAL_SIMILAR(qc_criteria2.component_group_qcs.at(0).ion_ratio_l, 2.5);
TEST_REAL_SIMILAR(qc_criteria2.component_group_qcs.at(0).ion_ratio_u, 60);
TEST_STRING_EQUAL(qc_criteria2.component_group_qcs.at(0).ion_ratio_feature_name, "peak_apex_int");
// transition 1
TEST_STRING_EQUAL(qc_criteria2.component_qcs.at(0).component_name, "component1.1.Heavy");
TEST_REAL_SIMILAR(qc_criteria2.component_qcs.at(0).retention_time_l, 2);
TEST_REAL_SIMILAR(qc_criteria2.component_qcs.at(0).retention_time_u, 3);
TEST_REAL_SIMILAR(qc_criteria2.component_qcs.at(0).intensity_l, 1000);
TEST_REAL_SIMILAR(qc_criteria2.component_qcs.at(0).intensity_u, 5000);
TEST_REAL_SIMILAR(qc_criteria2.component_qcs.at(0).overall_quality_l, 100);
TEST_REAL_SIMILAR(qc_criteria2.component_qcs.at(0).overall_quality_u, 200);
TEST_REAL_SIMILAR(qc_criteria2.component_qcs.at(0).meta_value_qc["peak_apex_int"].first, 1000);
TEST_REAL_SIMILAR(qc_criteria2.component_qcs.at(0).meta_value_qc["peak_apex_int"].second, 5000);
TEST_REAL_SIMILAR(qc_criteria2.component_qcs.at(0).meta_value_qc["peak_area"].first, 0);
TEST_REAL_SIMILAR(qc_criteria2.component_qcs.at(0).meta_value_qc["peak_area"].second, 0);
}
END_SECTION
START_SECTION(void EstimatePercRSD(const std::vector<FeatureMap>& samples, MRMFeatureQC& filter_template, const TargetedExperiment& transitions))
{
MRMFeatureFilter mrmff;
//make the FeatureMap
std::vector<FeatureMap> samples;
FeatureMap components;
OpenMS::Feature component_1, subordinate;
std::vector<OpenMS::Feature> subordinates;
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 500);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
// transition group 2
// transition 1
subordinate.setMetaValue("native_id", "component2.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 1000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component2.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 1000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group2");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
// simulate triplicates with idententical values
// (sufficient to test for differences in the means/vars/rsds)
samples.push_back(components);
samples.push_back(components);
samples.push_back(components);
// make the targeted experiment
TargetedExperiment transitions;
ReactionMonitoringTransition transition;
// transition group 1
// transition 1
transition.setNativeID("component1.1.Heavy");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component1.1.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 3
transition.setNativeID("component1.2.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(false);
transitions.addTransition(transition);
// transition group 2
// transition 1
transition.setNativeID("component2.1.Heavy");
transition.setPeptideRef("component_group2");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component2.1.Light");
transition.setPeptideRef("component_group2");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
//make the QCs
MRMFeatureQC qc_criteria;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
std::pair<double, double> lbub(500, 4e6);
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 1;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 1;
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 2;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 2;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 3;
cgqcs.n_transitions_l = 3;
cgqcs.n_transitions_u = 3;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0.5;
cgqcs.ion_ratio_u = 2.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
cqcs.meta_value_qc["peak_area"] = lbub;
qc_criteria.component_qcs.push_back(cqcs);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
cqcs.meta_value_qc["peak_area"] = lbub;
qc_criteria.component_qcs.push_back(cqcs);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
cqcs.meta_value_qc["peak_area"] = lbub;
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
MRMFeatureQC filter_zeros = qc_criteria;
mrmff.EstimatePercRSD(samples, filter_zeros, transitions);
// transition group 1
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).component_group_name, "component_group1");
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_u, 0);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_1, "component1.1.Light");
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_2, "component1.2.Light");
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_u, 0);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_feature_name, "peak_apex_int");
// transition 1
TEST_STRING_EQUAL(filter_zeros.component_qcs.at(0).component_name, "component1.1.Heavy");
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].second, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].second, 0);
// transition 2
TEST_STRING_EQUAL(filter_zeros.component_qcs.at(1).component_name, "component1.1.Light");
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).retention_time_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).retention_time_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).intensity_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).intensity_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).overall_quality_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).overall_quality_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).meta_value_qc["peak_apex_int"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).meta_value_qc["peak_apex_int"].second, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).meta_value_qc["peak_area"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).meta_value_qc["peak_area"].second, 0);
// transition 3
TEST_STRING_EQUAL(filter_zeros.component_qcs.at(2).component_name, "component1.2.Light");
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).retention_time_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).retention_time_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).intensity_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).intensity_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).overall_quality_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).overall_quality_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).meta_value_qc["peak_apex_int"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).meta_value_qc["peak_apex_int"].second, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).meta_value_qc["peak_area"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).meta_value_qc["peak_area"].second, 0);
}
END_SECTION
START_SECTION(void EstimateBackgroundInterferences(const std::vector<FeatureMap>& samples, MRMFeatureQC& filter_template, const TargetedExperiment& transitions))
{
MRMFeatureFilter mrmff;
//make the FeatureMap
std::vector<FeatureMap> samples;
FeatureMap components;
OpenMS::Feature component_1, subordinate;
std::vector<OpenMS::Feature> subordinates;
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 500);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
// transition group 2
// transition 1
subordinate.setMetaValue("native_id", "component2.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 1000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component2.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 1000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group2");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
// simulate triplicates with idententical values
// (sufficient to test for differences in the means/vars/rsds)
samples.push_back(components);
samples.push_back(components);
samples.push_back(components);
// make the targeted experiment
TargetedExperiment transitions;
ReactionMonitoringTransition transition;
// transition group 1
// transition 1
transition.setNativeID("component1.1.Heavy");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component1.1.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 3
transition.setNativeID("component1.2.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(false);
transitions.addTransition(transition);
// transition group 2
// transition 1
transition.setNativeID("component2.1.Heavy");
transition.setPeptideRef("component_group2");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component2.1.Light");
transition.setPeptideRef("component_group2");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
//make the QCs
MRMFeatureQC qc_criteria;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
std::pair<double, double> lbub(500, 4e6);
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 1;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 1;
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 2;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 2;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 3;
cgqcs.n_transitions_l = 3;
cgqcs.n_transitions_u = 3;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0.5;
cgqcs.ion_ratio_u = 2.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
cqcs.meta_value_qc["peak_area"] = lbub;
qc_criteria.component_qcs.push_back(cqcs);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
qc_criteria.component_qcs.push_back(cqcs);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = lbub;
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
MRMFeatureQC filter_zeros = qc_criteria;
mrmff.EstimateBackgroundInterferences(samples, filter_zeros, transitions);
// transition group 1
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).component_group_name, "component_group1");
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_u, 1);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_u, 2);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_u, 3);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_u, 2);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_u, 3);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_1, "component1.1.Light");
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_2, "component1.2.Light");
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_u, 10);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_feature_name, "peak_apex_int");
// transition 1
TEST_STRING_EQUAL(filter_zeros.component_qcs.at(0).component_name, "component1.1.Heavy");
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_u, 2.5);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_u, 5000);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_u, 100);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].second, 5000);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].first, 500);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].second, 4e6);
// transition 2
TEST_STRING_EQUAL(filter_zeros.component_qcs.at(1).component_name, "component1.1.Light");
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).retention_time_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).retention_time_u, 2.5);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).intensity_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).intensity_u, 5000);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).overall_quality_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).overall_quality_u, 100);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).meta_value_qc["peak_apex_int"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).meta_value_qc["peak_apex_int"].second, 5000);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).meta_value_qc["peak_area"].first, 500);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(1).meta_value_qc["peak_area"].second, 4e6);
// transition 3
TEST_STRING_EQUAL(filter_zeros.component_qcs.at(2).component_name, "component1.2.Light");
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).retention_time_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).retention_time_u, 2.5);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).intensity_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).intensity_u, 5000);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).overall_quality_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).overall_quality_u, 100);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).meta_value_qc["peak_apex_int"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).meta_value_qc["peak_apex_int"].second, 500);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).meta_value_qc["peak_area"].first, 500);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(2).meta_value_qc["peak_area"].second, 4e6);
}
END_SECTION
START_SECTION(void accumulateFilterValues(std::vector<MRMFeatureQC>& filter_values, const std::vector<FeatureMap>& samples, const MRMFeatureQC& filter_template, const TargetedExperiment& transitions) const)
{
MRMFeatureFilter mrmff;
//make the FeatureMap
std::vector<FeatureMap> samples;
FeatureMap components;
OpenMS::Feature component_1, subordinate;
std::vector<OpenMS::Feature> subordinates;
// sample 1
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 500);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setRT(2.5);
component_1.setIntensity(15000);
component_1.setOverallQuality(300);
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
samples.push_back(components);
components.clear();
// sample 2
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(3.0);
subordinate.setIntensity(1000);
subordinate.setOverallQuality(200);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 1000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(3);
subordinate.setIntensity(1000);
subordinate.setOverallQuality(400);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 2000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(3.1);
subordinate.setIntensity(2000);
subordinate.setOverallQuality(300);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 800);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setRT(3);
component_1.setIntensity(5000);
component_1.setOverallQuality(200);
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
samples.push_back(components);
components.clear();
// sample 3
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(2);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(2);
subordinate.setIntensity(4000);
subordinate.setOverallQuality(150);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 6000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(2);
subordinate.setIntensity(1000);
subordinate.setOverallQuality(300);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 100);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setRT(2);
component_1.setIntensity(15000);
component_1.setOverallQuality(500);
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
samples.push_back(components);
components.clear();
// make the targeted experiment
TargetedExperiment transitions;
ReactionMonitoringTransition transition;
// transition group 1
// transition 1
transition.setNativeID("component1.1.Heavy");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 2
transition.setNativeID("component1.1.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(true);
transitions.addTransition(transition);
// transition 3
transition.setNativeID("component1.2.Light");
transition.setPeptideRef("component_group1");
transition.setDetectingTransition(true);
transition.setIdentifyingTransition(false);
transition.setQuantifyingTransition(false);
transitions.addTransition(transition);
// make the expected QCs values
std::vector<MRMFeatureQC> filter_values;
MRMFeatureQC qc_criteria1, qc_criteria2, qc_criteria3;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 0;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 0;
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 0;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 0;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 0;
cgqcs.n_transitions_l = 0;
cgqcs.n_transitions_u = 3;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 10;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1;
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 2.5;
cqcs.intensity_l = 0;
cqcs.intensity_u = 5000;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 100;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 5000);
cqcs.meta_value_qc["peak_area"] = std::make_pair(500, 4e6);
qc_criteria1.component_group_qcs.push_back(cgqcs);
qc_criteria1.component_qcs.push_back(cqcs);
filter_values.push_back(qc_criteria1);
// transition group 1;
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 0;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 0;
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 0;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 0;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 0;
cgqcs.n_transitions_l = 0;
cgqcs.n_transitions_u = 3;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 2.5;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1;
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 3;
cqcs.intensity_l = 0;
cqcs.intensity_u = 1000;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 200;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 1000);
cqcs.meta_value_qc["peak_area"] = std::make_pair(500, 4e6);
qc_criteria2.component_group_qcs.push_back(cgqcs);
qc_criteria2.component_qcs.push_back(cqcs);
filter_values.push_back(qc_criteria2);
// transition group 1;
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 0;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 0;
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 0;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 0;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 0;
cgqcs.n_transitions_l = 0;
cgqcs.n_transitions_u = 3;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 60;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1;
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 2;
cqcs.intensity_l = 0;
cqcs.intensity_u = 5000;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 100;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 5000);
cqcs.meta_value_qc["peak_area"] = std::make_pair(500, 4e6);
qc_criteria3.component_group_qcs.push_back(cgqcs);
qc_criteria3.component_qcs.push_back(cqcs);
filter_values.push_back(qc_criteria3);
// Test calculateFilterValuesMean
std::vector<MRMFeatureQC> filter_values_test;
mrmff.accumulateFilterValues(filter_values_test, samples, qc_criteria1, transitions);
for (size_t i = 0; i < filter_values.size(); ++i)
{
// transition group 1
TEST_STRING_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).component_group_name, filter_values.at(i).component_group_qcs.at(0).component_group_name);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_heavy_l, filter_values.at(i).component_group_qcs.at(0).n_heavy_l);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_heavy_u, filter_values.at(i).component_group_qcs.at(0).n_heavy_u);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_light_l, filter_values.at(i).component_group_qcs.at(0).n_light_l);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_light_u, filter_values.at(i).component_group_qcs.at(0).n_light_u);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_detecting_l, filter_values.at(i).component_group_qcs.at(0).n_detecting_l);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_detecting_u, filter_values.at(i).component_group_qcs.at(0).n_detecting_u);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_quantifying_l, filter_values.at(i).component_group_qcs.at(0).n_quantifying_l);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_quantifying_u, filter_values.at(i).component_group_qcs.at(0).n_quantifying_u);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_identifying_l, filter_values.at(i).component_group_qcs.at(0).n_identifying_l);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_identifying_u, filter_values.at(i).component_group_qcs.at(0).n_identifying_u);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_transitions_l, filter_values.at(i).component_group_qcs.at(0).n_transitions_l);
TEST_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).n_transitions_u, filter_values.at(i).component_group_qcs.at(0).n_transitions_u);
TEST_STRING_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).ion_ratio_pair_name_1, filter_values.at(i).component_group_qcs.at(0).ion_ratio_pair_name_1);
TEST_STRING_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).ion_ratio_pair_name_2, filter_values.at(i).component_group_qcs.at(0).ion_ratio_pair_name_2);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_group_qcs.at(0).ion_ratio_l, filter_values.at(i).component_group_qcs.at(0).ion_ratio_l);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_group_qcs.at(0).ion_ratio_u, filter_values.at(i).component_group_qcs.at(0).ion_ratio_u);
TEST_STRING_EQUAL(filter_values_test.at(i).component_group_qcs.at(0).ion_ratio_feature_name, filter_values.at(i).component_group_qcs.at(0).ion_ratio_feature_name);
// transition 1
TEST_STRING_EQUAL(filter_values_test.at(i).component_qcs.at(0).component_name, filter_values.at(i).component_qcs.at(0).component_name);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_qcs.at(0).retention_time_l, filter_values.at(i).component_qcs.at(0).retention_time_l);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_qcs.at(0).retention_time_u, filter_values.at(i).component_qcs.at(0).retention_time_u);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_qcs.at(0).intensity_l, filter_values.at(i).component_qcs.at(0).intensity_l);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_qcs.at(0).intensity_u, filter_values.at(i).component_qcs.at(0).intensity_u);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_qcs.at(0).overall_quality_l, filter_values.at(i).component_qcs.at(0).overall_quality_l);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_qcs.at(0).overall_quality_u, filter_values.at(i).component_qcs.at(0).overall_quality_u);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_qcs.at(0).meta_value_qc["peak_apex_int"].first, filter_values.at(i).component_qcs.at(0).meta_value_qc["peak_apex_int"].first);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_qcs.at(0).meta_value_qc["peak_apex_int"].second, filter_values.at(i).component_qcs.at(0).meta_value_qc["peak_apex_int"].second);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_qcs.at(0).meta_value_qc["peak_area"].first, filter_values.at(i).component_qcs.at(0).meta_value_qc["peak_area"].first);
TEST_REAL_SIMILAR(filter_values_test.at(i).component_qcs.at(0).meta_value_qc["peak_area"].second, filter_values.at(i).component_qcs.at(0).meta_value_qc["peak_area"].second);
}
}
END_SECTION
START_SECTION(void zeroFilterValues(MRMFeatureQC& filter_zeros, const MRMFeatureQC& filter_template) const)
{
MRMFeatureFilter mrmff;
//make the QCs
MRMFeatureQC qc_criteria;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 1;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 1;
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 2;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 2;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 3;
cgqcs.n_transitions_l = 3;
cgqcs.n_transitions_u = 3;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0.5;
cgqcs.ion_ratio_u = 2.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 2.0;
cqcs.retention_time_u = 3.0;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4e6;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(500, 4e6);
cqcs.meta_value_qc["peak_area"] = std::make_pair(500, 4e6);
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
//test for all zeros
MRMFeatureQC filter_zeros;
mrmff.zeroFilterValues(filter_zeros, qc_criteria);
// transition group 1
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).component_group_name, "component_group1");
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_u, 0);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_1, "component1.1.Light");
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_2, "component1.2.Light");
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_u, 0);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_feature_name, "peak_apex_int");
// transition 1
TEST_STRING_EQUAL(filter_zeros.component_qcs.at(0).component_name, "component1.1.Heavy");
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_l, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_u, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].second, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].first, 0);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].second, 0);
}
END_SECTION
START_SECTION(void calculateFilterValuesMean(MRMFeatureQC& filter_mean, const std::vector<MRMFeatureQC>& filter_values, const MRMFeatureQC& filter_template) const)
{ // Test Mean, Var, and PercRSD
MRMFeatureFilter mrmff;
//make the QCs
std::vector<MRMFeatureQC> filter_values;
MRMFeatureQC qc_criteria1, qc_criteria2, qc_criteria3;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 0;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 1;
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 2;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 2;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 3;
cgqcs.n_transitions_l = 3;
cgqcs.n_transitions_u = 3;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0.5;
cgqcs.ion_ratio_u = 2;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1;
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 2;
cqcs.retention_time_u = 3;
cqcs.intensity_l = 500;
cqcs.intensity_u = 4.00E+06;
cqcs.overall_quality_l = 100;
cqcs.overall_quality_u = 500;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(500, 4e6);
cqcs.meta_value_qc["peak_area"] = std::make_pair(500, 4e6);
qc_criteria1.component_group_qcs.push_back(cgqcs);
qc_criteria1.component_qcs.push_back(cqcs);
filter_values.push_back(qc_criteria1);
// transition group 1;
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 1;
cgqcs.n_heavy_u = 1;
cgqcs.n_light_l = 2;
cgqcs.n_light_u = 3;
cgqcs.n_detecting_l = 2;
cgqcs.n_detecting_u = 6;
cgqcs.n_quantifying_l = 2;
cgqcs.n_quantifying_u = 2;
cgqcs.n_identifying_l = 0;
cgqcs.n_identifying_u = 3;
cgqcs.n_transitions_l = 1;
cgqcs.n_transitions_u = 2;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0.25;
cgqcs.ion_ratio_u = 3;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1;
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 1;
cqcs.retention_time_u = 2;
cqcs.intensity_l = 400;
cqcs.intensity_u = 5.00E+05;
cqcs.overall_quality_l = 50;
cqcs.overall_quality_u = 700;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(400, 5e5);
cqcs.meta_value_qc["peak_area"] = std::make_pair(400, 5e5);
qc_criteria2.component_group_qcs.push_back(cgqcs);
qc_criteria2.component_qcs.push_back(cqcs);
filter_values.push_back(qc_criteria2);
// transition group 1;
cgqcs.component_group_name = "component_group1";
cgqcs.n_heavy_l = 1;
cgqcs.n_heavy_u = 2;
cgqcs.n_light_l = 1;
cgqcs.n_light_u = 2;
cgqcs.n_detecting_l = 2;
cgqcs.n_detecting_u = 3;
cgqcs.n_quantifying_l = 2;
cgqcs.n_quantifying_u = 4;
cgqcs.n_identifying_l = 1;
cgqcs.n_identifying_u = 3;
cgqcs.n_transitions_l = 0;
cgqcs.n_transitions_u = 4;
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0.4;
cgqcs.ion_ratio_u = 2;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1;
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 1;
cqcs.retention_time_u = 4;
cqcs.intensity_l = 500;
cqcs.intensity_u = 3.00E+06;
cqcs.overall_quality_l = 10;
cqcs.overall_quality_u = 600;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(500, 3e6);
cqcs.meta_value_qc["peak_area"] = std::make_pair(500, 3e6);
qc_criteria3.component_group_qcs.push_back(cgqcs);
qc_criteria3.component_qcs.push_back(cqcs);
filter_values.push_back(qc_criteria3);
// Test calculateFilterValuesMean
MRMFeatureQC filter_zeros;
mrmff.calculateFilterValuesMean(filter_zeros, filter_values, qc_criteria1); // transition group 1
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).component_group_name, "component_group1");
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_l, 0.666666667);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_u, 1.333333333);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_l, 1.333333333);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_u, 2.333333333);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_l, 2);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_u, 4);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_l, 2);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_u, 2.666666667);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_l, 0.333333333);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_u, 3);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_l, 1.333333333);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_u, 3);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_1, "component1.1.Light");
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_2, "component1.2.Light");
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_l, 0.383333333);
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_u, 2.333333333);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_feature_name, "peak_apex_int");
// transition 1
TEST_STRING_EQUAL(filter_zeros.component_qcs.at(0).component_name, "component1.1.Heavy");
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_l, 1.333333333);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_u, 3);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_l, 466.6666667);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_u, 2500000);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_l, 53.33333333);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_u, 600);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].first, 466.6666667);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].second, 2500000);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].first, 466.6666667);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].second, 2500000);
// Test calculateFilterValuesVar
MRMFeatureQC filter_means = filter_zeros;
mrmff.calculateFilterValuesVar(filter_zeros, filter_values, filter_means, qc_criteria1);
// transition group 1
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).component_group_name, "component_group1");
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_l, 1);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_l, 0.333333333);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_u, 0.333333333);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_u, 3);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_u, 2);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_l, 0.333333333);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_l, 2.333333333);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_u, 1);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_1, "component1.1.Light");
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_2, "component1.2.Light");
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_l, 0.015833333);
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_u, 0.333333333);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_feature_name, "peak_apex_int");
// transition 1
TEST_STRING_EQUAL(filter_zeros.component_qcs.at(0).component_name, "component1.1.Heavy");
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_l, 0.333333333);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_u, 1);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_l, 3333.333333);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_u, 3.25e12);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_l, 2033.333333);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_u, 10000);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].first, 3333.333333);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].second, 3.25e12);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].first, 3333.333333);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].second, 3.25e12);
// Test calculateFilterValuesPercRSD
MRMFeatureQC filter_vars = filter_zeros;
mrmff.calculateFilterValuesPercRSD(filter_zeros, filter_means, filter_vars);
// transition group 1
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).component_group_name, "component_group1");
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_heavy_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_light_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_detecting_u, 43.30127019);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_quantifying_u, 70);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_l, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_identifying_u, 0);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_l, 141);
TEST_EQUAL(filter_zeros.component_group_qcs.at(0).n_transitions_u, 33.33333333);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_1, "component1.1.Light");
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_pair_name_2, "component1.2.Light");
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_l, 32.82536711);
TEST_REAL_SIMILAR(filter_zeros.component_group_qcs.at(0).ion_ratio_u, 24.74358297);
TEST_STRING_EQUAL(filter_zeros.component_group_qcs.at(0).ion_ratio_feature_name, "peak_apex_int");
// transition 1
TEST_STRING_EQUAL(filter_zeros.component_qcs.at(0).component_name, "component1.1.Heavy");
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_l, 43.30127019);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).retention_time_u, 33.33333333);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_l, 12.37179148);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).intensity_u, 72.11102551);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_l, 84.54843287);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).overall_quality_u, 16.66666667);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].first, 12.37179148);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_apex_int"].second, 72.11102551);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].first, 12.37179148);
TEST_REAL_SIMILAR(filter_zeros.component_qcs.at(0).meta_value_qc["peak_area"].second, 72.11102551);
}
END_SECTION
START_SECTION(void FilterFeatureMapPercRSD(FeatureMap& features, MRMFeatureQC& filter_criteria, const MRMFeatureQC & filter_values))
{
/** FilterFeatureMap Test 1: basic ability to flag or filter transitions or transition groups */
MRMFeatureFilter mrmff;
//make the FeatureMap
FeatureMap components;
OpenMS::Feature component_1, subordinate;
std::vector<OpenMS::Feature> subordinates;
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 500); //should fail
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
// transition group 2
// transition 1
subordinate.setMetaValue("native_id", "component2.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 1000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component2.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 1000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group2");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
//make the %RSD filter criteria and %RSD calculated values
MRMFeatureQC qc_criteria, qc_rsd_values;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
// %RSD filter criteria (30% RSD for all values)
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 30.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
// transition group 2
cgqcs.component_group_name = "component_group2";
cgqcs.ion_ratio_pair_name_1 = "component2.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component2.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 30.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component2.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 2
cqcs.component_name = "component2.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
// Calculated %RSD values
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 30.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 20.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 10.0);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 10.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 100.0);
qc_rsd_values.component_group_qcs.push_back(cgqcs);
qc_rsd_values.component_qcs.push_back(cqcs);
// transition group 2
cgqcs.component_group_name = "component_group2";
cgqcs.ion_ratio_pair_name_1 = "component2.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component2.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 40.0; // should fail
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component2.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 2
cqcs.component_name = "component2.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 10.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
qc_rsd_values.component_group_qcs.push_back(cgqcs);
qc_rsd_values.component_qcs.push_back(cqcs);
//test flag mode
Param params;
params.setValue("flag_or_filter", "flag");
mrmff.setParameters(params);
mrmff.FilterFeatureMapPercRSD(components, qc_criteria, qc_rsd_values);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_pass"), false);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_message").toStringList()[0], "peak_apex_int");
TEST_EQUAL(components[1].getMetaValue("QC_transition_group_%RSD_pass"), false);
TEST_EQUAL(components[1].getMetaValue("QC_transition_group_%RSD_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[1].getMetaValue("QC_transition_group_%RSD_message").toStringList()[0], "ion_ratio_pair[component2.1.Light/component2.2.Light]");
TEST_EQUAL(components[1].getSubordinates()[0].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[1].getSubordinates()[1].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_score"), 0.75);
TEST_REAL_SIMILAR(components[1].getMetaValue("QC_transition_group_%RSD_score"), 0.75);
TEST_REAL_SIMILAR(components[1].getSubordinates()[0].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[1].getSubordinates()[1].getMetaValue("QC_transition_%RSD_score"), 1.0);
//test filter mode
params.setValue("flag_or_filter", "filter");
mrmff.setParameters(params);
mrmff.FilterFeatureMapPercRSD(components, qc_criteria, qc_rsd_values);
TEST_EQUAL(components.size(), 1);
TEST_EQUAL(components[0].getSubordinates().size(), 2);
}
END_SECTION
START_SECTION(void FilterFeatureMapPercRSD(FeatureMap& features, MRMFeatureQC& filter_criteria, const MRMFeatureQC & filter_values))
{
/** FilterFeatureMap Test 2: tests for individual checks on each transition and transition group */
MRMFeatureFilter mrmff;
//make the FeatureMap
FeatureMap components;
OpenMS::Feature component_1, subordinate;
std::vector<OpenMS::Feature> subordinates;
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
//make the %RSD filter criteria and %RSD calculated values
MRMFeatureQC qc_criteria, qc_rsd_values;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
// %RSD filter criteria (30% RSD for all values)
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 30.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
// Calculated %RSD values
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 30.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 20.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 10.0);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 10.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 1.0);
qc_rsd_values.component_group_qcs.push_back(cgqcs);
qc_rsd_values.component_qcs.push_back(cqcs);
//test all possible comparisons
Param params;
params.setValue("flag_or_filter", "flag");
mrmff.setParameters(params);
mrmff.FilterFeatureMapPercRSD(components, qc_criteria, qc_rsd_values);
// control
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_score"), 1.0);
// RT
qc_rsd_values.component_group_qcs.clear();
qc_rsd_values.component_qcs.clear();
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 30.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 20.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 10.0);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 10.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 80.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 1.0);
qc_rsd_values.component_group_qcs.push_back(cgqcs);
qc_rsd_values.component_qcs.push_back(cqcs);
mrmff.FilterFeatureMapPercRSD(components, qc_criteria, qc_rsd_values);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_pass"), false);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_message").toStringList()[0], "retention_time");
// Intensity
qc_rsd_values.component_group_qcs.clear();
qc_rsd_values.component_qcs.clear();
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 30.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 20.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 10.0);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 10.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 100.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 1.0);
qc_rsd_values.component_group_qcs.push_back(cgqcs);
qc_rsd_values.component_qcs.push_back(cqcs);
mrmff.FilterFeatureMapPercRSD(components, qc_criteria, qc_rsd_values);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_pass"), false);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_message").toStringList()[0], "intensity");
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_score"), 0.75);
// OverallQuality
qc_rsd_values.component_group_qcs.clear();
qc_rsd_values.component_qcs.clear();
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 30.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 20.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 10.0);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 10.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 300.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 1.0);
qc_rsd_values.component_group_qcs.push_back(cgqcs);
qc_rsd_values.component_qcs.push_back(cqcs);
mrmff.FilterFeatureMapPercRSD(components, qc_criteria, qc_rsd_values);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_pass"), false);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_message").toStringList()[0], "overall_quality");
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_score"), 0.75);
// MetaValue
qc_rsd_values.component_group_qcs.clear();
qc_rsd_values.component_qcs.clear();
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 30.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 20.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 10.0);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 10.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 10.0);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 100.0);
qc_rsd_values.component_group_qcs.push_back(cgqcs);
qc_rsd_values.component_qcs.push_back(cqcs);
mrmff.FilterFeatureMapPercRSD(components, qc_criteria, qc_rsd_values);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_pass"), false);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_message").toStringList()[0], "peak_apex_int");
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_score"), 0.75);
// ion_ratio_pair
qc_rsd_values.component_group_qcs.clear();
qc_rsd_values.component_qcs.clear();
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.ion_ratio_pair_name_1 = "component1.1.Light";
cgqcs.ion_ratio_pair_name_2 = "component1.2.Light";
cgqcs.ion_ratio_l = 0;
cgqcs.ion_ratio_u = 50.0;
cgqcs.ion_ratio_feature_name = "peak_apex_int";
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 20.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 10.0);
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 10.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 20.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 30.0);
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.retention_time_l = 0;
cqcs.retention_time_u = 30.0;
cqcs.intensity_l = 0;
cqcs.intensity_u = 10.0;
cqcs.overall_quality_l = 0;
cqcs.overall_quality_u = 30.0;
cqcs.meta_value_qc["peak_apex_int"] = std::make_pair(0, 1.0);
qc_rsd_values.component_group_qcs.push_back(cgqcs);
qc_rsd_values.component_qcs.push_back(cqcs);
mrmff.FilterFeatureMapPercRSD(components, qc_criteria, qc_rsd_values);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_%RSD_pass"), false);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_%RSD_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getMetaValue("QC_transition_group_%RSD_message").toStringList()[0], "ion_ratio_pair[component1.1.Light/component1.2.Light]");
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_pass"), true);
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_%RSD_score"), 0.75);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_%RSD_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_%RSD_score"), 1.0);
}
END_SECTION
START_SECTION(void FilterFeatureMapBackgroundInterference(FeatureMap& features, MRMFeatureQC& filter_criteria, const MRMFeatureQC & filter_values))
{
/** FilterFeatureMap Test 1: basic ability to flag or filter transitions or transition groups */
MRMFeatureFilter mrmff;
//make the FeatureMap
FeatureMap components;
OpenMS::Feature component_1, subordinate;
std::vector<OpenMS::Feature> subordinates;
// transition group 1
// transition 1
subordinate.setMetaValue("native_id", "component1.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component1.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 5000);
subordinates.push_back(subordinate);
// transition 3
subordinate.setMetaValue("native_id", "component1.2.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 500); //should fail
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group1");
component_1.setIntensity(5000);
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
// transition group 2
// transition 1
subordinate.setMetaValue("native_id", "component2.1.Heavy");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Heavy");
subordinate.setMetaValue("peak_apex_int", 1000);
subordinates.push_back(subordinate);
// transition 2
subordinate.setMetaValue("native_id", "component2.1.Light");
subordinate.setRT(2.5);
subordinate.setIntensity(5000);
subordinate.setOverallQuality(100);
subordinate.setMetaValue("LabelType", "Light");
subordinate.setMetaValue("peak_apex_int", 1000);
subordinates.push_back(subordinate);
component_1.setMetaValue("PeptideRef", "component_group2");
component_1.setIntensity(5000);
component_1.setSubordinates(subordinates);
components.push_back(component_1);
subordinates.clear();
//make the %BackgroundInterference filter criteria and %BackgroundInterference calculated values
MRMFeatureQC qc_criteria, qc_background_values;
MRMFeatureQC::ComponentGroupQCs cgqcs;
MRMFeatureQC::ComponentQCs cqcs;
// %BackgroundInterference filter criteria (30% BackgroundInterference for all values)
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.intensity_l = 0;
cgqcs.intensity_u = 30;
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
// transition group 2
cgqcs.component_group_name = "component_group2";
cgqcs.intensity_l = 0;
cgqcs.intensity_u = 30;
// transition 1
cqcs.component_name = "component2.1.Heavy";
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
// transition 2
cqcs.component_name = "component2.1.Light";
cqcs.intensity_l = 0;
cqcs.intensity_u = 30.0;
qc_criteria.component_group_qcs.push_back(cgqcs);
qc_criteria.component_qcs.push_back(cqcs);
// Calculated %BackgroundInterference values
// transition group 1
cgqcs.component_group_name = "component_group1";
cgqcs.intensity_l = 0;
cgqcs.intensity_u = 0;
// transition 1
cqcs.component_name = "component1.1.Heavy";
cqcs.intensity_l = 0;
cqcs.intensity_u = 0.0;
// transition 2
cqcs.component_name = "component1.1.Light";
cqcs.intensity_l = 0;
cqcs.intensity_u = 0.0;
// transition 3
cqcs.component_name = "component1.2.Light";
cqcs.intensity_l = 0;
cqcs.intensity_u = 10000.0;
qc_background_values.component_group_qcs.push_back(cgqcs);
qc_background_values.component_qcs.push_back(cqcs);
// transition group 2
cgqcs.component_group_name = "component_group2";
cgqcs.intensity_l = 0;
cgqcs.intensity_u = 10000;
// transition 1
cqcs.component_name = "component2.1.Heavy";
cqcs.intensity_l = 0;
cqcs.intensity_u = 0;
// transition 2
cqcs.component_name = "component2.1.Light";
cqcs.intensity_l = 0;
cqcs.intensity_u = 0;
qc_background_values.component_group_qcs.push_back(cgqcs);
qc_background_values.component_qcs.push_back(cqcs);
//test flag mode
Param params;
params.setValue("flag_or_filter", "flag");
mrmff.setParameters(params);
mrmff.FilterFeatureMapBackgroundInterference(components, qc_criteria, qc_background_values);
TEST_EQUAL(components[0].getMetaValue("QC_transition_group_%BackgroundInterference_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[0].getMetaValue("QC_transition_%BackgroundInterference_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[1].getMetaValue("QC_transition_%BackgroundInterference_pass"), true);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%BackgroundInterference_pass"), false);
TEST_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%BackgroundInterference_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[0].getSubordinates()[2].getMetaValue("QC_transition_%BackgroundInterference_message").toStringList()[0], "intensity");
TEST_EQUAL(components[1].getMetaValue("QC_transition_group_%BackgroundInterference_pass"), false);
TEST_EQUAL(components[1].getMetaValue("QC_transition_group_%BackgroundInterference_message").toStringList().size(), 1);
TEST_STRING_EQUAL(components[1].getMetaValue("QC_transition_group_%BackgroundInterference_message").toStringList()[0], "intensity");
TEST_EQUAL(components[1].getSubordinates()[0].getMetaValue("QC_transition_%BackgroundInterference_pass"), true);
TEST_EQUAL(components[1].getSubordinates()[1].getMetaValue("QC_transition_%BackgroundInterference_pass"), true);
TEST_REAL_SIMILAR(components[0].getMetaValue("QC_transition_group_%BackgroundInterference_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[0].getMetaValue("QC_transition_%BackgroundInterference_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[1].getMetaValue("QC_transition_%BackgroundInterference_score"), 1.0);
TEST_REAL_SIMILAR(components[0].getSubordinates()[2].getMetaValue("QC_transition_%BackgroundInterference_score"), 0.0);
TEST_REAL_SIMILAR(components[1].getMetaValue("QC_transition_group_%BackgroundInterference_score"), 0.0);
TEST_REAL_SIMILAR(components[1].getSubordinates()[0].getMetaValue("QC_transition_%BackgroundInterference_score"), 1.0);
TEST_REAL_SIMILAR(components[1].getSubordinates()[1].getMetaValue("QC_transition_%BackgroundInterference_score"), 1.0);
//test filter mode
params.setValue("flag_or_filter", "filter");
mrmff.setParameters(params);
mrmff.FilterFeatureMapBackgroundInterference(components, qc_criteria, qc_background_values);
TEST_EQUAL(components.size(), 1);
TEST_EQUAL(components[0].getSubordinates().size(), 2);
}
END_SECTION
START_SECTION(double calculateRTDifference(Feature & component_1, Feature & component_2))
{
MRMFeatureFilter mrmff;
Feature f1, f2;
f1.setRT(100.0);
f2.setRT(105.5);
double rt_diff = mrmff.calculateRTDifference(f1, f2);
TEST_REAL_SIMILAR(rt_diff, 5.5);
// Test with reversed order (should give same absolute difference)
rt_diff = mrmff.calculateRTDifference(f2, f1);
TEST_REAL_SIMILAR(rt_diff, 5.5);
}
END_SECTION
START_SECTION(double calculateResolution(Feature & component_1, Feature & component_2))
{
MRMFeatureFilter mrmff;
Feature f1, f2;
f1.setRT(100.0);
f1.setMetaValue("width_at_50", 2.0); // FWHM = 2.0
f2.setRT(106.0);
f2.setMetaValue("width_at_50", 2.0); // FWHM = 2.0
// Resolution = 2 * |RT2 - RT1| / (W1 + W2)
// where W = FWHM * 1.7 (width at base)
// Resolution = 2 * 6 / (3.4 + 3.4) = 12 / 6.8 ≈ 1.7647
double resolution = mrmff.calculateResolution(f1, f2);
TEST_REAL_SIMILAR(resolution, 1.7647);
// Test with zero width (should return 0)
Feature f3, f4;
f3.setRT(100.0);
f4.setRT(106.0);
// No width_at_50 metavalue and default width is 0
resolution = mrmff.calculateResolution(f3, f4);
TEST_REAL_SIMILAR(resolution, 0.0);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/DTAFile_test.cpp | .cpp | 9,531 | 360 | // 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/DTAFile.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
///////////////////////////
START_TEST(DTAFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
DTAFile* ptr = nullptr;
DTAFile* nullPointer = nullptr;
START_SECTION(DTAFile())
ptr = new DTAFile;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~DTAFile())
delete ptr;
END_SECTION
START_SECTION(template<typename SpectrumType> void load(const String& filename, SpectrumType& spectrum) )
TOLERANCE_ABSOLUTE(0.01)
MSSpectrum s;
DTAFile f1;
TEST_EXCEPTION(Exception::FileNotFound, f1.load("data_Idontexist",s);)
f1.load(OPENMS_GET_TEST_DATA_PATH("DTAFile_test.dta"),s);
TEST_EQUAL(s.size(), 25);
TEST_EQUAL(s.getPrecursors().size(), 1);
TEST_REAL_SIMILAR(s.getPrecursors()[0].getMZ(), 582.40666)
TEST_EQUAL(s.getPrecursors()[0].getCharge(), 3)
ABORT_IF(s.size() != 25)
MSSpectrum::ConstIterator it(s.begin());
TEST_REAL_SIMILAR(it->getPosition()[0], 139.42)
TEST_REAL_SIMILAR(it->getIntensity(), 318.52)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 149.93)
TEST_REAL_SIMILAR(it->getIntensity(), 61870.99)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 169.65)
TEST_REAL_SIMILAR(it->getIntensity(), 62074.22)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 189.30)
TEST_REAL_SIMILAR(it->getIntensity(), 53737.85)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 202.28)
TEST_REAL_SIMILAR(it->getIntensity(), 49410.25)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 207.82)
TEST_REAL_SIMILAR(it->getIntensity(), 17038.71)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 219.72)
TEST_REAL_SIMILAR(it->getIntensity(), 73629.98)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 230.02)
TEST_REAL_SIMILAR(it->getIntensity(), 47218.89)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 231.51)
TEST_REAL_SIMILAR(it->getIntensity(), 89935.22)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 263.88)
TEST_REAL_SIMILAR(it->getIntensity(), 81685.67)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 318.38)
TEST_REAL_SIMILAR(it->getIntensity(), 11876.49)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 362.22)
TEST_REAL_SIMILAR(it->getIntensity(), 91984.30)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 389.84)
TEST_REAL_SIMILAR(it->getIntensity(), 35049.17)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 489.86)
TEST_REAL_SIMILAR(it->getIntensity(), 55259.42)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 508.47)
TEST_REAL_SIMILAR(it->getIntensity(), 63411.68)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 521.44)
TEST_REAL_SIMILAR(it->getIntensity(), 42096.49)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 546.98)
TEST_REAL_SIMILAR(it->getIntensity(), 7133.92)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 562.72)
TEST_REAL_SIMILAR(it->getIntensity(), 47540.11)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 579.61)
TEST_REAL_SIMILAR(it->getIntensity(), 63350.29)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 600.60)
TEST_REAL_SIMILAR(it->getIntensity(), 29075.85)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 628.64)
TEST_REAL_SIMILAR(it->getIntensity(), 41030.62)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 629.66)
TEST_REAL_SIMILAR(it->getIntensity(), 51153.79)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 630.37)
TEST_REAL_SIMILAR(it->getIntensity(), 31411.63)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 652.64)
TEST_REAL_SIMILAR(it->getIntensity(), 26967.56)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 712.18)
TEST_REAL_SIMILAR(it->getIntensity(), 29235.72)
//TEST WITH Peak1D
MSSpectrum s2;
f1.load(OPENMS_GET_TEST_DATA_PATH("DTAFile_test.dta"),s2);
TEST_EQUAL(s2.size(), 25);
TEST_EQUAL(s2.getPrecursors().size(), 1);
TEST_REAL_SIMILAR(s2.getPrecursors()[0].getMZ(), 582.4066)
TEST_EQUAL(s2.getPrecursors()[0].getCharge(), 3)
ABORT_IF(s2.size() != 25)
MSSpectrum::ConstIterator it2(s2.begin());
TEST_REAL_SIMILAR(it2->getPosition()[0], 139.42)
TEST_REAL_SIMILAR(it2->getIntensity(), 318.52)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 149.93)
TEST_REAL_SIMILAR(it2->getIntensity(), 61870.99)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 169.65)
TEST_REAL_SIMILAR(it2->getIntensity(), 62074.22)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 189.30)
TEST_REAL_SIMILAR(it2->getIntensity(), 53737.85)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 202.28)
TEST_REAL_SIMILAR(it2->getIntensity(), 49410.25)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 207.82)
TEST_REAL_SIMILAR(it2->getIntensity(), 17038.71)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 219.72)
TEST_REAL_SIMILAR(it2->getIntensity(), 73629.98)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 230.02)
TEST_REAL_SIMILAR(it2->getIntensity(), 47218.89)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 231.51)
TEST_REAL_SIMILAR(it2->getIntensity(), 89935.22)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 263.88)
TEST_REAL_SIMILAR(it2->getIntensity(), 81685.67)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 318.38)
TEST_REAL_SIMILAR(it2->getIntensity(), 11876.49)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 362.22)
TEST_REAL_SIMILAR(it2->getIntensity(), 91984.30)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 389.84)
TEST_REAL_SIMILAR(it2->getIntensity(), 35049.17)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 489.86)
TEST_REAL_SIMILAR(it2->getIntensity(), 55259.42)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 508.47)
TEST_REAL_SIMILAR(it2->getIntensity(), 63411.68)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 521.44)
TEST_REAL_SIMILAR(it2->getIntensity(), 42096.49)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 546.98)
TEST_REAL_SIMILAR(it2->getIntensity(), 7133.92)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 562.72)
TEST_REAL_SIMILAR(it2->getIntensity(), 47540.11)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 579.61)
TEST_REAL_SIMILAR(it2->getIntensity(), 63350.29)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 600.60)
TEST_REAL_SIMILAR(it2->getIntensity(), 29075.85)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 628.64)
TEST_REAL_SIMILAR(it2->getIntensity(), 41030.62)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 629.66)
TEST_REAL_SIMILAR(it2->getIntensity(), 51153.79)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 630.37)
TEST_REAL_SIMILAR(it2->getIntensity(), 31411.63)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 652.64)
TEST_REAL_SIMILAR(it2->getIntensity(), 26967.56)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 712.18)
TEST_REAL_SIMILAR(it2->getIntensity(), 29235.72)
END_SECTION
START_SECTION(template<typename SpectrumType> void store(const String& filename, const SpectrumType& spectrum) const )
String filename;
NEW_TMP_FILE(filename);
DTAFile dta;
MSSpectrum spec, spec2;
MSSpectrum::PeakType peak;
spec.getPrecursors().resize(1);
spec.getPrecursors()[0].setMZ(582.40666);
spec.getPrecursors()[0].setCharge(3);
peak.getPosition()[0] = 11.4;
peak.setIntensity(11.5);
spec.push_back(peak);
peak.getPosition()[0] = 12.4;
peak.setIntensity(12.5);
spec.push_back(peak);
peak.getPosition()[0] = 13.4;
peak.setIntensity(13.5);
spec.push_back(peak);
//store file
dta.store(filename,spec);
//load file
dta.load(filename,spec2);
TEST_EQUAL(spec2.getPrecursors().size(),1)
TEST_REAL_SIMILAR(spec2.getPrecursors()[0].getMZ(),582.40666)
TEST_EQUAL(spec2.getPrecursors()[0].getCharge(),3)
ABORT_IF(spec2.size() != 3)
MSSpectrum::ConstIterator it = spec2.begin();
TEST_REAL_SIMILAR(it->getPosition()[0], 11.4)
TEST_REAL_SIMILAR(it->getIntensity(), 11.5)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 12.4)
TEST_REAL_SIMILAR(it->getIntensity(), 12.5)
++it;
TEST_REAL_SIMILAR(it->getPosition()[0], 13.4)
TEST_REAL_SIMILAR(it->getIntensity(), 13.5)
//TEST WITH std::vector and Peak1D
MSSpectrum raw_spec, raw_spec2;
MSSpectrum::PeakType raw_peak;
raw_peak.getPosition()[0] = 11.4;
raw_peak.setIntensity(11.5);
raw_spec.push_back(raw_peak);
raw_peak.getPosition()[0] = 12.4;
raw_peak.setIntensity(12.5);
raw_spec.push_back(raw_peak);
raw_peak.getPosition()[0] = 13.4;
raw_peak.setIntensity(13.5);
raw_spec.push_back(raw_peak);
//store file
dta.store(filename,raw_spec);
//load file
dta.load(filename,raw_spec2);
ABORT_IF(raw_spec2.size() != 3)
MSSpectrum::ConstIterator it2 = raw_spec2.begin();
TEST_REAL_SIMILAR(it2->getPosition()[0], 11.4)
TEST_REAL_SIMILAR(it2->getIntensity(), 11.5)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 12.4)
TEST_REAL_SIMILAR(it2->getIntensity(), 12.5)
++it2;
TEST_REAL_SIMILAR(it2->getPosition()[0], 13.4)
TEST_REAL_SIMILAR(it2->getIntensity(), 13.5)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/DIAScoring_test.cpp | .cpp | 34,210 | 878 | // 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/DIAScoring.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DIAHelper.h>
#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h>
#include "OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h"
#include "OpenMS/OPENSWATHALGO/DATAACCESS/MockObjects.h"
using namespace std;
using namespace OpenMS;
using namespace OpenSwath;
void getMRMFeatureTest(MockMRMFeature * imrmfeature_test)
{
std::shared_ptr<MockFeature> f1_ptr = std::shared_ptr<MockFeature>(new MockFeature());
std::shared_ptr<MockFeature> f2_ptr = std::shared_ptr<MockFeature>(new MockFeature());
f1_ptr->m_intensity = 0.3f;
f2_ptr->m_intensity = 0.7f;
std::map<std::string, std::shared_ptr<MockFeature> > features;
features["group1"] = f1_ptr;
features["group2"] = f2_ptr;
imrmfeature_test->m_features = features;
imrmfeature_test->m_intensity = 1.0;
}
OpenSwath::SpectrumPtr prepareIMSpectrum()
{
OpenSwath::SpectrumPtr sptr = (OpenSwath::SpectrumPtr)(new OpenSwath::Spectrum);
std::vector<OpenSwath::BinaryDataArrayPtr> binaryDataArrayPtrs;
OpenSwath::BinaryDataArrayPtr mz = (OpenSwath::BinaryDataArrayPtr)(new OpenSwath::BinaryDataArray);
OpenSwath::BinaryDataArrayPtr intensity = (OpenSwath::BinaryDataArrayPtr)(new OpenSwath::BinaryDataArray);
OpenSwath::BinaryDataArrayPtr im = (OpenSwath::BinaryDataArrayPtr)(new OpenSwath::BinaryDataArray);
std::vector<double> intensityVector = {
10, 20, 50, 100, 50, 20, 10, // peak at 499 -> 260-20 = 240 intensity within 0.05 Th
3, 7, 15, 30, 200000, 15, 7, 3, // peak at 500 -> 80-6 = 74 intensity within 0.05 Th
1, 3, 9, 15, 9, 3, 1, // peak at 501 -> 41-2 = 39 intensity within 0.05 Th
3, 9, 3, // peak at 502 -> 15 intensity within 0.05 Th
10, 20, 50, 100, 50, 20, 10, // peak at 600 -> 260-20 = 240 intensity within 0.05 Th
3, 7, 15, 30, 15, 7, 3, // peak at 601 -> 80-6 = 74 intensity within 0.05 Th
1, 3, 9, 15, 9, 3, 1, // peak at 602 -> sum([ 9, 15, 9, 3, 1]) = 37 intensity within 0.05 Th
3, 9, 200000, 3 // peak at 603 (strong interfering signal (200000) separated out by IM
};
std::vector<double> mzVector = {
498.97, 498.98, 498.99, 499.0, 499.01, 499.02, 499.03,
499.97, 499.98, 499.99, 500.0, 500.005, 500.01, 500.02, 500.03, // Add interfering 500.025 peak at different IM
500.97, 500.98, 500.99, 501.0, 501.01, 501.02, 501.03,
501.99, 502.0, 502.01,
599.97, 599.98, 599.99, 600.0, 600.01, 600.02, 600.03,
600.97, 600.98, 600.99, 601.0, 601.01, 601.02, 601.03,
// note that this peak at 602 is special since it is integrated from
// [(600+2*1.0033548) - 0.025, (600+2*1.0033548) + 0.025] = [601.9817096 to 602.0317096]
601.97, 601.98, 601.99, 602.0, 602.01, 602.02, 602.03,
602.99, 603.0, 603.01, 603.01
};
std::vector<double> imVector = {
2, 3, 2, 3, 4, 2, 3,
2, 3, 2, 3, 6, 2, 3, 3, // Note the interfering signal has an IM of 6 while all others have IM range of 2-4
2, 3, 2, 3, 4, 2, 3,
2, 3, 3,
2, 3, 2, 3, 4, 2, 3,
2, 3, 2, 3, 4, 2, 3,
2, 3, 2, 3, 4, 2, 3,
2, 3, 6, 3, // Note the interfering signal has an IM of 6 while all others have IM range of 2-4
};
TEST_EQUAL(imVector.size(), mzVector.size());
TEST_EQUAL(imVector.size(), intensityVector.size());
mz->data = mzVector;
intensity->data = intensityVector;
im->data = imVector;
im->description = "Ion Mobility";
sptr->setMZArray( mz );
sptr->setIntensityArray( intensity );
sptr->getDataArrays().push_back( im );
return sptr;
}
OpenSwath::SpectrumPtr prepareSpectrum()
{
OpenSwath::SpectrumPtr sptr = (OpenSwath::SpectrumPtr)(new OpenSwath::Spectrum);
std::vector<OpenSwath::BinaryDataArrayPtr> binaryDataArrayPtrs;
OpenSwath::BinaryDataArrayPtr data1 = (OpenSwath::BinaryDataArrayPtr)(new OpenSwath::BinaryDataArray);
OpenSwath::BinaryDataArrayPtr data2 = (OpenSwath::BinaryDataArrayPtr)(new OpenSwath::BinaryDataArray);
std::vector<double> intensity = {
10, 20, 50, 100, 50, 20, 10, // peak at 499 -> 260-20 = 240 intensity within 0.05 Th
3, 7, 15, 30, 15, 7, 3, // peak at 500 -> 80-6 = 74 intensity within 0.05 Th
1, 3, 9, 15, 9, 3, 1, // peak at 501 -> 41-2 = 39 intensity within 0.05 Th
3, 9, 3, // peak at 502 -> 15 intensity within 0.05 Th
10, 20, 50, 100, 50, 20, 10, // peak at 600 -> 260-20 = 240 intensity within 0.05 Th
3, 7, 15, 30, 15, 7, 3, // peak at 601 -> 80-6 = 74 intensity within 0.05 Th
1, 3, 9, 15, 9, 3, 1, // peak at 602 -> sum([ 9, 15, 9, 3, 1]) = 37 intensity within 0.05 Th
3, 9, 3 // peak at 603
};
std::vector<double> mz = {
498.97, 498.98, 498.99, 499.0, 499.01, 499.02, 499.03,
499.97, 499.98, 499.99, 500.0, 500.01, 500.02, 500.03,
500.97, 500.98, 500.99, 501.0, 501.01, 501.02, 501.03,
501.99, 502.0, 502.01,
599.97, 599.98, 599.99, 600.0, 600.01, 600.02, 600.03,
600.97, 600.98, 600.99, 601.0, 601.01, 601.02, 601.03,
// note that this peak at 602 is special since it is integrated from
// [(600+2*1.0033548) - 0.025, (600+2*1.0033548) + 0.025] = [601.9817096 to 602.0317096]
601.97, 601.98, 601.99, 602.0, 602.01, 602.02, 602.03,
602.99, 603.0, 603.01
};
data1->data = mz;
data2->data = intensity;
sptr->setMZArray( data1 );
sptr->setIntensityArray( data2 );
return sptr;
}
SpectrumSequence prepareSpectrumSequence()
{
OpenSwath::SpectrumPtr sptr = prepareSpectrum();
SpectrumSequence out;
out.push_back(sptr);
return out;
}
SpectrumSequence prepareIMSpectrumSequence()
{
OpenSwath::SpectrumPtr sptr = prepareIMSpectrum();
SpectrumSequence out;
out.push_back(sptr);
return out;
}
SpectrumSequence prepareShiftedSpectrum()
{
OpenSwath::SpectrumPtr sptr = prepareSpectrum();
// shift the peaks by a fixed amount in ppm
for (std::size_t i = 0; i < sptr->getMZArray()->data.size() / 2.0; i++)
{
sptr->getMZArray()->data[i] += sptr->getMZArray()->data[i] / 1000000 * 15; // shift first peak by 15 ppm
}
for (std::size_t i = sptr->getMZArray()->data.size() / 2.0; i < sptr->getMZArray()->data.size(); i++)
{
sptr->getMZArray()->data[i] += sptr->getMZArray()->data[i] / 1000000 * 10; // shift second peak by 10 ppm
}
SpectrumSequence out;
out.push_back(sptr);
return out;
}
SpectrumSequence prepareShiftedSpectrumIM()
{
OpenSwath::SpectrumPtr sptr = prepareIMSpectrum();
// shift the peaks by a fixed amount in ppm
for (std::size_t i = 0; i < sptr->getMZArray()->data.size() / 2.0; i++)
{
sptr->getMZArray()->data[i] += sptr->getMZArray()->data[i] / 1000000 * 15; // shift first peak by 15 ppm
}
for (std::size_t i = sptr->getMZArray()->data.size() / 2.0; i < sptr->getMZArray()->data.size(); i++)
{
sptr->getMZArray()->data[i] += sptr->getMZArray()->data[i] / 1000000 * 10; // shift second peak by 10 ppm
}
SpectrumSequence out;
out.push_back(sptr);
return out;
}
START_TEST(DIAScoring, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
DIAScoring diascoring_t;
// diascoring.set_dia_parameters(0.05, false, 30, 50, 4, 4); // here we use a large enough window so that none of our peaks falls out
Param p_dia = diascoring_t.getDefaults();
p_dia.setValue("dia_extraction_window", 0.05);
p_dia.setValue("dia_extraction_unit", "Th");
p_dia.setValue("dia_centroided", "false");
p_dia.setValue("dia_byseries_intensity_min", 30.0);
p_dia.setValue("dia_byseries_ppm_diff", 50.0);
p_dia.setValue("dia_nr_isotopes", 4);
p_dia.setValue("dia_nr_charges", 4);
Param p_dia_large = p_dia;
p_dia_large.setValue("dia_extraction_window", 0.5);
DIAScoring* ptr = nullptr;
DIAScoring* nullPointer = nullptr;
START_SECTION(DIAScoring())
{
ptr = new DIAScoring();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~DIAScoring())
{
delete ptr;
}
END_SECTION
START_SECTION(([EXTRA] void MRMFeatureScoring::getBYSeries(AASequence& a, int charge, std::vector<double>& bseries, std::vector<double>& yseries)))
{
OpenMS::DIAScoring diascoring;
String sequence = "SYVAWDR";
std::vector<double> bseries, yseries;
OpenMS::AASequence a = OpenMS::AASequence::fromString(sequence);
TheoreticalSpectrumGenerator generator;
Param p;
p.setValue("add_metainfo", "true",
"Adds the type of peaks as metainfo to the peaks, like y8+, [M-H2O+2H]++");
generator.setParameters(p);
OpenMS::DIAHelpers::getBYSeries(a, bseries, yseries, &generator, 1);
TEST_EQUAL(bseries.size(), 5)
TEST_EQUAL(yseries.size(), 6)
//TEST_REAL_SIMILAR (bseries[0], 88.03990 );
TEST_REAL_SIMILAR (bseries[0], 251.10323 );
TEST_REAL_SIMILAR (bseries[1], 350.17164 );
TEST_REAL_SIMILAR (bseries[2], 421.20875 );
TEST_REAL_SIMILAR (bseries[3], 607.28807 );
TEST_REAL_SIMILAR (bseries[4], 722.31501 );
//TEST_REAL_SIMILAR (bseries[5], 878.41612 );
TEST_REAL_SIMILAR (yseries[0], 175.11955 );
TEST_REAL_SIMILAR (yseries[1], 290.14649 );
TEST_REAL_SIMILAR (yseries[2], 476.22580 );
TEST_REAL_SIMILAR (yseries[3], 547.26291 );
TEST_REAL_SIMILAR (yseries[4], 646.33133 );
TEST_REAL_SIMILAR (yseries[5], 809.39466 );
//TEST_REAL_SIMILAR (yseries[6], 896.42668 );
// now add a modification to the sequence
bseries.clear();
yseries.clear();
a.setModification(1, "Phospho" ); // modify the Y
OpenMS::DIAHelpers::getBYSeries(a, bseries, yseries, &generator, 1);
TEST_EQUAL(bseries.size(), 5)
TEST_EQUAL(yseries.size(), 6)
//TEST_REAL_SIMILAR (bseries[0], 88.03990 );
TEST_REAL_SIMILAR (bseries[0], 251.10323 + 79.9657 );
TEST_REAL_SIMILAR (bseries[1], 350.17164 + 79.9657 );
TEST_REAL_SIMILAR (bseries[2], 421.20875 + 79.9657 );
TEST_REAL_SIMILAR (bseries[3], 607.28807 + 79.9657 );
TEST_REAL_SIMILAR (bseries[4], 722.31501 + 79.9657 );
//TEST_REAL_SIMILAR (bseries[5], 878.41612 );
TEST_REAL_SIMILAR (yseries[0], 175.11955 );
TEST_REAL_SIMILAR (yseries[1], 290.14649 );
TEST_REAL_SIMILAR (yseries[2], 476.22580 );
TEST_REAL_SIMILAR (yseries[3], 547.26291 );
TEST_REAL_SIMILAR (yseries[4], 646.33133 );
TEST_REAL_SIMILAR (yseries[5], 809.39466 + 79.9657);
//TEST_REAL_SIMILAR (yseries[6], 896.42668 );
}
END_SECTION
OpenSwath::LightTransition mock_tr1;
mock_tr1.product_mz = 500;
mock_tr1.fragment_charge = 1;
mock_tr1.transition_name = "group1";
OpenSwath::LightTransition mock_tr2;
mock_tr2.product_mz = 600;
mock_tr2.fragment_charge = 1;
mock_tr2.transition_name = "group2";
START_SECTION([EXTRA] forward void dia_isotope_scores(const std::vector<TransitionType> & transitions, std::vector<SpectrumType> spectrum, OpenSwath::IMRMFeature * mrmfeature, int putative_fragment_charge, const RangeMobility& im_range, double & isotope_corr, double & isotope_overlap))
{
SpectrumSequence sptr = prepareSpectrumSequence();
MockMRMFeature * imrmfeature_test = new MockMRMFeature();
getMRMFeatureTest(imrmfeature_test);
imrmfeature_test->m_intensity = 0.7f;
std::vector<OpenSwath::LightTransition> transitions;
OpenMS::RangeMobility empty_im_range;
// Try with transition at 600 m/z
transitions.push_back(mock_tr2);
DIAScoring diascoring;
diascoring.setParameters(p_dia);
double isotope_corr = 0, isotope_overlap = 0;
diascoring.dia_isotope_scores(transitions, sptr, imrmfeature_test, empty_im_range, isotope_corr, isotope_overlap);
// >> exp = [240, 74, 37, 15, 0]
// >> theo = [1, 0.325757771553019, 0.0678711748364005, 0.0105918703087134, 0.00134955223787482]
// >> from scipy.stats.stats import pearsonr
// >> pearsonr(exp, theo)
// (0.99536128611183172, 0.00037899006151919545)
//
TEST_REAL_SIMILAR(isotope_corr, 0.995335798317618)
TEST_REAL_SIMILAR(isotope_overlap, 0.0)
delete imrmfeature_test;
}
END_SECTION
START_SECTION([EXTRA] forward with IM void dia_isotope_scores(const std::vector<TransitionType> & transitions, std::vector<SpectrumType> spectrum, OpenSwath::IMRMFeature * mrmfeature, int putative_fragment_charge, const RangeMobility& im_range, double & isotope_corr, double & isotope_overlap))
{
SpectrumSequence sptr = prepareIMSpectrumSequence();
MockMRMFeature * imrmfeature_test = new MockMRMFeature();
getMRMFeatureTest(imrmfeature_test);
imrmfeature_test->m_intensity = 0.7f;
std::vector<OpenSwath::LightTransition> transitions;
// im_range 2-4
OpenMS::RangeMobility im_range(3);
im_range.minSpanIfSingular(2); // im_range from 2-4
// Try with transition at 600 m/z
transitions.push_back(mock_tr2);
DIAScoring diascoring;
diascoring.setParameters(p_dia);
double isotope_corr = 0, isotope_overlap = 0;
diascoring.dia_isotope_scores(transitions, sptr, imrmfeature_test, im_range, isotope_corr, isotope_overlap);
// Should be same as above because the IM is filtered out
TEST_REAL_SIMILAR(isotope_corr, 0.995335798317618)
TEST_REAL_SIMILAR(isotope_overlap, 0.0)
delete imrmfeature_test;
}
END_SECTION
START_SECTION([EXTRA] forward negative charge: void dia_isotope_scores(const std::vector<TransitionType> & transitions, std::vector<SpectrumType> spectrum, OpenSwath::IMRMFeature * mrmfeature, int putative_fragment_charge, const RangeMobility& im_range, double & isotope_corr, double & isotope_overlap))
{
RangeMobility empty_im_range;
SpectrumSequence sptr = prepareSpectrumSequence();
MockMRMFeature * imrmfeature_test = new MockMRMFeature();
getMRMFeatureTest(imrmfeature_test);
imrmfeature_test->m_intensity = 0.7f;
std::vector<OpenSwath::LightTransition> transitions;
auto mock_tr2_copy = mock_tr2;
mock_tr2_copy.fragment_charge = -1;
// Try with transition at 600 m/z
transitions.push_back(mock_tr2_copy);
DIAScoring diascoring;
diascoring.setParameters(p_dia);
double isotope_corr = 0, isotope_overlap = 0;
diascoring.dia_isotope_scores(transitions, sptr, imrmfeature_test, empty_im_range, isotope_corr, isotope_overlap);
// >> exp = [240, 74, 37, 15, 0]
// >> theo = [1, 0.325757771553019, 0.0678711748364005, 0.0105918703087134, 0.00134955223787482]
// >> from scipy.stats.stats import pearsonr
// >> pearsonr(exp, theo)
// (0.99536128611183172, 0.00037899006151919545)
//
TEST_REAL_SIMILAR(isotope_corr, 0.995335798317618)
TEST_REAL_SIMILAR(isotope_overlap, 0.0)
delete imrmfeature_test;
}
END_SECTION
START_SECTION([EXTRA] forward negative charge: void dia_isotope_scores(const std::vector<TransitionType> & transitions, std::vector<SpectrumType> spectrum, OpenSwath::IMRMFeature * mrmfeature, int putative_fragment_charge, const RangeMobility& im_range, double & isotope_corr, double & isotope_overlap))
{
OpenMS::RangeMobility empty_im_range;
SpectrumSequence sptr = prepareSpectrumSequence();
MockMRMFeature * imrmfeature_test = new MockMRMFeature();
getMRMFeatureTest(imrmfeature_test);
imrmfeature_test->m_intensity = 0.7f;
std::vector<OpenSwath::LightTransition> transitions;
auto mock_tr2_copy = mock_tr2;
mock_tr2_copy.fragment_charge = -2;
// Try with transition at 600 m/z
transitions.push_back(mock_tr2_copy);
DIAScoring diascoring;
diascoring.setParameters(p_dia);
double isotope_corr = 0, isotope_overlap = 0;
diascoring.dia_isotope_scores(transitions, sptr, imrmfeature_test, empty_im_range, isotope_corr, isotope_overlap);
// >> exp = [240, 74, 37, 15, 0]
// >> theo = [1, 0.325757771553019, 0.0678711748364005, 0.0105918703087134, 0.00134955223787482]
// >> from scipy.stats.stats import pearsonr
// >> pearsonr(exp, theo)
// (0.99536128611183172, 0.00037899006151919545)
//
TEST_REAL_SIMILAR(isotope_corr, 0.717092518007138)
TEST_REAL_SIMILAR(isotope_overlap, 0.0)
delete imrmfeature_test;
}
END_SECTION
START_SECTION([EXTRA] backward void dia_isotope_scores(const std::vector<TransitionType> & transitions, std::vector<SpectrumType> spectrum, OpenSwath::IMRMFeature * mrmfeature, int putative_fragment_charge, const RangeMobility& im_range, double & isotope_corr, double & isotope_overlap))
{
OpenMS::RangeMobility empty_im_range;
SpectrumSequence sptr = prepareSpectrumSequence();
MockMRMFeature * imrmfeature_test = new MockMRMFeature();
getMRMFeatureTest(imrmfeature_test);
imrmfeature_test->m_intensity = 0.3f;
std::vector<OpenSwath::LightTransition> transitions;
// Try with transition at 500 m/z
// This peak is not monoisotopic (e.g. at 499 there is another, more intense, peak)
transitions.push_back(mock_tr1);
DIAScoring diascoring;
diascoring.setParameters(p_dia);
double isotope_corr = 0, isotope_overlap = 0;
diascoring.dia_isotope_scores(transitions, sptr, imrmfeature_test, empty_im_range, isotope_corr, isotope_overlap);
// >> exp = [74, 39, 15, 0, 0]
// >> theo = [1, 0.266799519434277, 0.0486475002325161, 0.0066525896497495, 0.000747236543377621]
// >> from scipy.stats.stats import pearsonr
// >> pearsonr(exp, theo)
// (0.959570883150479, 0.0096989307464742554)
TEST_REAL_SIMILAR(isotope_corr, 0.959692139694113)
TEST_REAL_SIMILAR(isotope_overlap, 1.0)
delete imrmfeature_test;
}
END_SECTION
START_SECTION([EXTRA] backward with IM void dia_isotope_scores(const std::vector<TransitionType> & transitions, std::vector<SpectrumType> spectrum, OpenSwath::IMRMFeature * mrmfeature, int putative_fragment_charge, const RangeMobility& im_range, double & isotope_corr, double & isotope_overlap))
{
// IM range from 2-4
OpenMS::RangeMobility im_range(3);
im_range.minSpanIfSingular(2);
SpectrumSequence sptr = prepareIMSpectrumSequence();
MockMRMFeature * imrmfeature_test = new MockMRMFeature();
getMRMFeatureTest(imrmfeature_test);
imrmfeature_test->m_intensity = 0.3f;
std::vector<OpenSwath::LightTransition> transitions;
// Try with transition at 500 m/z
// This peak is not monoisotopic (e.g. at 499 there is another, more intense, peak)
transitions.push_back(mock_tr1);
DIAScoring diascoring;
diascoring.setParameters(p_dia);
double isotope_corr = 0, isotope_overlap = 0;
diascoring.dia_isotope_scores(transitions, sptr, imrmfeature_test, im_range, isotope_corr, isotope_overlap);
// >> exp = [74, 39, 15, 0, 0]
// >> theo = [1, 0.266799519434277, 0.0486475002325161, 0.0066525896497495, 0.000747236543377621]
// >> from scipy.stats.stats import pearsonr
// >> pearsonr(exp, theo)
// (0.959570883150479, 0.0096989307464742554)
TEST_REAL_SIMILAR(isotope_corr, 0.959692139694113)
TEST_REAL_SIMILAR(isotope_overlap, 1.0)
delete imrmfeature_test;
}
END_SECTION
START_SECTION ( void dia_isotope_scores(const std::vector< TransitionType > &transitions, std::vector<SpectrumType> spectrum, OpenSwath::IMRMFeature *mrmfeature, const RangeMobility& im_range, double &isotope_corr, double &isotope_overlap) )
{
OpenMS::RangeMobility empty_im_range;
SpectrumSequence sptr = prepareSpectrumSequence();
MockMRMFeature * imrmfeature_test = new MockMRMFeature();
getMRMFeatureTest(imrmfeature_test);
// create transitions, e.g. library intensity
std::vector<OpenSwath::LightTransition> transitions;
transitions.push_back(mock_tr1);
transitions.push_back(mock_tr2);
DIAScoring diascoring;
diascoring.setParameters(p_dia);
double isotope_corr = 0, isotope_overlap = 0;
diascoring.dia_isotope_scores(transitions, sptr, imrmfeature_test, empty_im_range, isotope_corr, isotope_overlap);
// see above for the two individual numbers (forward and backward)
TEST_REAL_SIMILAR(isotope_corr, 0.995335798317618 * 0.7 + 0.959692139694113 * 0.3)
TEST_REAL_SIMILAR(isotope_overlap, 0.0 * 0.7 + 1.0 * 0.3)
delete imrmfeature_test;
}
END_SECTION
START_SECTION ( [EXTRA] with IM void dia_isotope_scores(const std::vector< TransitionType > &transitions, std::vector<SpectrumType> spectrum, OpenSwath::IMRMFeature *mrmfeature, const RangeMobility& im_range, double &isotope_corr, double &isotope_overlap) )
{
OpenMS::RangeMobility im_range(3);
im_range.minSpanIfSingular(2);
SpectrumSequence sptr = prepareIMSpectrumSequence();
MockMRMFeature * imrmfeature_test = new MockMRMFeature();
getMRMFeatureTest(imrmfeature_test);
// create transitions, e.g. library intensity
std::vector<OpenSwath::LightTransition> transitions;
transitions.push_back(mock_tr1);
transitions.push_back(mock_tr2);
DIAScoring diascoring;
diascoring.setParameters(p_dia);
double isotope_corr = 0, isotope_overlap = 0;
diascoring.dia_isotope_scores(transitions, sptr, imrmfeature_test, im_range, isotope_corr, isotope_overlap);
// see above for the two individual numbers (forward and backward)
TEST_REAL_SIMILAR(isotope_corr, 0.995335798317618 * 0.7 + 0.959692139694113 * 0.3)
TEST_REAL_SIMILAR(isotope_overlap, 0.0 * 0.7 + 1.0 * 0.3)
delete imrmfeature_test;
}
END_SECTION
START_SECTION(void dia_ms1_isotope_scores(double precursor_mz, std::vector<SpectrumPtrType> spectrum, size_t charge_state, const RangeMobility& im_range,
double& isotope_corr, double& isotope_overlap))
{
SpectrumSequence sptr = prepareSpectrumSequence();
DIAScoring diascoring;
diascoring.setParameters(p_dia);
OpenMS::RangeMobility empty_im_range;
// Check for charge 1+ and m/z at 500
{
size_t precursor_charge_state = 1;
double precursor_mz = 500;
double isotope_corr = 0, isotope_overlap = 0;
diascoring
.dia_ms1_isotope_scores_averagine(precursor_mz, sptr, precursor_charge_state, empty_im_range, isotope_corr, isotope_overlap);
// see above for the two individual numbers (forward and backward)
TEST_REAL_SIMILAR(isotope_corr, 0.959692139694113)
TEST_REAL_SIMILAR(isotope_overlap, 240/74.0)
}
// Check if charge state is assumed 2+
{
size_t precursor_charge_state = 2;
double precursor_mz = 500;
double isotope_corr = 0, isotope_overlap = 0;
diascoring
.dia_ms1_isotope_scores_averagine(precursor_mz, sptr, precursor_charge_state, empty_im_range, isotope_corr, isotope_overlap);
// >>> theo = [0.57277789564886, 0.305415548811564, 0.0952064968352544, 0.0218253361702587, 0.00404081869309618]
// >>> exp = [74, 0, 39, 0, 15]
// >>> pearsonr(exp, theo)
// (0.68135233883093205, 0.20528953804781694)
TEST_REAL_SIMILAR(isotope_corr, 0.680028918385546)
TEST_REAL_SIMILAR(isotope_overlap, 240/74.0)
}
// Check and confirm that monoisotopic is at m/z 499
{
size_t precursor_charge_state = 1;
double precursor_mz = 499;
double isotope_corr = 0, isotope_overlap = 0;
diascoring
.dia_ms1_isotope_scores_averagine(precursor_mz, sptr, precursor_charge_state, empty_im_range, isotope_corr, isotope_overlap);
// >> exp = [240, 74, 39, 15, 0]
// >> theo = [0.755900817146293, 0.201673974754608, 0.0367726851778834, 0.00502869795238462, 0.000564836713740715]
// >> from scipy.stats.stats import pearsonr
// >> pearsonr(exp, theo)
// (0.99463189043051314, 0.00047175434098498532)
TEST_REAL_SIMILAR(isotope_corr, 0.995485552148335)
TEST_REAL_SIMILAR(isotope_overlap, 0.0) // monoisotopic
}
}
END_SECTION
START_SECTION([EXTRA] with IM void dia_ms1_isotope_scores(double precursor_mz, std::vector<SpectrumPtrType> spectrum, size_t charge_state, const RangeMobility& im_range,
double& isotope_corr, double& isotope_overlap))
{
SpectrumSequence sptr = prepareIMSpectrumSequence();
DIAScoring diascoring;
diascoring.setParameters(p_dia);
// IM range 2-4
OpenMS::RangeMobility im_range(3);
im_range.minSpanIfSingular(2);
// Check for charge 1+ and m/z at 500
{
size_t precursor_charge_state = 1;
double precursor_mz = 500;
double isotope_corr = 0, isotope_overlap = 0;
diascoring
.dia_ms1_isotope_scores_averagine(precursor_mz, sptr, precursor_charge_state, im_range, isotope_corr, isotope_overlap);
// see above for the two individual numbers (forward and backward)
TEST_REAL_SIMILAR(isotope_corr, 0.959692139694113)
TEST_REAL_SIMILAR(isotope_overlap, 240/74.0)
}
// Check if charge state is assumed 2+
{
size_t precursor_charge_state = 2;
double precursor_mz = 500;
double isotope_corr = 0, isotope_overlap = 0;
diascoring
.dia_ms1_isotope_scores_averagine(precursor_mz, sptr, precursor_charge_state, im_range, isotope_corr, isotope_overlap);
// >>> theo = [0.57277789564886, 0.305415548811564, 0.0952064968352544, 0.0218253361702587, 0.00404081869309618]
// >>> exp = [74, 0, 39, 0, 15]
// >>> pearsonr(exp, theo)
// (0.68135233883093205, 0.20528953804781694)
TEST_REAL_SIMILAR(isotope_corr, 0.680028918385546)
TEST_REAL_SIMILAR(isotope_overlap, 240/74.0)
}
// Check and confirm that monoisotopic is at m/z 499
{
size_t precursor_charge_state = 1;
double precursor_mz = 499;
double isotope_corr = 0, isotope_overlap = 0;
diascoring
.dia_ms1_isotope_scores_averagine(precursor_mz, sptr, precursor_charge_state, im_range, isotope_corr, isotope_overlap);
// >> exp = [240, 74, 39, 15, 0]
// >> theo = [0.755900817146293, 0.201673974754608, 0.0367726851778834, 0.00502869795238462, 0.000564836713740715]
// >> from scipy.stats.stats import pearsonr
// >> pearsonr(exp, theo)
// (0.99463189043051314, 0.00047175434098498532)
TEST_REAL_SIMILAR(isotope_corr, 0.995485552148335)
TEST_REAL_SIMILAR(isotope_overlap, 0.0) // monoisotopic
}
}
END_SECTION
START_SECTION (void dia_massdiff_score(const std::vector< TransitionType > &transitions, const SpectrumSequence& spectrum, const std::vector< double > &normalized_library_intensity, const RangeMobility& im_range, double &ppm_score, double &ppm_score_weighted) )
{
SpectrumSequence sptr = prepareShiftedSpectrum();
OpenMS::RangeMobility empty_im_range;
MockMRMFeature * imrmfeature_test = new MockMRMFeature();
getMRMFeatureTest(imrmfeature_test);
delete imrmfeature_test;
// create transitions, e.g. library intensity
std::vector<OpenSwath::LightTransition> transitions;
transitions.push_back(mock_tr1);
transitions.push_back(mock_tr2);
DIAScoring diascoring;
diascoring.setParameters(p_dia_large);
double ppm_score = 0, ppm_score_weighted = 0;
std::vector<double> normalized_library_intensity;
normalized_library_intensity.push_back(0.7);
normalized_library_intensity.push_back(0.3);
std::vector<double> ppm_errors;
diascoring.dia_massdiff_score(transitions, sptr, normalized_library_intensity, empty_im_range, ppm_score, ppm_score_weighted, ppm_errors);
TEST_REAL_SIMILAR(ppm_score, (15 + 10) / 2.0); // 15 ppm and 10 ppm
TEST_REAL_SIMILAR(ppm_score_weighted, 15 * 0.7 + 10* 0.3); // weighted
}
END_SECTION
START_SECTION ([EXTRA] with IM void dia_massdiff_score(const std::vector< TransitionType > &transitions, const SpectrumSequence& spectrum, const std::vector< double > &normalized_library_intensity, const RangeMobility& im_range, double &ppm_score, double &ppm_score_weighted) )
{
SpectrumSequence sptr = prepareShiftedSpectrumIM();
// IM range from 2-4
OpenMS::RangeMobility im_range(3);
im_range.minSpanIfSingular(2);
MockMRMFeature * imrmfeature_test = new MockMRMFeature();
getMRMFeatureTest(imrmfeature_test);
delete imrmfeature_test;
// create transitions, e.g. library intensity
std::vector<OpenSwath::LightTransition> transitions;
transitions.push_back(mock_tr1);
transitions.push_back(mock_tr2);
DIAScoring diascoring;
diascoring.setParameters(p_dia_large);
double ppm_score = 0, ppm_score_weighted = 0;
std::vector<double> normalized_library_intensity;
normalized_library_intensity.push_back(0.7);
normalized_library_intensity.push_back(0.3);
std::vector<double> ppm_errors;
diascoring.dia_massdiff_score(transitions, sptr, normalized_library_intensity, im_range, ppm_score, ppm_score_weighted, ppm_errors);
TEST_REAL_SIMILAR(ppm_score, (15 + 10) / 2.0); // 15 ppm and 10 ppm
TEST_REAL_SIMILAR(ppm_score_weighted, 15 * 0.7 + 10* 0.3); // weighted
}
END_SECTION
START_SECTION ( bool DIAScoring::dia_ms1_massdiff_score(double precursor_mz, transitions, const SpectrumSequence& spectrum, RangeMobility& im_range, double& ppm_score) )
{
SpectrumSequence sptr = prepareShiftedSpectrum();
DIAScoring diascoring;
OpenMS::RangeMobility empty_imRange;
diascoring.setParameters(p_dia_large);
double ppm_score = 0;
TEST_EQUAL(diascoring.dia_ms1_massdiff_score(500.0, sptr, empty_imRange, ppm_score), true);
TEST_REAL_SIMILAR(ppm_score, 15); // 15 ppm shifted
TEST_EQUAL(diascoring.dia_ms1_massdiff_score(600.0, sptr, empty_imRange, ppm_score), true);
TEST_REAL_SIMILAR(ppm_score, 10); // 10 ppm shifted
TEST_EQUAL(diascoring.dia_ms1_massdiff_score(100.0, sptr, empty_imRange, ppm_score), false);
TEST_REAL_SIMILAR(ppm_score, 0.5 * 1000000 / 100.0); // not present
}
END_SECTION
START_SECTION ( [EXTRA] with IM bool DIAScoring::dia_ms1_massdiff_score(double precursor_mz, transitions, const SpectrumSequence& spectrum, RangeMobility& im_range, double& ppm_score) )
{
SpectrumSequence sptr = prepareShiftedSpectrumIM();
DIAScoring diascoring;
// im_range 2-4
OpenMS::RangeMobility imRange(3);
imRange.minSpanIfSingular(2);
diascoring.setParameters(p_dia_large);
double ppm_score = 0;
TEST_EQUAL(diascoring.dia_ms1_massdiff_score(500.0, sptr, imRange, ppm_score), true);
TEST_REAL_SIMILAR(ppm_score, 15); // 15 ppm shifted
TEST_EQUAL(diascoring.dia_ms1_massdiff_score(600.0, sptr, imRange, ppm_score), true);
TEST_REAL_SIMILAR(ppm_score, 10); // 10 ppm shifted
TEST_EQUAL(diascoring.dia_ms1_massdiff_score(100.0, sptr, imRange, ppm_score), false);
TEST_REAL_SIMILAR(ppm_score, 0.5 * 1000000 / 100.0); // not present
}
END_SECTION
START_SECTION ( void dia_by_ion_score(std::vector<SpectrumType> spectrum, AASequence &sequence, int charge, RangeMobility& im_range, double &bseries_score, double &yseries_score) )
{
OpenSwath::SpectrumPtr sptr = (OpenSwath::SpectrumPtr)(new OpenSwath::Spectrum);
std::vector<OpenSwath::BinaryDataArrayPtr> binaryDataArrayPtrs;
OpenSwath::BinaryDataArrayPtr data1 = (OpenSwath::BinaryDataArrayPtr)(new OpenSwath::BinaryDataArray);
OpenSwath::BinaryDataArrayPtr data2 = (OpenSwath::BinaryDataArrayPtr)(new OpenSwath::BinaryDataArray);
OpenMS::RangeMobility empty_imRange;
std::vector<double> intensity(6, 100);
std::vector<double> mz {
// four of the naked b/y ions
// as well as one of the modified b and y ions ion each
350.17164, // b
421.20875, // b
421.20875 + 79.9657, // b + P
547.26291, // y
646.33133, // y
809.39466 + 79.9657 // y + P
};
data1->data = mz;
data2->data = intensity;
sptr->setMZArray(data1);
sptr->setIntensityArray( data2 );
DIAScoring diascoring;
diascoring.setParameters(p_dia);
String sequence = "SYVAWDR";
std::vector<double> bseries, yseries;
AASequence a = AASequence::fromString(sequence);
double bseries_score = 0, yseries_score = 0;
SpectrumSequence sptrArr;
sptrArr.push_back(sptr);
diascoring.dia_by_ion_score(sptrArr, a, 1, empty_imRange, bseries_score, yseries_score);
TEST_REAL_SIMILAR (bseries_score, 2);
TEST_REAL_SIMILAR (yseries_score, 2);
// now add a modification to the sequence
a.setModification(1, "Phospho" ); // modify the Y
bseries_score = 0, yseries_score = 0;
diascoring.dia_by_ion_score(sptrArr, a, 1, empty_imRange, bseries_score, yseries_score);
TEST_REAL_SIMILAR (bseries_score, 1);
TEST_REAL_SIMILAR (yseries_score, 3);
}
END_SECTION
START_SECTION( void score_with_isotopes(std::vector<SpectrumType> spectrum, const std::vector< TransitionType > &transitions, double &dotprod, double &manhattan))
{
OpenSwath::LightTransition mock_tr1;
mock_tr1.product_mz = 500.;
mock_tr1.fragment_charge = 1;
mock_tr1.transition_name = "group1";
mock_tr1.library_intensity = 5.;
OpenSwath::LightTransition mock_tr2;
mock_tr2.product_mz = 600.;
mock_tr2.fragment_charge = 1;
mock_tr2.transition_name = "group2";
mock_tr2.library_intensity = 5.;
SpectrumSequence sptr = prepareSpectrumSequence();
std::vector<OpenSwath::LightTransition> transitions;
transitions.push_back(mock_tr1);
transitions.push_back(mock_tr2);
DIAScoring diascoring;
diascoring.setParameters(p_dia);
OpenMS::RangeMobility empty_imRange;
double dotprod, manhattan;
diascoring.score_with_isotopes(sptr,transitions, empty_imRange, dotprod,manhattan);
TEST_REAL_SIMILAR (dotprod, 0.43738312458795);
TEST_REAL_SIMILAR (manhattan, 0.55743322213368);
}
END_SECTION
START_SECTION( [EXTRA] with IM void score_with_isotopes(std::vector<SpectrumType> spectrum, const std::vector< TransitionType > &transitions, double &dotprod, double &manhattan))
{
OpenSwath::LightTransition mock_tr1;
mock_tr1.product_mz = 500.;
mock_tr1.fragment_charge = 1;
mock_tr1.transition_name = "group1";
mock_tr1.library_intensity = 5.;
OpenSwath::LightTransition mock_tr2;
mock_tr2.product_mz = 600.;
mock_tr2.fragment_charge = 1;
mock_tr2.transition_name = "group2";
mock_tr2.library_intensity = 5.;
SpectrumSequence sptr = prepareIMSpectrumSequence();
std::vector<OpenSwath::LightTransition> transitions;
transitions.push_back(mock_tr1);
transitions.push_back(mock_tr2);
DIAScoring diascoring;
diascoring.setParameters(p_dia);
// im range from 2-4
OpenMS::RangeMobility imRange(3);
imRange.minSpanIfSingular(2);
double dotprod, manhattan;
diascoring.score_with_isotopes(sptr,transitions, imRange, dotprod,manhattan);
TEST_REAL_SIMILAR (dotprod, 0.43738312458795);
TEST_REAL_SIMILAR (manhattan, 0.55743322213368);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MRMAssay_test.cpp | .cpp | 38,602 | 1,010 | // 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 $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h>
#include <OpenMS/FORMAT/TraMLFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MRMAssay, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MRMAssay * ptr = nullptr;
MRMAssay* nullPointer = nullptr;
class MRMAssay_test :
public MRMAssay
{
public:
std::vector<std::string> getMatchingPeptidoforms_test(const double fragment_ion, std::vector<std::pair<double, std::string> >& ions, const double mz_threshold)
{
return getMatchingPeptidoforms_(fragment_ion, ions, mz_threshold);
}
int getSwath_test(const std::vector<std::pair<double, double> >& swathes, const double precursor_mz)
{
return getSwath_(swathes, precursor_mz);
}
bool isInSwath_test(const std::vector<std::pair<double, double> >& swathes, const double precursor_mz, const double product_mz)
{
return isInSwath_(swathes, precursor_mz, product_mz);
}
std::string getRandomSequence_test(int sequence_size, boost::variate_generator<boost::mt19937&, boost::uniform_int<> > pseudoRNG)
{
return getRandomSequence_(sequence_size, pseudoRNG);
}
std::vector<std::vector<size_t> > nchoosekcombinations_test(std::vector<size_t> n, size_t k)
{
return nchoosekcombinations_(n, k);
}
std::vector<OpenMS::AASequence> addModificationsSequences_test(std::vector<OpenMS::AASequence> sequences, std::vector<std::vector<size_t> > mods_combs, OpenMS::String modification)
{
return addModificationsSequences_(sequences, mods_combs, modification);
}
std::vector<OpenMS::AASequence> generateTheoreticalPeptidoforms_test(OpenMS::AASequence sequence)
{
return generateTheoreticalPeptidoforms_(sequence);
}
std::vector<OpenMS::AASequence> generateTheoreticalPeptidoformsDecoy_test(OpenMS::AASequence sequence, OpenMS::AASequence decoy_sequence)
{
return generateTheoreticalPeptidoformsDecoy_(sequence, decoy_sequence);
}
};
START_SECTION(MRMAssay())
{
ptr = new MRMAssay();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~MRMAssay())
{
delete ptr;
}
END_SECTION
START_SECTION(std::vector<std::string> MRMAssay::getMatchingPeptidoforms_(const double fragment_ion, std::vector<std::pair<double, std::string> >& ions, const double mz_threshold); )
{
MRMAssay_test mrma;
std::vector<std::pair<double, std::string> > ions;
ions.push_back(std::make_pair(100.00, "PEPTIDEK"));
ions.push_back(std::make_pair(100.01, "PEPTIDEK"));
ions.push_back(std::make_pair(100.10, "PEPT(UniMod:21)IDEK"));
ions.push_back(std::make_pair(100.12, "PEPTIDEK"));
ions.push_back(std::make_pair(100.11, "PEPTIDEK"));
// Sort by m/z (first element) - required for binary search in getMatchingPeptidoforms_
std::sort(ions.begin(), ions.end(),
[](const std::pair<double, std::string>& a, const std::pair<double, std::string>& b)
{ return a.first < b.first; });
std::vector<std::string> isoforms1 = mrma.getMatchingPeptidoforms_test(100.06, ions, 0.03);
std::vector<std::string> isoforms2 = mrma.getMatchingPeptidoforms_test(100.06, ions, 0.06);
TEST_EQUAL(isoforms1.size(), 0)
TEST_EQUAL(isoforms2.size(), 2)
TEST_EQUAL(isoforms2[0], "PEPT(UniMod:21)IDEK")
TEST_EQUAL(isoforms2[1], "PEPTIDEK")
}
END_SECTION
START_SECTION(int MRMAssay::getSwath_(const std::vector<std::pair<double, double> > swathes, const double precursor_mz))
{
MRMAssay_test mrma;
std::vector<std::pair<double, double> > swathes;
swathes.push_back(std::make_pair(400, 425));
swathes.push_back(std::make_pair(424, 450));
swathes.push_back(std::make_pair(449, 475));
swathes.push_back(std::make_pair(474, 500));
swathes.push_back(std::make_pair(499, 525));
swathes.push_back(std::make_pair(524, 550));
swathes.push_back(std::make_pair(549, 575));
swathes.push_back(std::make_pair(574, 600));
swathes.push_back(std::make_pair(599, 625));
swathes.push_back(std::make_pair(624, 650));
swathes.push_back(std::make_pair(649, 675));
swathes.push_back(std::make_pair(674, 700));
swathes.push_back(std::make_pair(699, 725));
swathes.push_back(std::make_pair(724, 750));
swathes.push_back(std::make_pair(749, 775));
swathes.push_back(std::make_pair(774, 800));
swathes.push_back(std::make_pair(799, 825));
swathes.push_back(std::make_pair(824, 850));
swathes.push_back(std::make_pair(849, 875));
swathes.push_back(std::make_pair(874, 900));
swathes.push_back(std::make_pair(899, 925));
swathes.push_back(std::make_pair(924, 950));
swathes.push_back(std::make_pair(949, 975));
swathes.push_back(std::make_pair(974, 1000));
swathes.push_back(std::make_pair(999, 1025));
swathes.push_back(std::make_pair(1024, 1050));
swathes.push_back(std::make_pair(1049, 1075));
swathes.push_back(std::make_pair(1074, 1100));
swathes.push_back(std::make_pair(1099, 1125));
swathes.push_back(std::make_pair(1124, 1150));
swathes.push_back(std::make_pair(1149, 1175));
swathes.push_back(std::make_pair(1174, 1200));
TEST_EQUAL(mrma.getSwath_test(swathes, 427.229959), 1)
TEST_EQUAL(mrma.getSwath_test(swathes, 449.0), 2)
TEST_EQUAL(mrma.getSwath_test(swathes, 449.229959), 2)
TEST_EQUAL(mrma.getSwath_test(swathes, 685.8547721), 11)
TEST_EQUAL(mrma.getSwath_test(swathes, 1685.8547721), -1)
TEST_EQUAL(mrma.getSwath_test(swathes, -41.1), -1)
}
END_SECTION
START_SECTION(bool MRMAssay::isInSwath_(const std::vector<std::pair<double, double> > swathes, const double precursor_mz, const double product_mz))
{
MRMAssay_test mrma;
std::vector<std::pair<double, double> > swathes;
swathes.push_back(std::make_pair(400, 425));
swathes.push_back(std::make_pair(424, 450));
swathes.push_back(std::make_pair(449, 475));
swathes.push_back(std::make_pair(474, 500));
swathes.push_back(std::make_pair(499, 525));
swathes.push_back(std::make_pair(524, 550));
swathes.push_back(std::make_pair(549, 575));
swathes.push_back(std::make_pair(574, 600));
swathes.push_back(std::make_pair(599, 625));
swathes.push_back(std::make_pair(624, 650));
swathes.push_back(std::make_pair(649, 675));
swathes.push_back(std::make_pair(674, 700));
swathes.push_back(std::make_pair(699, 725));
swathes.push_back(std::make_pair(724, 750));
swathes.push_back(std::make_pair(749, 775));
swathes.push_back(std::make_pair(774, 800));
swathes.push_back(std::make_pair(799, 825));
swathes.push_back(std::make_pair(824, 850));
swathes.push_back(std::make_pair(849, 875));
swathes.push_back(std::make_pair(874, 900));
swathes.push_back(std::make_pair(899, 925));
swathes.push_back(std::make_pair(924, 950));
swathes.push_back(std::make_pair(949, 975));
swathes.push_back(std::make_pair(974, 1000));
swathes.push_back(std::make_pair(999, 1025));
swathes.push_back(std::make_pair(1024, 1050));
swathes.push_back(std::make_pair(1049, 1075));
swathes.push_back(std::make_pair(1074, 1100));
swathes.push_back(std::make_pair(1099, 1125));
swathes.push_back(std::make_pair(1124, 1150));
swathes.push_back(std::make_pair(1149, 1175));
swathes.push_back(std::make_pair(1174, 1200));
TEST_EQUAL(mrma.isInSwath_test(swathes, 685.8547721, 427.229959), false)
TEST_EQUAL(mrma.isInSwath_test(swathes, 685.8547721, 689), true)
}
END_SECTION
START_SECTION(std::string MRMAssay::getRandomSequence_(int sequence_size, boost::variate_generator<boost::mt19937&, boost::uniform
_int<> > pseudoRNG))
{
MRMAssay_test mrma;
boost::mt19937 generator(42);
boost::uniform_int<> uni_dist;
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > pseudoRNG(generator, uni_dist);
std::string sequence1 = mrma.getRandomSequence_test(10, pseudoRNG);
TEST_EQUAL(sequence1, "CHLNHHQQNE");
}
END_SECTION
START_SECTION(std::vector<std::vector<size_t> > MRMAssay::nchoosekcombinations_(std::vector<size_t> n, size_t k))
{
MRMAssay_test mrma;
std::vector<size_t> n;
size_t k = 5;
for (size_t i = 1; i <= 16; i++)
{
n.push_back(i);
}
TEST_EQUAL(mrma.nchoosekcombinations_test(n, k).size(), 4368)
TEST_EQUAL(mrma.nchoosekcombinations_test(n, k)[0].size(), 5)
}
END_SECTION
START_SECTION(std::vector<std::vector<size_t> > MRMAssay::nchoosekcombinations_(std::vector<size_t> n, size_t k))
{
MRMAssay_test mrma;
std::vector<size_t> n;
size_t k = 3;
for (size_t i = 1; i <= 5; i++)
{
n.push_back(i);
}
std::vector<std::vector<size_t> > res = mrma.nchoosekcombinations_test(n, k);
TEST_EQUAL(res.size(), 10)
TEST_EQUAL(res[0].size(), 3)
TEST_EQUAL(res[0][0], 1)
TEST_EQUAL(res[0][1], 2)
TEST_EQUAL(res[0][2], 3)
TEST_EQUAL(res[1][0], 1)
TEST_EQUAL(res[1][1], 2)
TEST_EQUAL(res[1][2], 4)
TEST_EQUAL(res[2][0], 1)
TEST_EQUAL(res[2][1], 2)
TEST_EQUAL(res[2][2], 5)
TEST_EQUAL(res[3][0], 1)
TEST_EQUAL(res[3][1], 3)
TEST_EQUAL(res[3][2], 4)
TEST_EQUAL(res[4][0], 1)
TEST_EQUAL(res[4][1], 3)
TEST_EQUAL(res[4][2], 5)
TEST_EQUAL(res[5][0], 1)
TEST_EQUAL(res[5][1], 4)
TEST_EQUAL(res[5][2], 5)
TEST_EQUAL(res[6][0], 2)
TEST_EQUAL(res[6][1], 3)
TEST_EQUAL(res[6][2], 4)
TEST_EQUAL(res[7][0], 2)
TEST_EQUAL(res[7][1], 3)
TEST_EQUAL(res[7][2], 5)
TEST_EQUAL(res[8][0], 2)
TEST_EQUAL(res[8][1], 4)
TEST_EQUAL(res[8][2], 5)
TEST_EQUAL(res[9][0], 3)
TEST_EQUAL(res[9][1], 4)
TEST_EQUAL(res[9][2], 5)
}
END_SECTION
START_SECTION(std::vector<OpenMS::AASequence> MRMAssay::addModificationsSequences_(std::vector<OpenMS::AASequence> sequences, std::vector<std::vector<size_t> > mods_combs, OpenMS::String modification))
{
MRMAssay_test mrma;
AASequence sequence = AASequence::fromString("PEPTDIEK");
std::vector<OpenMS::AASequence> sequences;
sequences.push_back(sequence);
std::vector<size_t> no;
no.push_back(1);
no.push_back(3);
no.push_back(5);
no.push_back(8);
no.push_back(9);
std::vector<std::vector<size_t> > mods_combs_o = mrma.nchoosekcombinations_test(no, 1);
sequences = mrma.addModificationsSequences_test(sequences, mods_combs_o, String("Oxidation"));
std::vector<size_t> np;
np.push_back(4);
np.push_back(5);
np.push_back(8);
std::vector<std::vector<size_t> > mods_combs_p = mrma.nchoosekcombinations_test(np, 1);
sequences = mrma.addModificationsSequences_test(sequences, mods_combs_p, String("Phospho"));
TEST_EQUAL(sequences.size(), 10)
TEST_EQUAL(sequences[0].toString(), String("P(Oxidation)EPT(Phospho)DIEK"));
TEST_EQUAL(sequences[1].toString(), String("P(Oxidation)EPTD(Phospho)IEK"));
TEST_EQUAL(sequences[2].toString(), String("P(Oxidation)EPTDIEK(Phospho)"));
TEST_EQUAL(sequences[3].toString(), String("PEP(Oxidation)T(Phospho)DIEK"));
TEST_EQUAL(sequences[4].toString(), String("PEP(Oxidation)TD(Phospho)IEK"));
TEST_EQUAL(sequences[5].toString(), String("PEP(Oxidation)TDIEK(Phospho)"));
TEST_EQUAL(sequences[6].toString(), String("PEPT(Phospho)D(Oxidation)IEK"));
TEST_EQUAL(sequences[7].toString(), String("PEPTD(Oxidation)IEK(Phospho)"));
TEST_EQUAL(sequences[8].toString(), String("PEPT(Phospho)DIEK(Oxidation)"));
TEST_EQUAL(sequences[9].toString(), String("PEPTD(Phospho)IEK(Oxidation)"));
std::vector<std::string> sequence_list {};
for (std::vector<OpenMS::AASequence>::const_iterator sq_it = sequences.begin(); sq_it != sequences.end(); ++sq_it)
{
OpenMS::AASequence temp_sequence = *sq_it;
sequence_list.push_back(temp_sequence.toString());
}
bool check_terminal_mod_present = (std::find(sequence_list.begin(), sequence_list.end(), "PEPT(Phospho)DIEK.(Oxidation)") != sequence_list.end());
TEST_EQUAL(check_terminal_mod_present, false)
}
END_SECTION
START_SECTION(std::vector<OpenMS::AASequence> MRMAssay::generateTheoreticalPeptidoforms_(OpenMS::AASequence sequence))
{
MRMAssay_test mrma;
std::vector<AASequence> sequences = mrma.generateTheoreticalPeptidoforms_test(AASequence::fromString(".(Acetyl)PEPT(Phospho)DIEK"));
TEST_EQUAL(sequences.size(), 13)
TEST_EQUAL(sequences[0], AASequence::fromString(".(Acetyl)PE(Phospho)PTDIEK"));
TEST_EQUAL(sequences[1], AASequence::fromString(".(Acetyl)PEPT(Phospho)DIEK"));
TEST_EQUAL(sequences[2], AASequence::fromString(".(Acetyl)PEPTD(Phospho)IEK"));
TEST_EQUAL(sequences[3], AASequence::fromString(".(Acetyl)PEPTDIE(Phospho)K"));
TEST_EQUAL(sequences[4], AASequence::fromString(".(Acetyl)PEPTDIEK(Phospho)"));
TEST_EQUAL(sequences[5], AASequence::fromString("PE(Phospho)PT(Acetyl)DIEK"));
TEST_EQUAL(sequences[6], AASequence::fromString("PEPT(Acetyl)D(Phospho)IEK"));
TEST_EQUAL(sequences[7], AASequence::fromString("PEPT(Acetyl)DIE(Phospho)K"));
TEST_EQUAL(sequences[8], AASequence::fromString("PEPT(Acetyl)DIEK(Phospho)"));
TEST_EQUAL(sequences[9], AASequence::fromString("PE(Phospho)PTDIEK(Acetyl)"));
TEST_EQUAL(sequences[10], AASequence::fromString("PEPT(Phospho)DIEK(Acetyl)"));
TEST_EQUAL(sequences[11], AASequence::fromString("PEPTD(Phospho)IEK(Acetyl)"));
TEST_EQUAL(sequences[12], AASequence::fromString("PEPTDIE(Phospho)K(Acetyl)"));
}
END_SECTION
START_SECTION(std::vector<OpenMS::AASequence> MRMAssay::generateTheoreticalPeptidoformsDecoy_(OpenMS::AASequence sequence, OpenMS::AASequence decoy_sequence))
{
MRMAssay_test mrma;
std::vector<AASequence> sequences = mrma.generateTheoreticalPeptidoformsDecoy_test(AASequence::fromString(".(Acetyl)PEPT(Phospho)DIEK"), AASequence::fromString("PESTDIEK"));
TEST_EQUAL(sequences.size(), 13)
TEST_EQUAL(sequences[0], AASequence::fromString(".(Acetyl)PE(Phospho)STDIEK"));
TEST_EQUAL(sequences[1], AASequence::fromString(".(Acetyl)PEST(Phospho)DIEK"));
TEST_EQUAL(sequences[2], AASequence::fromString(".(Acetyl)PESTD(Phospho)IEK"));
TEST_EQUAL(sequences[3], AASequence::fromString(".(Acetyl)PESTDIE(Phospho)K"));
TEST_EQUAL(sequences[4], AASequence::fromString(".(Acetyl)PESTDIEK(Phospho)"));
TEST_EQUAL(sequences[5], AASequence::fromString("PE(Phospho)ST(Acetyl)DIEK"));
TEST_EQUAL(sequences[6], AASequence::fromString("PEST(Acetyl)D(Phospho)IEK"));
TEST_EQUAL(sequences[7], AASequence::fromString("PEST(Acetyl)DIE(Phospho)K"));
TEST_EQUAL(sequences[8], AASequence::fromString("PEST(Acetyl)DIEK(Phospho)"));
TEST_EQUAL(sequences[9], AASequence::fromString("PE(Phospho)STDIEK(Acetyl)"));
TEST_EQUAL(sequences[10], AASequence::fromString("PEST(Phospho)DIEK(Acetyl)"));
TEST_EQUAL(sequences[11], AASequence::fromString("PESTD(Phospho)IEK(Acetyl)"));
TEST_EQUAL(sequences[12], AASequence::fromString("PESTDIE(Phospho)K(Acetyl)"));
}
END_SECTION
START_SECTION(void reannotateTransitions(OpenMS::TargetedExperiment& exp, double precursor_mz_threshold, double product_mz_threshold, std::vector<String> fragment_types, std::vector<size_t> fragment_charges, bool enable_reannotation, bool enable_specific_losses, bool enable_specific_losses))
{
TraMLFile traml;
TargetedExperiment targeted_exp;
String in = "MRMAssay_reannotateTransitions_input.TraML";
traml.load(OPENMS_GET_TEST_DATA_PATH(in), targeted_exp);
MRMAssay mrma;
double precursor_mz_threshold1 = 0.05;
double product_mz_threshold1 = 0.05;
std::vector<String> fragment_types1;
fragment_types1.push_back(String("y"));
std::vector<size_t> fragment_charges1;
fragment_charges1.push_back(2);
bool enable_losses1 = false;
String out1 = "MRMAssay_reannotateTransitions_output_1.TraML";
TargetedExperiment targeted_exp1 = targeted_exp;
mrma.reannotateTransitions(targeted_exp1, precursor_mz_threshold1,
product_mz_threshold1, fragment_types1, fragment_charges1,
enable_losses1, enable_losses1);
String test1;
NEW_TMP_FILE(test1);
traml.store(test1, targeted_exp1);
TEST_FILE_SIMILAR(test1.c_str(), OPENMS_GET_TEST_DATA_PATH(out1))
double precursor_mz_threshold2 = 0.05;
double product_mz_threshold2 = 0.05;
std::vector<String> fragment_types2;
fragment_types2.push_back(String("y"));
fragment_types2.push_back(String("b"));
std::vector<size_t> fragment_charges2;
fragment_charges2.push_back(2);
fragment_charges2.push_back(3);
bool enable_losses2 = true;
String out2 = "MRMAssay_reannotateTransitions_output_2.TraML";
TargetedExperiment targeted_exp2 = targeted_exp;
mrma.reannotateTransitions(targeted_exp2, precursor_mz_threshold2, product_mz_threshold2, fragment_types2, fragment_charges2, enable_losses2, enable_losses2);
String test2;
NEW_TMP_FILE(test2);
traml.store(test2, targeted_exp2);
TEST_FILE_SIMILAR(test2.c_str(), OPENMS_GET_TEST_DATA_PATH(out2))
}
END_SECTION
START_SECTION(void restrictTransitions(OpenMS::TargetedExperiment& exp, double lower_mz_limit, double upper_mz_limit, std::vector<std::pair<double, double> > swathes))
{
std::vector<std::pair<double, double> > swathes;
swathes.push_back(std::make_pair(400, 425));
swathes.push_back(std::make_pair(424, 450));
swathes.push_back(std::make_pair(449, 475));
swathes.push_back(std::make_pair(474, 500));
swathes.push_back(std::make_pair(499, 525));
swathes.push_back(std::make_pair(524, 550));
swathes.push_back(std::make_pair(549, 575));
swathes.push_back(std::make_pair(574, 600));
swathes.push_back(std::make_pair(599, 625));
swathes.push_back(std::make_pair(624, 650));
swathes.push_back(std::make_pair(649, 675));
swathes.push_back(std::make_pair(674, 700));
swathes.push_back(std::make_pair(699, 725));
swathes.push_back(std::make_pair(724, 750));
swathes.push_back(std::make_pair(749, 775));
swathes.push_back(std::make_pair(774, 800));
swathes.push_back(std::make_pair(799, 825));
swathes.push_back(std::make_pair(824, 850));
swathes.push_back(std::make_pair(849, 875));
swathes.push_back(std::make_pair(874, 900));
swathes.push_back(std::make_pair(899, 925));
swathes.push_back(std::make_pair(924, 950));
swathes.push_back(std::make_pair(949, 975));
swathes.push_back(std::make_pair(974, 1000));
swathes.push_back(std::make_pair(999, 1025));
swathes.push_back(std::make_pair(1024, 1050));
swathes.push_back(std::make_pair(1049, 1075));
swathes.push_back(std::make_pair(1074, 1100));
swathes.push_back(std::make_pair(1099, 1125));
swathes.push_back(std::make_pair(1124, 1150));
swathes.push_back(std::make_pair(1149, 1175));
swathes.push_back(std::make_pair(1174, 1200));
TraMLFile traml;
TargetedExperiment targeted_exp;
String in = "MRMAssay_restrictTransitions_input.TraML";
traml.load(OPENMS_GET_TEST_DATA_PATH(in), targeted_exp);
MRMAssay mrma;
double lower_mz_limit = 400;
double upper_mz_limit = 2000;
String out1 = "MRMAssay_restrictTransitions_output.TraML";
TargetedExperiment targeted_exp1 = targeted_exp;
mrma.restrictTransitions(targeted_exp1, lower_mz_limit, upper_mz_limit, swathes);
String test1;
NEW_TMP_FILE(test1);
traml.store(test1, targeted_exp1);
TEST_FILE_SIMILAR(test1.c_str(), OPENMS_GET_TEST_DATA_PATH(out1))
}
END_SECTION
START_SECTION(void detectingTransitions(OpenMS::TargetedExperiment& exp, int min_transitions, int max_transitions))
{
TraMLFile traml;
TargetedExperiment targeted_exp;
String in = "MRMAssay_detectingTransitions_input.TraML";
traml.load(OPENMS_GET_TEST_DATA_PATH(in), targeted_exp);
MRMAssay mrma;
int min_transitions = 4;
int max_transitions = 6;
String out1 = "MRMAssay_detectingTransitions_output.TraML";
TargetedExperiment targeted_exp1 = targeted_exp;
mrma.detectingTransitions(targeted_exp1, min_transitions, max_transitions);
String test1;
NEW_TMP_FILE(test1);
traml.store(test1, targeted_exp1);
TEST_FILE_SIMILAR(test1.c_str(), OPENMS_GET_TEST_DATA_PATH(out1))
}
END_SECTION
START_SECTION(void filterMinMaxTransitionsCompound(OpenMS::TargetedExperiment& exp, int min_transitions, int max_transitions))
{
TraMLFile traml;
TargetedExperiment targeted_exp;
String in = "MRMAssay_detectingTransistionCompound_input.TraML";
traml.load(OPENMS_GET_TEST_DATA_PATH(in), targeted_exp);
MRMAssay mrma;
int min_transitions = 3;
int max_transitions = 6;
String out1 = "MRMAssay_detectingTransitionCompound_output.TraML";
TargetedExperiment targeted_exp1 = targeted_exp;
mrma.filterMinMaxTransitionsCompound(targeted_exp1, min_transitions, max_transitions);
String test1;
NEW_TMP_FILE(test1);
traml.store(test1, targeted_exp1);
TEST_FILE_SIMILAR(test1.c_str(), OPENMS_GET_TEST_DATA_PATH(out1))
}
END_SECTION
START_SECTION(void uisTransitions(OpenMS::TargetedExperiment& exp, std::vector<String> fragment_types, std::vector<size_t> fragment_charges, bool enable_specific_losses, bool enable_unspecific_losses, double mz_threshold, std::vector<std::pair<double, double> > swathes, int round_decPow, size_t max_num_alternative_localizations, double shuffle_identity_threshold, int shuffle_max_attempts, int shuffle_seed))
{
std::vector<std::pair<double, double> > swathes;
swathes.push_back(std::make_pair(400, 425));
swathes.push_back(std::make_pair(424, 450));
swathes.push_back(std::make_pair(449, 475));
swathes.push_back(std::make_pair(474, 500));
swathes.push_back(std::make_pair(499, 525));
swathes.push_back(std::make_pair(524, 550));
swathes.push_back(std::make_pair(549, 575));
swathes.push_back(std::make_pair(574, 600));
swathes.push_back(std::make_pair(599, 625));
swathes.push_back(std::make_pair(624, 650));
swathes.push_back(std::make_pair(649, 675));
swathes.push_back(std::make_pair(674, 700));
swathes.push_back(std::make_pair(699, 725));
swathes.push_back(std::make_pair(724, 750));
swathes.push_back(std::make_pair(749, 775));
swathes.push_back(std::make_pair(774, 800));
swathes.push_back(std::make_pair(799, 825));
swathes.push_back(std::make_pair(824, 850));
swathes.push_back(std::make_pair(849, 875));
swathes.push_back(std::make_pair(874, 900));
swathes.push_back(std::make_pair(899, 925));
swathes.push_back(std::make_pair(924, 950));
swathes.push_back(std::make_pair(949, 975));
swathes.push_back(std::make_pair(974, 1000));
swathes.push_back(std::make_pair(999, 1025));
swathes.push_back(std::make_pair(1024, 1050));
swathes.push_back(std::make_pair(1049, 1075));
swathes.push_back(std::make_pair(1074, 1100));
swathes.push_back(std::make_pair(1099, 1125));
swathes.push_back(std::make_pair(1124, 1150));
swathes.push_back(std::make_pair(1149, 1175));
swathes.push_back(std::make_pair(1174, 1200));
TraMLFile traml;
TargetedExperiment targeted_exp;
String in = "MRMAssay_uisTransitions_input_1.TraML";
traml.load(OPENMS_GET_TEST_DATA_PATH(in), targeted_exp);
MRMAssay mrma;
std::vector<String> fragment_types1;
fragment_types1.push_back(String("y"));
std::vector<size_t> fragment_charges1;
fragment_charges1.push_back(2);
bool enable_specific_losses1 = true;
bool enable_unspecific_losses1 = false;
bool enable_ms2_precursors1 = false;
double product_mz_threshold1 = 0.05;
String out1 = "MRMAssay_uisTransitions_output_1.TraML";
TargetedExperiment targeted_exp1 = targeted_exp;
mrma.uisTransitions(targeted_exp1, fragment_types1, fragment_charges1, enable_specific_losses1, enable_unspecific_losses1, enable_ms2_precursors1, product_mz_threshold1, swathes, -4, 20, 42);
String test1;
NEW_TMP_FILE(test1);
traml.store(test1, targeted_exp1);
#if !defined(__APPLE__) // currently fails on macOS likely due to different boost version and different random number generator
TEST_FILE_SIMILAR(test1.c_str(), OPENMS_GET_TEST_DATA_PATH(out1))
#endif
std::vector<String> fragment_types2;
fragment_types2.push_back(String("y"));
std::vector<size_t> fragment_charges2;
fragment_charges2.push_back(2);
bool enable_specific_losses2 = true;
bool enable_unspecific_losses2 = true;
bool enable_ms2_precursors2 = false;
double product_mz_threshold2 = 0.05;
String out2 = "MRMAssay_uisTransitions_output_2.TraML";
TargetedExperiment targeted_exp2 = targeted_exp;
mrma.uisTransitions(targeted_exp2, fragment_types2, fragment_charges2, enable_specific_losses2, enable_unspecific_losses2, enable_ms2_precursors2, product_mz_threshold2, swathes, -4, 20, 42);
String test2;
NEW_TMP_FILE(test2);
traml.store(test2, targeted_exp2);
#if !defined(__APPLE__) // currently fails on macOS likely due to different boost version and different random number generator
TEST_FILE_SIMILAR(test2.c_str(), OPENMS_GET_TEST_DATA_PATH(out2))
#endif
}
END_SECTION
START_SECTION(void uisTransitions(OpenMS::TargetedExperiment& exp, std::vector<String> fragment_types, std::vector<size_t> fragment_charges, bool enable_specific_losses, bool enable_unspecific_losses, double mz_threshold, std::vector<std::pair<double, double> > swathes, int round_decPow, size_t max_num_alternative_localizations))
{
std::vector<std::pair<double, double> > swathes;
swathes.push_back(std::make_pair(400, 425));
swathes.push_back(std::make_pair(424, 450));
swathes.push_back(std::make_pair(449, 475));
swathes.push_back(std::make_pair(474, 500));
swathes.push_back(std::make_pair(499, 525));
swathes.push_back(std::make_pair(524, 550));
swathes.push_back(std::make_pair(549, 575));
swathes.push_back(std::make_pair(574, 600));
swathes.push_back(std::make_pair(599, 625));
swathes.push_back(std::make_pair(624, 650));
swathes.push_back(std::make_pair(649, 675));
swathes.push_back(std::make_pair(674, 700));
swathes.push_back(std::make_pair(699, 725));
swathes.push_back(std::make_pair(724, 750));
swathes.push_back(std::make_pair(749, 775));
swathes.push_back(std::make_pair(774, 800));
swathes.push_back(std::make_pair(799, 825));
swathes.push_back(std::make_pair(824, 850));
swathes.push_back(std::make_pair(849, 875));
swathes.push_back(std::make_pair(874, 900));
swathes.push_back(std::make_pair(899, 925));
swathes.push_back(std::make_pair(924, 950));
swathes.push_back(std::make_pair(949, 975));
swathes.push_back(std::make_pair(974, 1000));
swathes.push_back(std::make_pair(999, 1025));
swathes.push_back(std::make_pair(1024, 1050));
swathes.push_back(std::make_pair(1049, 1075));
swathes.push_back(std::make_pair(1074, 1100));
swathes.push_back(std::make_pair(1099, 1125));
swathes.push_back(std::make_pair(1124, 1150));
swathes.push_back(std::make_pair(1149, 1175));
swathes.push_back(std::make_pair(1174, 1200));
TraMLFile traml;
TargetedExperiment targeted_exp;
String in = "MRMAssay_uisTransitions_input_3.TraML";
traml.load(OPENMS_GET_TEST_DATA_PATH(in), targeted_exp);
MRMAssay mrma;
std::vector<String> fragment_types1;
fragment_types1.push_back(String("b"));
std::vector<size_t> fragment_charges1;
fragment_charges1.push_back(3);
bool enable_losses1 = true;
bool enable_ms2_precursors1 = false;
double product_mz_threshold1 = 0.05;
String out1 = "MRMAssay_uisTransitions_output_3.TraML";
TargetedExperiment targeted_exp1 = targeted_exp;
mrma.uisTransitions(targeted_exp1, fragment_types1, fragment_charges1, enable_losses1, enable_losses1, enable_ms2_precursors1, product_mz_threshold1, swathes, -4, 20, 42);
String test1;
NEW_TMP_FILE(test1);
traml.store(test1, targeted_exp1);
#if !defined(__APPLE__) // currently fails on macOS likely due to different boost version and different random number generator
TEST_FILE_SIMILAR(test1.c_str(), OPENMS_GET_TEST_DATA_PATH(out1))
#endif
std::vector<String> fragment_types2;
fragment_types2.push_back(String("y"));
fragment_types2.push_back(String("b"));
std::vector<size_t> fragment_charges2;
fragment_charges2.push_back(2);
fragment_charges2.push_back(3);
bool enable_losses2 = true;
bool enable_ms2_precursors2 = false;
double product_mz_threshold2 = 0.05;
String out2 = "MRMAssay_uisTransitions_output_4.TraML";
TargetedExperiment targeted_exp2 = targeted_exp;
mrma.uisTransitions(targeted_exp2, fragment_types2, fragment_charges2, enable_losses2, enable_losses2, enable_ms2_precursors2, product_mz_threshold2, swathes, -4, 20, 42);
String test2;
NEW_TMP_FILE(test2);
traml.store(test2, targeted_exp2);
#if !defined(__APPLE__) // currently fails on macOS likely due to different boost version and different random number generator
TEST_FILE_SIMILAR(test2.c_str(), OPENMS_GET_TEST_DATA_PATH(out2))
#endif
std::vector<String> fragment_types3;
fragment_types3.push_back(String("y"));
fragment_types3.push_back(String("b"));
std::vector<size_t> fragment_charges3;
fragment_charges3.push_back(2);
fragment_charges3.push_back(3);
bool enable_losses3 = true;
bool enable_ms2_precursors3 = true;
double product_mz_threshold3 = 0.05;
String out3 = "MRMAssay_uisTransitions_output_5.TraML";
TargetedExperiment targeted_exp3 = targeted_exp;
mrma.uisTransitions(targeted_exp3, fragment_types3, fragment_charges3, enable_losses3, enable_losses3, enable_ms2_precursors3, product_mz_threshold3, swathes, -4, 20, 42);
String test3;
NEW_TMP_FILE(test3);
traml.store(test3, targeted_exp3);
#if !defined(__APPLE__) // currently fails on macOS likely due to different boost version and different random number generator
TEST_FILE_SIMILAR(test3.c_str(), OPENMS_GET_TEST_DATA_PATH(out3))
#endif
}
END_SECTION
START_SECTION(void uisTransitionsLight(OpenSwath::LightTargetedExperiment& exp, const std::vector<String>& fragment_types, const std::vector<size_t>& fragment_charges, bool enable_specific_losses, bool enable_unspecific_losses, bool enable_ms2_precursors, double mz_threshold, const std::vector<std::pair<double, double> >& swathes, int round_decPow, size_t max_num_alternative_localizations, int shuffle_seed, bool disable_decoy_transitions))
{
// Setup SWATH windows (same as heavy version tests)
std::vector<std::pair<double, double> > swathes;
swathes.push_back(std::make_pair(400, 425));
swathes.push_back(std::make_pair(424, 450));
swathes.push_back(std::make_pair(449, 475));
swathes.push_back(std::make_pair(474, 500));
swathes.push_back(std::make_pair(499, 525));
swathes.push_back(std::make_pair(524, 550));
swathes.push_back(std::make_pair(549, 575));
swathes.push_back(std::make_pair(574, 600));
swathes.push_back(std::make_pair(599, 625));
swathes.push_back(std::make_pair(624, 650));
swathes.push_back(std::make_pair(649, 675));
swathes.push_back(std::make_pair(674, 700));
swathes.push_back(std::make_pair(699, 725));
swathes.push_back(std::make_pair(724, 750));
swathes.push_back(std::make_pair(749, 775));
swathes.push_back(std::make_pair(774, 800));
swathes.push_back(std::make_pair(799, 825));
swathes.push_back(std::make_pair(824, 850));
swathes.push_back(std::make_pair(849, 875));
swathes.push_back(std::make_pair(874, 900));
swathes.push_back(std::make_pair(899, 925));
swathes.push_back(std::make_pair(924, 950));
swathes.push_back(std::make_pair(949, 975));
swathes.push_back(std::make_pair(974, 1000));
swathes.push_back(std::make_pair(999, 1025));
swathes.push_back(std::make_pair(1024, 1050));
swathes.push_back(std::make_pair(1049, 1075));
swathes.push_back(std::make_pair(1074, 1100));
swathes.push_back(std::make_pair(1099, 1125));
swathes.push_back(std::make_pair(1124, 1150));
swathes.push_back(std::make_pair(1149, 1175));
swathes.push_back(std::make_pair(1174, 1200));
// Load input TraML
TraMLFile traml;
TargetedExperiment targeted_exp;
String in = "MRMAssay_uisTransitions_input_1.TraML";
traml.load(OPENMS_GET_TEST_DATA_PATH(in), targeted_exp);
// Convert to LightTargetedExperiment
OpenSwath::LightTargetedExperiment light_exp;
OpenSwathDataAccessHelper::convertTargetedExp(targeted_exp, light_exp);
// Count initial transitions
size_t initial_transitions = light_exp.transitions.size();
// Count initial identifying transitions
size_t initial_identifying = 0;
for (const auto& tr : light_exp.transitions)
{
if (tr.isIdentifyingTransition()) initial_identifying++;
}
MRMAssay mrma;
std::vector<String> fragment_types;
fragment_types.push_back(String("y"));
std::vector<size_t> fragment_charges;
fragment_charges.push_back(2);
bool enable_specific_losses = true;
bool enable_unspecific_losses = false;
bool enable_ms2_precursors = false;
double product_mz_threshold = 0.05;
// Run uisTransitionsLight with fixed seed for reproducibility
mrma.uisTransitionsLight(light_exp, fragment_types, fragment_charges,
enable_specific_losses, enable_unspecific_losses, enable_ms2_precursors,
product_mz_threshold, swathes, -4, 20, 42, false);
// Count final transitions
size_t final_transitions = light_exp.transitions.size();
// Count identifying transitions
size_t final_identifying = 0;
size_t target_identifying = 0;
size_t decoy_identifying = 0;
for (const auto& tr : light_exp.transitions)
{
if (tr.isIdentifyingTransition())
{
final_identifying++;
if (tr.getDecoy()) decoy_identifying++;
else target_identifying++;
}
}
// Test: New transitions should have been added
TEST_EQUAL(final_transitions > initial_transitions, true)
// Test: Identifying transitions should have been created
TEST_EQUAL(final_identifying > initial_identifying, true)
// Test: Both target and decoy identifying transitions should exist
TEST_EQUAL(target_identifying > 0, true)
TEST_EQUAL(decoy_identifying > 0, true)
// Test: Identifying transitions should have peptidoforms annotated
bool has_peptidoforms = false;
for (const auto& tr : light_exp.transitions)
{
if (tr.isIdentifyingTransition() && !tr.peptidoforms.empty())
{
has_peptidoforms = true;
break;
}
}
TEST_EQUAL(has_peptidoforms, true)
}
END_SECTION
START_SECTION([EXTRA] uisTransitionsLight vs uisTransitions equivalence test)
{
// This test verifies that uisTransitionsLight produces equivalent output to the heavy version
// We compare the number and types of transitions generated
std::vector<std::pair<double, double> > swathes;
swathes.push_back(std::make_pair(400, 425));
swathes.push_back(std::make_pair(424, 450));
swathes.push_back(std::make_pair(449, 475));
swathes.push_back(std::make_pair(474, 500));
swathes.push_back(std::make_pair(499, 525));
swathes.push_back(std::make_pair(524, 550));
swathes.push_back(std::make_pair(549, 575));
swathes.push_back(std::make_pair(574, 600));
swathes.push_back(std::make_pair(599, 625));
swathes.push_back(std::make_pair(624, 650));
swathes.push_back(std::make_pair(649, 675));
swathes.push_back(std::make_pair(674, 700));
swathes.push_back(std::make_pair(699, 725));
swathes.push_back(std::make_pair(724, 750));
swathes.push_back(std::make_pair(749, 775));
swathes.push_back(std::make_pair(774, 800));
swathes.push_back(std::make_pair(799, 825));
swathes.push_back(std::make_pair(824, 850));
swathes.push_back(std::make_pair(849, 875));
swathes.push_back(std::make_pair(874, 900));
swathes.push_back(std::make_pair(899, 925));
swathes.push_back(std::make_pair(924, 950));
swathes.push_back(std::make_pair(949, 975));
swathes.push_back(std::make_pair(974, 1000));
swathes.push_back(std::make_pair(999, 1025));
swathes.push_back(std::make_pair(1024, 1050));
swathes.push_back(std::make_pair(1049, 1075));
swathes.push_back(std::make_pair(1074, 1100));
swathes.push_back(std::make_pair(1099, 1125));
swathes.push_back(std::make_pair(1124, 1150));
swathes.push_back(std::make_pair(1149, 1175));
swathes.push_back(std::make_pair(1174, 1200));
// Load input TraML
TraMLFile traml;
TargetedExperiment targeted_exp_heavy;
String in = "MRMAssay_uisTransitions_input_1.TraML";
traml.load(OPENMS_GET_TEST_DATA_PATH(in), targeted_exp_heavy);
size_t initial_transitions = targeted_exp_heavy.getTransitions().size();
// Convert to Light for light path
OpenSwath::LightTargetedExperiment light_exp;
OpenSwathDataAccessHelper::convertTargetedExp(targeted_exp_heavy, light_exp);
MRMAssay mrma;
std::vector<String> fragment_types;
fragment_types.push_back(String("y"));
std::vector<size_t> fragment_charges;
fragment_charges.push_back(2);
bool enable_specific_losses = true;
bool enable_unspecific_losses = false;
bool enable_ms2_precursors = false;
double product_mz_threshold = 0.05;
// Run heavy version with fixed seed
mrma.uisTransitions(targeted_exp_heavy, fragment_types, fragment_charges,
enable_specific_losses, enable_unspecific_losses, enable_ms2_precursors,
product_mz_threshold, swathes, -4, 20, 42);
// Run light version with same parameters and seed
mrma.uisTransitionsLight(light_exp, fragment_types, fragment_charges,
enable_specific_losses, enable_unspecific_losses, enable_ms2_precursors,
product_mz_threshold, swathes, -4, 20, 42, false);
// Count heavy transitions by type
size_t heavy_total = targeted_exp_heavy.getTransitions().size();
size_t heavy_identifying = 0;
size_t heavy_target_ident = 0;
size_t heavy_decoy_ident = 0;
for (const auto& tr : targeted_exp_heavy.getTransitions())
{
if (tr.isIdentifyingTransition())
{
heavy_identifying++;
if (tr.getDecoyTransitionType() == ReactionMonitoringTransition::DECOY)
heavy_decoy_ident++;
else
heavy_target_ident++;
}
}
// Count light transitions by type
size_t light_total = light_exp.transitions.size();
size_t light_identifying = 0;
size_t light_target_ident = 0;
size_t light_decoy_ident = 0;
for (const auto& tr : light_exp.transitions)
{
if (tr.isIdentifyingTransition())
{
light_identifying++;
if (tr.getDecoy())
light_decoy_ident++;
else
light_target_ident++;
}
}
// Test: Total transition counts should be equal
TEST_EQUAL(light_total, heavy_total)
// Test: Identifying transition counts should be equal
TEST_EQUAL(light_identifying, heavy_identifying)
// Test: Target identifying counts should be equal
TEST_EQUAL(light_target_ident, heavy_target_ident)
// Test: Decoy identifying counts should be equal
TEST_EQUAL(light_decoy_ident, heavy_decoy_ident)
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MzMLValidator_test.cpp | .cpp | 1,338 | 47 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/FORMAT/VALIDATORS/MzMLValidator.h>
#include <OpenMS/DATASTRUCTURES/CVMappings.h>
#include <OpenMS/FORMAT/ControlledVocabulary.h>
///////////////////////////
START_TEST(MzMLValidator, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace OpenMS::Internal;
using namespace std;
CVMappings mapping;
ControlledVocabulary cv;
SemanticValidator* ptr = nullptr;
SemanticValidator* nullPointer = nullptr;
START_SECTION((MzMLValidator(const CVMappings& mapping, const ControlledVocabulary& cv)))
ptr = new MzMLValidator(mapping,cv);
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~MzMLValidator()))
delete ptr;
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/OPXLSpectrumProcessingAlgorithms_test.cpp | .cpp | 4,646 | 110 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Eugen Netz $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/XLMS/OPXLSpectrumProcessingAlgorithms.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/SpectrumHelper.h>
#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGeneratorXLMS.h>
#include <OpenMS/PROCESSING/DEISOTOPING/Deisotoper.h>
using namespace OpenMS;
START_TEST(OPXLSpectrumProcessingAlgorithms, "$Id$")
TheoreticalSpectrumGeneratorXLMS specGen;
Param param = specGen.getParameters();
param.setValue("add_isotopes", "false");
param.setValue("add_metainfo", "true");
param.setValue("add_first_prefix_ion", "false");
param.setValue("y_intensity", 10.0, "Intensity of the y-ions");
param.setValue("add_a_ions", "false");
param.setValue("add_losses", "false");
param.setValue("add_precursor_peaks", "false");
param.setValue("add_k_linked_ions", "false");
specGen.setParameters(param);
PeakSpectrum theo_spec_1, theo_spec_2, exp_spec_1, exp_spec_2;
AASequence peptide = AASequence::fromString("PEPTIDE");
AASequence peptedi = AASequence::fromString("PEPTEDI");
specGen.getLinearIonSpectrum(exp_spec_1, peptide, 2, true, 3);
specGen.getLinearIonSpectrum(exp_spec_2, peptedi, 3, true, 3);
specGen.getLinearIonSpectrum(theo_spec_1, peptide, 3, true, 3);
specGen.getLinearIonSpectrum(theo_spec_2, peptedi, 4, true, 3);
START_SECTION(static PeakSpectrum mergeAnnotatedSpectra(PeakSpectrum & first_spectrum, PeakSpectrum & second_spectrum))
PeakSpectrum merged_spec = OPXLSpectrumProcessingAlgorithms::mergeAnnotatedSpectra(theo_spec_1, theo_spec_2);
TEST_EQUAL(merged_spec.size(), 36)
TEST_EQUAL(merged_spec.getIntegerDataArrays().size(), 1)
TEST_EQUAL(merged_spec.getIntegerDataArrays()[0].size(), 36)
TEST_EQUAL(merged_spec.getStringDataArrays()[0].size(), 36)
TEST_EQUAL(merged_spec.getIntegerDataArrays()[0][10], 3)
TEST_EQUAL(merged_spec.getStringDataArrays()[0][10], "[alpha|ci$y2]")
TEST_EQUAL(merged_spec.getIntegerDataArrays()[0][20], 2)
TEST_EQUAL(merged_spec.getStringDataArrays()[0][20], "[alpha|ci$y2]")
TEST_REAL_SIMILAR(merged_spec[10].getMZ(), 83.04780)
TEST_REAL_SIMILAR(merged_spec[20].getMZ(), 132.04732)
for (Size i = 0; i < merged_spec.size()-1; ++i)
{
TEST_EQUAL(merged_spec[i].getMZ() <= merged_spec[i+1].getMZ(), true)
}
END_SECTION
START_SECTION(static void getSpectrumAlignmentFastCharge(
std::vector<std::pair<Size, Size> > & alignment, double fragment_mass_tolerance,
bool fragment_mass_tolerance_unit_ppm,
const PeakSpectrum& theo_spectrum,
const PeakSpectrum& exp_spectrum,
const DataArrays::IntegerDataArray& theo_charges,
const DataArrays::IntegerDataArray& exp_charges,
DataArrays::FloatDataArray& ppm_error_array,
double intensity_cutoff = 0.0))
std::vector <std::pair <Size, Size> > alignment1;
std::vector <std::pair <Size, Size> > alignment2;
theo_spec_1.sortByPosition();
// slightly shift one of the exp spectra to get non-zero ppm error values
PeakSpectrum exp_spec_3 = exp_spec_2;
for (Peak1D p : exp_spec_3)
{
p.setMZ(p.getMZ() + 0.00001);
}
auto theo_2_it = getDataArrayByName(theo_spec_2.getIntegerDataArrays(), "charge");
DataArrays::IntegerDataArray theo_2_charges = *theo_2_it;
auto exp_3_it = getDataArrayByName(exp_spec_3.getIntegerDataArrays(), "charge");
DataArrays::IntegerDataArray exp_3_charges = *exp_3_it;
DataArrays::IntegerDataArray dummy_charges;
DataArrays::FloatDataArray dummy_array;
DataArrays::FloatDataArray ppm_error_array;
OPXLSpectrumProcessingAlgorithms::getSpectrumAlignmentFastCharge(alignment1, 50, true, theo_spec_1, exp_spec_1, dummy_charges, dummy_charges, dummy_array);
OPXLSpectrumProcessingAlgorithms::getSpectrumAlignmentFastCharge(alignment2, 50, true, theo_spec_2, exp_spec_3, theo_2_charges, exp_3_charges, ppm_error_array);
TEST_EQUAL(alignment1.size(), 15)
TEST_EQUAL(alignment2.size(), 15)
for (Size i = 0; i < alignment2.size(); i++)
{
TEST_REAL_SIMILAR(theo_spec_2[alignment2[i].first].getMZ(), exp_spec_3[alignment2[i].second].getMZ())
TEST_REAL_SIMILAR((theo_spec_2[alignment2[i].first].getMZ() - exp_spec_3[alignment2[i].second].getMZ()) / theo_spec_2[alignment2[i].first].getMZ() / 1e-6, ppm_error_array[i])
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/LinearRegression_test.cpp | .cpp | 4,093 | 128 | // 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/ML/REGRESSION/LinearRegression.h>
///////////////////////////
START_TEST(LinearRegression<Iterator>, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace Math;
using namespace std;
LinearRegression* ptr;
LinearRegression* nullPointer = nullptr;
START_SECTION((LinearRegression()))
ptr = new LinearRegression;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~LinearRegression()))
delete ptr;
END_SECTION
// Create a test data set
vector<double> x_axis(10);
vector<double> y_axis(10);
vector<double> y_axis0(10);
vector<double> weight(10);
for (int i=0; i < 10; ++i)
{
x_axis[i]=i;
y_axis[i]=2*i+4;
y_axis0[i]=2*i; // no intercept
weight[i]=1+i;
}
LinearRegression lin_reg, lin_reg2;
START_SECTION((template < typename Iterator > void computeRegression(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin, bool compute_goodness = true)))
lin_reg.computeRegression(0.95,x_axis.begin(),x_axis.end(),y_axis.begin());
TEST_REAL_SIMILAR(lin_reg.getSlope(),2.0)
TEST_REAL_SIMILAR(lin_reg.getIntercept(),4.0)
TEST_REAL_SIMILAR(lin_reg.getChiSquared(),0.0)
lin_reg2.computeRegression(0.95,x_axis.begin(),x_axis.end(),y_axis0.begin());
TEST_REAL_SIMILAR(lin_reg2.getSlope(), 2.0)
TEST_REAL_SIMILAR(lin_reg2.getIntercept(), 0.0)
TEST_REAL_SIMILAR(lin_reg2.getChiSquared(), 0.0)
END_SECTION
START_SECTION((template < typename Iterator > void computeRegressionWeighted(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin, bool compute_goodness = true)))
lin_reg.computeRegressionWeighted(0.95,x_axis.begin(),x_axis.end(),y_axis.begin(),weight.begin(), false);
TEST_REAL_SIMILAR(lin_reg.getSlope(), 2.0)
TEST_REAL_SIMILAR(lin_reg.getIntercept(), 4.0)
lin_reg2.computeRegressionWeighted(0.95,x_axis.begin(),x_axis.end(),y_axis0.begin(),weight.begin(), false);
TEST_REAL_SIMILAR(lin_reg2.getSlope(), 2.0)
TEST_REAL_SIMILAR(lin_reg2.getIntercept(), 0.0)
lin_reg.computeRegressionWeighted(0.95,x_axis.begin(),x_axis.end(),y_axis.begin(),weight.begin(), true); // to get meta stats (tested below)
END_SECTION
START_SECTION((double getChiSquared() const))
TEST_REAL_SIMILAR(lin_reg.getChiSquared(),0)
END_SECTION
START_SECTION((double getIntercept() const))
TEST_REAL_SIMILAR(lin_reg.getIntercept(),4.0)
END_SECTION
START_SECTION((double getLower() const))
TEST_REAL_SIMILAR(lin_reg.getLower(),-2.0)
END_SECTION
START_SECTION((double getUpper() const))
TEST_REAL_SIMILAR(lin_reg.getUpper(),-2.0)
END_SECTION
START_SECTION((double getSlope() const))
TEST_REAL_SIMILAR(lin_reg.getSlope(),2.0)
END_SECTION
START_SECTION((double getStandDevRes() const))
TEST_REAL_SIMILAR(lin_reg.getStandDevRes(),0.0)
END_SECTION
START_SECTION((double getStandErrSlope() const))
TEST_REAL_SIMILAR(lin_reg.getStandErrSlope(),0.0)
END_SECTION
START_SECTION((double getRSquared() const))
TEST_REAL_SIMILAR(lin_reg.getRSquared(),1.0)
END_SECTION
START_SECTION((double getTValue() const))
TEST_REAL_SIMILAR(lin_reg.getTValue(),2.306)
END_SECTION
START_SECTION((double getXIntercept() const))
TEST_REAL_SIMILAR(lin_reg.getXIntercept(),-2.0)
END_SECTION
START_SECTION((double getRSD() const))
TEST_REAL_SIMILAR(lin_reg.getRSD(),0.0)
END_SECTION
START_SECTION((double getMeanRes() const))
TEST_REAL_SIMILAR(lin_reg.getMeanRes(),0.0)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/WindowMower_test.cpp | .cpp | 8,071 | 282 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Volker Mosthaf, Andreas Bertsch $
// --------------------------------------------------------------------------
//
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/PROCESSING/FILTERING/WindowMower.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/FORMAT/DTAFile.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(WindowMower, "$Id$")
/////////////////////////////////////////////////////////////
WindowMower* e_ptr = nullptr;
WindowMower* e_nullPointer = nullptr;
START_SECTION((WindowMower()))
e_ptr = new WindowMower;
TEST_NOT_EQUAL(e_ptr, e_nullPointer)
END_SECTION
START_SECTION((~WindowMower()))
delete e_ptr;
END_SECTION
e_ptr = new WindowMower();
START_SECTION((WindowMower(const WindowMower& source)))
WindowMower copy(*e_ptr);
TEST_EQUAL(copy.getParameters(), e_ptr->getParameters())
TEST_EQUAL(copy.getName(), e_ptr->getName())
END_SECTION
START_SECTION((WindowMower& operator = (const WindowMower& source)))
WindowMower copy;
copy = *e_ptr;
TEST_EQUAL(copy.getParameters(), e_ptr->getParameters())
TEST_EQUAL(copy.getName(), e_ptr->getName())
END_SECTION
START_SECTION((template<typename SpectrumType> void filterPeakSpectrumForTopNInSlidingWindow(SpectrumType& spectrum)))
DTAFile dta_file;
PeakSpectrum spec;
dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec);
TEST_EQUAL(spec.size(), 121)
Param p(e_ptr->getParameters());
p.setValue("windowsize", 50.0); // default
p.setValue("peakcount", 2); // default
p.setValue("movetype", "slide"); // default and not needed as we directly call sliding window function
e_ptr->setParameters(p);
e_ptr->filterPeakSpectrumForTopNInSlidingWindow(spec);
TEST_EQUAL(spec.size(), 56)
END_SECTION
START_SECTION((template<typename SpectrumType> void filterPeakSpectrumForTopNInJumpingWindow(SpectrumType& spectrum)))
DTAFile dta_file;
PeakSpectrum spec;
dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec);
TEST_EQUAL(spec.size(), 121)
Param p(e_ptr->getParameters());
p.setValue("windowsize", 50.0); // default
p.setValue("peakcount", 2); // default
p.setValue("movetype", "jump"); // actually not needed as we directly call jumping window function
e_ptr->setParameters(p);
e_ptr->filterPeakSpectrumForTopNInJumpingWindow(spec);
TEST_EQUAL(spec.size(), 30)
END_SECTION
START_SECTION((void filterPeakMap(PeakMap& exp)))
DTAFile dta_file;
PeakSpectrum spec;
dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec);
PeakMap pm;
pm.addSpectrum(spec);
TEST_EQUAL(pm.begin()->size(), 121)
Param p(e_ptr->getParameters());
p.setValue("windowsize", 50.0); // default
p.setValue("peakcount", 2);
p.setValue("movetype", "slide"); // default
e_ptr->setParameters(p);
e_ptr->filterPeakMap(pm);
TEST_EQUAL(pm.begin()->size(), 56)
END_SECTION
START_SECTION((void filterPeakSpectrum(PeakSpectrum& spectrum)))
DTAFile dta_file;
PeakSpectrum spec;
dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec);
TEST_EQUAL(spec.size(), 121)
Param p(e_ptr->getParameters());
p.setValue("windowsize", 50.0); // default
p.setValue("peakcount", 2);
p.setValue("movetype", "slide");
e_ptr->setParameters(p);
e_ptr->filterPeakSpectrum(spec);
TEST_EQUAL(spec.size(), 56)
// test data array handling
PeakSpectrum s_da;
// create a "triangle" shape with apex at i=50
/*
int mz DA_int DA_string
0.1 0 0 up
1.1 1 1 up
2.1 2 2 up
...
47.1 47 47 up
48.1 48 48 up
49.1 49 49 up
50.2 50 50 down
49.2 51 51 down
48.2 52 52 down
...
3.2 97 97 down
2.2 98 98 down
1.2 99 99 down
*/
p.setValue("movetype", "slide");
e_ptr->setParameters(p);
s_da.getIntegerDataArrays().resize(1);
s_da.getStringDataArrays().resize(1);
for (Size i = 0; i != 50; ++i)
{
s_da.push_back(Peak1D(i, i + 0.1));
s_da.getIntegerDataArrays()[0].push_back(i);
s_da.getStringDataArrays()[0].push_back("up");
}
for (int i = 50; i != 100; ++i)
{
s_da.push_back(Peak1D(i, (100 - i) + 0.2));
s_da.getIntegerDataArrays()[0].push_back(i);
s_da.getStringDataArrays()[0].push_back("down");
}
e_ptr->filterPeakSpectrum(s_da);
/* result: the 4 rows in the middle: (48,49) + (49,50) + (50, 51) = 48,49,50,51
int mz DA_int DA_string
48.1 48 48 up
49.1 49 49 up
50.2 50 50 down
49.2 51 51 down
*/
TEST_EQUAL(s_da.size(), 4)
TEST_EQUAL(s_da[0].getIntensity(), 48.1)
TEST_EQUAL(s_da[1].getIntensity(), 49.1)
TEST_EQUAL(s_da[2].getIntensity(), 50.2)
TEST_EQUAL(s_da[3].getIntensity(), 49.2)
TEST_EQUAL(s_da.getIntegerDataArrays()[0][0], 48)
TEST_EQUAL(s_da.getIntegerDataArrays()[0][1], 49)
TEST_EQUAL(s_da.getIntegerDataArrays()[0][2], 50)
TEST_EQUAL(s_da.getIntegerDataArrays()[0][3], 51)
TEST_EQUAL(s_da.getStringDataArrays()[0][0], "up")
TEST_EQUAL(s_da.getStringDataArrays()[0][1], "up")
TEST_EQUAL(s_da.getStringDataArrays()[0][2], "down")
TEST_EQUAL(s_da.getStringDataArrays()[0][3], "down")
p.setValue("movetype", "jump");
e_ptr->setParameters(p);
s_da.clear(true);
s_da.getIntegerDataArrays().resize(1);
s_da.getStringDataArrays().resize(1);
for (Size i = 0; i != 50; ++i)
{
s_da.push_back(Peak1D(i, i + 0.1));
s_da.getIntegerDataArrays()[0].push_back(i);
s_da.getStringDataArrays()[0].push_back("up");
}
for (int i = 50; i != 100; ++i)
{
s_da.push_back(Peak1D(i, (100 - i) + 0.2));
s_da.getIntegerDataArrays()[0].push_back(i);
s_da.getStringDataArrays()[0].push_back("down");
}
e_ptr->filterPeakSpectrum(s_da);
/* result: first window from m/z 0 to 49 and second window from m/z 50 to 99
int mz DA_int DA_string
48.1 48 48 up
49.1 49 49 up
50.2 50 50 down
49.2 51 51 down
*/
TEST_EQUAL(s_da.size(), 4)
TEST_EQUAL(s_da[0].getIntensity(), 48.1)
TEST_EQUAL(s_da[1].getIntensity(), 49.1)
TEST_EQUAL(s_da[2].getIntensity(), 50.2)
TEST_EQUAL(s_da[3].getIntensity(), 49.2)
TEST_EQUAL(s_da.getIntegerDataArrays()[0][0], 48)
TEST_EQUAL(s_da.getIntegerDataArrays()[0][1], 49)
TEST_EQUAL(s_da.getIntegerDataArrays()[0][2], 50)
TEST_EQUAL(s_da.getIntegerDataArrays()[0][3], 51)
TEST_EQUAL(s_da.getStringDataArrays()[0][0], "up")
TEST_EQUAL(s_da.getStringDataArrays()[0][1], "up")
TEST_EQUAL(s_da.getStringDataArrays()[0][2], "down")
TEST_EQUAL(s_da.getStringDataArrays()[0][3], "down")
p.setValue("windowsize", 10.0);
e_ptr->setParameters(p);
s_da.clear(true);
s_da.getIntegerDataArrays().resize(1);
s_da.getStringDataArrays().resize(1);
for (Size i = 0; i != 50; ++i)
{
s_da.push_back(Peak1D(i, i + 0.1));
s_da.getIntegerDataArrays()[0].push_back(i);
s_da.getStringDataArrays()[0].push_back("up");
}
for (int i = 50; i != 100; ++i)
{
s_da.push_back(Peak1D(i, (100 - i) + 0.2));
s_da.getIntegerDataArrays()[0].push_back(i);
s_da.getStringDataArrays()[0].push_back("down");
}
e_ptr->filterPeakSpectrum(s_da);
/*
int mz DA_int DA_string
8.1 8 8 up
9.1 9 9 up
18.1 18 18 up
19.1 19 19 up
28.1 28 28 up
29.1 29 29 up
38.1 38 38 up
39.1 39 39 up
48.1 48 48 up
49.1 49 49 up
50.2 50 50 down
49.2 51 51 down
40.2 60 60 down
39.2 61 61 down
30.2 70 70 down
29.2 71 71 down
20.2 80 80 down
19.2 81 81 down
10.2 90 90 down
9.2 91 91 down
*/
// note that the last window contains only one peak
// because the peak fraction in window mower is 0.9
TEST_EQUAL(s_da.size(), 20)
END_SECTION
delete e_ptr;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MetaInfoRegistry_test.cpp | .cpp | 8,104 | 214 | // 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>
///////////////////////////
#ifdef _OPENMP
#include <omp.h>
#endif
#include <OpenMS/METADATA/MetaInfoRegistry.h>
///////////////////////////
START_TEST(MetaInfoRegistry, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
MetaInfoRegistry* test = nullptr;
MetaInfoRegistry* nullPointer = nullptr;
START_SECTION((MetaInfoRegistry()))
test = new MetaInfoRegistry;
TEST_NOT_EQUAL(test, nullPointer)
END_SECTION
START_SECTION((~MetaInfoRegistry()))
delete test;
END_SECTION
MetaInfoRegistry mir;
START_SECTION((UInt registerName(const String& name, const String& description = "", const String& unit = "")))
{
UInt testname = mir.registerName("testname", "this is just a test");
TEST_EQUAL(testname, 1024);
UInt retention_time = mir.registerName("retention time", "this is just another test", "sec");
TEST_EQUAL(retention_time, 1025);
UInt another_testname = mir.registerName("another testname", "i will be set later", "me too");
TEST_EQUAL(another_testname, 1026);
}
END_SECTION
START_SECTION((void setDescription(UInt index, const String& description)))
mir.setDescription(1026, "foo");
TEST_STRING_EQUAL(mir.getDescription(1026), "foo")
END_SECTION
START_SECTION((void setDescription(const String& name, const String& description)))
mir.setDescription("another testname", "bar");
TEST_STRING_EQUAL(mir.getDescription(1026), "bar")
END_SECTION
START_SECTION((void setUnit(UInt index, const String& unit)))
mir.setUnit(1026, "foo");
TEST_STRING_EQUAL(mir.getUnit(1026), "foo")
END_SECTION
START_SECTION((void setUnit(const String& name, const String& unit)))
mir.setUnit("another testname", "bar");
TEST_STRING_EQUAL(mir.getUnit(1026), "bar")
END_SECTION
START_SECTION((UInt getIndex(const String& name) const))
TEST_EQUAL(mir.getIndex("testname"), 1024)
TEST_EQUAL(mir.getIndex("retention time"), 1025)
TEST_EQUAL(mir.getIndex("isotopic_range"), 1)
TEST_EQUAL(mir.getIndex("cluster_id"), 2)
TEST_EQUAL(mir.getIndex("unregistered name"), UInt(-1))
END_SECTION
START_SECTION((String getName(UInt index) const))
TEST_STRING_EQUAL(mir.getName(1), "isotopic_range")
TEST_STRING_EQUAL(mir.getName(2), "cluster_id")
TEST_STRING_EQUAL(mir.getName(3), "label")
TEST_STRING_EQUAL(mir.getName(4), "icon")
TEST_STRING_EQUAL(mir.getName(1024), "testname")
TEST_STRING_EQUAL(mir.getName(1025), "retention time")
END_SECTION
START_SECTION((String getDescription(UInt index) const))
TEST_STRING_EQUAL(mir.getDescription(1024), "this is just a test")
TEST_STRING_EQUAL(mir.getDescription(1025), "this is just another test")
TEST_STRING_EQUAL(mir.getDescription(1), "consecutive numbering of the peaks in an isotope pattern. 0 is the monoisotopic peak")
TEST_STRING_EQUAL(mir.getDescription(2), "consecutive numbering of isotope clusters in a spectrum")
END_SECTION
START_SECTION((String getDescription(const String& name) const))
TEST_STRING_EQUAL(mir.getDescription("testname"), "this is just a test")
TEST_STRING_EQUAL(mir.getDescription("retention time"), "this is just another test")
TEST_STRING_EQUAL(mir.getDescription("isotopic_range"), "consecutive numbering of the peaks in an isotope pattern. 0 is the monoisotopic peak")
TEST_STRING_EQUAL(mir.getDescription("cluster_id"), "consecutive numbering of isotope clusters in a spectrum")
END_SECTION
START_SECTION((String getUnit(UInt index) const))
TEST_STRING_EQUAL(mir.getUnit(1024), "")
TEST_STRING_EQUAL(mir.getUnit(1025), "sec")
TEST_STRING_EQUAL(mir.getUnit(1), "")
TEST_STRING_EQUAL(mir.getUnit(2), "")
END_SECTION
START_SECTION((String getUnit(const String& name) const))
TEST_STRING_EQUAL(mir.getUnit("testname"), "")
TEST_STRING_EQUAL(mir.getUnit("retention time"), "sec")
TEST_STRING_EQUAL(mir.getUnit("isotopic_range"), "")
TEST_STRING_EQUAL(mir.getUnit("cluster_id"), "")
END_SECTION
START_SECTION((MetaInfoRegistry(const MetaInfoRegistry& rhs)))
MetaInfoRegistry mir2(mir);
TEST_EQUAL(mir2.getIndex("testname"), 1024)
TEST_EQUAL(mir2.getIndex("retention time"), 1025)
TEST_STRING_EQUAL(mir2.getName(1), "isotopic_range")
TEST_STRING_EQUAL(mir2.getName(1024), "testname")
TEST_STRING_EQUAL(mir2.getName(1025), "retention time")
TEST_STRING_EQUAL(mir2.getDescription(1024), "this is just a test")
TEST_STRING_EQUAL(mir2.getDescription(1025), "this is just another test")
TEST_STRING_EQUAL(mir2.getDescription("testname"), "this is just a test")
TEST_STRING_EQUAL(mir2.getDescription("retention time"), "this is just another test")
TEST_STRING_EQUAL(mir2.getUnit(1024), "")
TEST_STRING_EQUAL(mir2.getUnit(1025), "sec")
TEST_STRING_EQUAL(mir2.getUnit("testname"), "")
TEST_STRING_EQUAL(mir2.getUnit("retention time"), "sec")
END_SECTION
START_SECTION((MetaInfoRegistry& operator=(const MetaInfoRegistry& rhs)))
MetaInfoRegistry mir2;
mir2 = mir;
TEST_EQUAL(mir2.getIndex("testname"), 1024)
TEST_EQUAL(mir2.getIndex("retention time"), 1025)
TEST_STRING_EQUAL(mir2.getName(1), "isotopic_range")
TEST_STRING_EQUAL(mir2.getName(1024), "testname")
TEST_STRING_EQUAL(mir2.getName(1025), "retention time")
TEST_STRING_EQUAL(mir2.getDescription(1024), "this is just a test")
TEST_STRING_EQUAL(mir2.getDescription(1025), "this is just another test")
TEST_STRING_EQUAL(mir2.getDescription("testname"), "this is just a test")
TEST_STRING_EQUAL(mir2.getDescription("retention time"), "this is just another test")
TEST_STRING_EQUAL(mir2.getUnit(1024), "")
TEST_STRING_EQUAL(mir2.getUnit(1025), "sec")
TEST_STRING_EQUAL(mir2.getUnit("testname"), "")
TEST_STRING_EQUAL(mir2.getUnit("retention time"), "sec")
END_SECTION
START_SECTION([EXTRA] multithreaded example)
{
// All measurements are best of three (wall time, Linux, 8 threads)
//
// Serial execution of code:
// 1e7 iterations -> 1.10 seconds
// 1e6 iterations -> 0.31 seconds
//
// Parallel execution of code:
// 1e7 iterations -> 3.41 seconds with omp critical
// 1e7 iterations -> 4.30 seconds with std::mutex
// 1e7 iterations -> ??? seconds with boost::shared_mutex
//
// 1e6 iterations -> 0.36 seconds with omp critical
// 1e6 iterations -> 0.43 seconds with std::mutex
// 1e6 iterations -> 5.96 seconds with boost::shared_mutex
// 1e7 iterations with 1000 different values
// Serial execution of code:
// 1e7 iterations -> 6.84 seconds
// 1e6 iterations -> 0.91 seconds
//
// Parallel execution of code:
// 1e7 iterations -> 5.20 seconds with omp critical
// 1e7 iterations -> 7.44 seconds with std::mutex
// 1e7 iterations -> ??? seconds with boost::shared_mutex
//
// 1e6 iterations -> 0.55 seconds with omp critical
// 1e6 iterations -> 0.78 seconds with std::mutex
// 1e6 iterations -> 7.63 seconds with boost::shared_mutex
// Note how the omp critical is 3x slower for the "same value" code than
// serial code whereas it is slightly faster for the "1000 different values"
// code.
// The shared_mutex code is an order of magnitude slower (10-20x) for both
// cases. It seems for this case, most case is spent in locking / unlocking
// the mutex.
int nr_iterations (1e6);
int test = 0;
#pragma omp parallel for reduction(+: test)
for (int k = 1; k < nr_iterations + 1; k++)
{
#if 0
std::string val = "newValue" + String(k%1000);
#else
std::string val = "newValue";
#endif
UInt index = mir.registerName(val);
mir.setDescription(index, val);
test += index;
}
TEST_EQUAL(test, 1027 * nr_iterations)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/TMTElevenPlexQuantitationMethod_test.cpp | .cpp | 8,437 | 238 | // 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/TMTElevenPlexQuantitationMethod.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/Matrix.h>
using namespace OpenMS;
using namespace std;
START_TEST(TMTElevenPlexQuantitationMethod, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
TMTElevenPlexQuantitationMethod* ptr = 0;
TMTElevenPlexQuantitationMethod* null_ptr = 0;
START_SECTION(TMTElevenPlexQuantitationMethod())
{
ptr = new TMTElevenPlexQuantitationMethod();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~TMTElevenPlexQuantitationMethod())
{
delete ptr;
}
END_SECTION
START_SECTION((const String& getMethodName() const ))
{
TMTElevenPlexQuantitationMethod quant_meth;
TEST_EQUAL(quant_meth.getMethodName(), "tmt11plex")
}
END_SECTION
START_SECTION((const IsobaricChannelList& getChannelInformation() const ))
{
TMTElevenPlexQuantitationMethod quant_meth;
IsobaricQuantitationMethod::IsobaricChannelList channel_list = quant_meth.getChannelInformation();
TEST_EQUAL(channel_list.size(), 11)
ABORT_IF(channel_list.size() != 11)
// descriptions are empty by default
TEST_STRING_EQUAL(channel_list[0].description, "")
TEST_STRING_EQUAL(channel_list[1].description, "")
TEST_STRING_EQUAL(channel_list[2].description, "")
TEST_STRING_EQUAL(channel_list[3].description, "")
TEST_STRING_EQUAL(channel_list[4].description, "")
TEST_STRING_EQUAL(channel_list[5].description, "")
TEST_STRING_EQUAL(channel_list[6].description, "")
TEST_STRING_EQUAL(channel_list[7].description, "")
TEST_STRING_EQUAL(channel_list[8].description, "")
TEST_STRING_EQUAL(channel_list[9].description, "")
TEST_STRING_EQUAL(channel_list[10].description, "")
// check masses&co
TEST_EQUAL(channel_list[0].name, "126")
TEST_EQUAL(channel_list[0].id, 0)
TEST_EQUAL(channel_list[0].center, 126.127726)
TEST_EQUAL(channel_list[0].affected_channels[0], -1)
TEST_EQUAL(channel_list[0].affected_channels[1], -1)
TEST_EQUAL(channel_list[0].affected_channels[2], 2)
TEST_EQUAL(channel_list[0].affected_channels[3], 4)
TEST_EQUAL(channel_list[1].name, "127N")
TEST_EQUAL(channel_list[1].id, 1)
TEST_EQUAL(channel_list[1].center, 127.124761)
TEST_EQUAL(channel_list[1].affected_channels[0], -1)
TEST_EQUAL(channel_list[1].affected_channels[1], -1)
TEST_EQUAL(channel_list[1].affected_channels[2], 3)
TEST_EQUAL(channel_list[1].affected_channels[3], 5)
TEST_EQUAL(channel_list[2].name, "127C")
TEST_EQUAL(channel_list[2].id, 2)
TEST_EQUAL(channel_list[2].center, 127.131081)
TEST_EQUAL(channel_list[2].affected_channels[0], -1)
TEST_EQUAL(channel_list[2].affected_channels[1], 0)
TEST_EQUAL(channel_list[2].affected_channels[2], 4)
TEST_EQUAL(channel_list[2].affected_channels[3], 6)
TEST_EQUAL(channel_list[3].name, "128N")
TEST_EQUAL(channel_list[3].id, 3)
TEST_EQUAL(channel_list[3].center, 128.128116)
TEST_EQUAL(channel_list[3].affected_channels[0], -1)
TEST_EQUAL(channel_list[3].affected_channels[1], 1)
TEST_EQUAL(channel_list[3].affected_channels[2], 5)
TEST_EQUAL(channel_list[3].affected_channels[3], 7)
TEST_EQUAL(channel_list[4].name, "128C")
TEST_EQUAL(channel_list[4].id, 4)
TEST_EQUAL(channel_list[4].center, 128.134436)
TEST_EQUAL(channel_list[4].affected_channels[0], 0)
TEST_EQUAL(channel_list[4].affected_channels[1], 2)
TEST_EQUAL(channel_list[4].affected_channels[2], 6)
TEST_EQUAL(channel_list[4].affected_channels[3], 8)
TEST_EQUAL(channel_list[5].name, "129N")
TEST_EQUAL(channel_list[5].id, 5)
TEST_EQUAL(channel_list[5].center, 129.131471)
TEST_EQUAL(channel_list[5].affected_channels[0], 1)
TEST_EQUAL(channel_list[5].affected_channels[1], 3)
TEST_EQUAL(channel_list[5].affected_channels[2], 7)
TEST_EQUAL(channel_list[5].affected_channels[3], 9)
TEST_EQUAL(channel_list[6].name, "129C")
TEST_EQUAL(channel_list[6].id, 6)
TEST_EQUAL(channel_list[6].center, 129.137790)
TEST_EQUAL(channel_list[6].affected_channels[0], 2)
TEST_EQUAL(channel_list[6].affected_channels[1], 4)
TEST_EQUAL(channel_list[6].affected_channels[2], 8)
TEST_EQUAL(channel_list[6].affected_channels[3], 10)
TEST_EQUAL(channel_list[7].name, "130N")
TEST_EQUAL(channel_list[7].id, 7)
TEST_EQUAL(channel_list[7].center, 130.134825)
TEST_EQUAL(channel_list[7].affected_channels[0], 3)
TEST_EQUAL(channel_list[7].affected_channels[1], 5)
TEST_EQUAL(channel_list[7].affected_channels[2], 9)
TEST_EQUAL(channel_list[7].affected_channels[3], -1)
TEST_EQUAL(channel_list[8].name, "130C")
TEST_EQUAL(channel_list[8].id, 8)
TEST_EQUAL(channel_list[8].center, 130.141145)
TEST_EQUAL(channel_list[8].affected_channels[0], 4)
TEST_EQUAL(channel_list[8].affected_channels[1], 6)
TEST_EQUAL(channel_list[8].affected_channels[2], 10)
TEST_EQUAL(channel_list[8].affected_channels[3], -1)
TEST_EQUAL(channel_list[9].name, "131N")
TEST_EQUAL(channel_list[9].id, 9)
TEST_EQUAL(channel_list[9].center, 131.138180)
TEST_EQUAL(channel_list[9].affected_channels[0], 5)
TEST_EQUAL(channel_list[9].affected_channels[1], 7)
TEST_EQUAL(channel_list[9].affected_channels[2], -1)
TEST_EQUAL(channel_list[9].affected_channels[3], -1)
TEST_EQUAL(channel_list[10].name, "131C")
TEST_EQUAL(channel_list[10].id, 10)
TEST_EQUAL(channel_list[10].center, 131.144500)
TEST_EQUAL(channel_list[10].affected_channels[0], 6)
TEST_EQUAL(channel_list[10].affected_channels[1], 8)
TEST_EQUAL(channel_list[10].affected_channels[2], -1)
TEST_EQUAL(channel_list[10].affected_channels[3], -1)
}
END_SECTION
START_SECTION((Size getNumberOfChannels() const ))
{
TMTElevenPlexQuantitationMethod quant_meth;
TEST_EQUAL(quant_meth.getNumberOfChannels(), 11)
}
END_SECTION
START_SECTION((virtual Matrix<double> getIsotopeCorrectionMatrix() const ))
{
TMTElevenPlexQuantitationMethod quant_meth;
// we only check the default matrix here which is an identity matrix
// for tmt11plex
Matrix<double> m = quant_meth.getIsotopeCorrectionMatrix();
TEST_EQUAL(m.rows(), 11)
TEST_EQUAL(m.cols(), 11)
ABORT_IF(m.rows() != 11)
ABORT_IF(m.cols() != 11)
for (Size i = 0; i < m.rows(); ++i)
{
for (Size j = 0; j < m.cols(); ++j)
{
if (i == j) { TEST_TRUE(m(i,j) > 0.5 ) } // diagonal entries should be largest
else { TEST_TRUE(m(i,j) < 0.5) }
}
}
}
END_SECTION
START_SECTION((Size getReferenceChannel() const ))
{
TMTElevenPlexQuantitationMethod quant_meth;
TEST_EQUAL(quant_meth.getReferenceChannel(), 0)
Param p;
p.setValue("reference_channel","128N");
quant_meth.setParameters(p);
TEST_EQUAL(quant_meth.getReferenceChannel(), 3)
}
END_SECTION
START_SECTION((TMTElevenPlexQuantitationMethod(const TMTElevenPlexQuantitationMethod &other)))
{
TMTElevenPlexQuantitationMethod qm;
Param p = qm.getParameters();
p.setValue("channel_127N_description", "new_description");
p.setValue("reference_channel", "129C");
qm.setParameters(p);
TMTElevenPlexQuantitationMethod qm2(qm);
IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation();
TEST_STRING_EQUAL(channel_list[1].description, "new_description")
TEST_EQUAL(qm2.getReferenceChannel(), 6)
}
END_SECTION
START_SECTION((TMTElevenPlexQuantitationMethod& operator=(const TMTElevenPlexQuantitationMethod &rhs)))
{
TMTElevenPlexQuantitationMethod qm;
Param p = qm.getParameters();
p.setValue("channel_127N_description", "new_description");
p.setValue("reference_channel", "130C");
qm.setParameters(p);
TMTElevenPlexQuantitationMethod qm2 = qm;
IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation();
TEST_STRING_EQUAL(channel_list[1].description, "new_description")
TEST_EQUAL(qm2.getReferenceChannel(), 8)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SpectrumAddition_test.cpp | .cpp | 10,712 | 301 | // 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/ANALYSIS/OPENSWATH/SpectrumAddition.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(SpectrumAddition, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION((void sortSpectrumByMZ(OpenSwath::Spectrum& spec)) - No IM)
{
OpenSwath::SpectrumPtr spec(new OpenSwath::Spectrum());
OpenSwath::BinaryDataArrayPtr mass(new OpenSwath::BinaryDataArray);
OpenSwath::BinaryDataArrayPtr intensity(new OpenSwath::BinaryDataArray);
// Intensity Sorted
std::vector<double> intensSorted = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};
// Mass Sorted
std::vector<double> massSorted = {
100, 101.5, 101.9, 102.0, 102.1, 102.11, 102.2, 102.25, 102.3, 102.4, 102.45
};
// Intensity Not Sorted
std::vector<double> intensNotSorted = {
11, 4, 3, 5, 6, 7, 8, 9, 1, 2, 10
};
// Mass Not Sorted
std::vector<double> massNotSorted = {
102.45, 102.0, 101.9, 102.1, 102.11, 102.2, 102.25, 102.3, 100, 101.5, 102.4
};
// IM Not Sorted
std::vector<double> imNotSorted = {
11, 4, 3, 5, 6, 7, 8, 9, 1, 2, 10
};
mass->data=massNotSorted;
intensity->data=intensNotSorted;
spec->setMZArray(mass);
spec->setIntensityArray(intensity);
SpectrumAddition::sortSpectrumByMZ(*spec);
TEST_EQUAL(spec->getMZArray()->data.size(), massSorted.size());
TEST_EQUAL(spec->getIntensityArray()->data.size(), intensSorted.size());
for (size_t i=0; i<massSorted.size(); i++)
{
TEST_REAL_SIMILAR(massSorted[i], spec->getMZArray()->data[i]);
TEST_REAL_SIMILAR(intensSorted[i], spec->getIntensityArray()->data[i]);
}
}
END_SECTION
START_SECTION((void sortSpectrumByMZ(OpenSwath::Spectrum& spec)) - With IM)
{
OpenSwath::SpectrumPtr specIM(new OpenSwath::Spectrum());
OpenSwath::BinaryDataArrayPtr mass(new OpenSwath::BinaryDataArray);
OpenSwath::BinaryDataArrayPtr intensity(new OpenSwath::BinaryDataArray);
OpenSwath::BinaryDataArrayPtr im(new OpenSwath::BinaryDataArray);
// Intensity Sorted
std::vector<double> intensSorted = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};
// Mass Sorted
std::vector<double> massSorted = {
100, 101.5, 101.9, 102.0, 102.1, 102.11, 102.2, 102.25, 102.3, 102.4, 102.45
};
// IM Sorted
std::vector<double> imSorted = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};
// Intensity Not Sorted
std::vector<double> intensNotSorted = {
11, 4, 3, 5, 6, 7, 8, 9, 1, 2, 10
};
// Mass Not Sorted
std::vector<double> massNotSorted = {
102.45, 102.0, 101.9, 102.1, 102.11, 102.2, 102.25, 102.3, 100, 101.5, 102.4
};
// IM Not Sorted
std::vector<double> imNotSorted = {
11, 4, 3, 5, 6, 7, 8, 9, 1, 2, 10
};
// Create non sorted IM spectrum
mass->data=massNotSorted;
intensity->data=intensNotSorted;
im->data=imNotSorted;
specIM->setMZArray(mass);
specIM->setIntensityArray(intensity);
specIM->setDriftTimeArray(im);
mass->data=massNotSorted;
intensity->data=intensNotSorted;
im->data=imNotSorted;
SpectrumAddition::sortSpectrumByMZ(*specIM);
TEST_EQUAL(specIM->getMZArray()->data.size(), massSorted.size());
TEST_EQUAL(specIM->getIntensityArray()->data.size(), intensSorted.size());
TEST_EQUAL(specIM->getDriftTimeArray()->data.size(), imSorted.size());
for (size_t i=0; i<massSorted.size(); i++)
{
TEST_REAL_SIMILAR(massSorted[i], specIM->getMZArray()->data[i]);
TEST_REAL_SIMILAR(intensSorted[i], specIM->getIntensityArray()->data[i]);
TEST_REAL_SIMILAR(imSorted[i], specIM->getDriftTimeArray()->data[i]);
}
}
END_SECTION
START_SECTION((static OpenSwath::SpectrumPtr addUpSpectra(std::vector< OpenSwath::SpectrumPtr > all_spectra, double sampling_rate, double filter_zeros)) )
{
OpenSwath::SpectrumPtr spec1(new OpenSwath::Spectrum());
OpenSwath::BinaryDataArrayPtr mass1(new OpenSwath::BinaryDataArray);
OpenSwath::BinaryDataArrayPtr intensity1(new OpenSwath::BinaryDataArray);
OpenSwath::SpectrumPtr spec2(new OpenSwath::Spectrum());
OpenSwath::BinaryDataArrayPtr mass2(new OpenSwath::BinaryDataArray);
OpenSwath::BinaryDataArrayPtr intensity2(new OpenSwath::BinaryDataArray);
// Intensity
static const double arr1[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};
std::vector<double> intensity1_ (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) );
intensity1->data = intensity1_;
static const double arr2[] = {
1, 3, 5, 7, 9, 11, 9, 7, 5, 3, 1
};
std::vector<double> intensity2_ (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) );
intensity2->data = intensity2_;
// Mass
static const double arr3[] = {
100, 101.5, 101.9, 102.0, 102.1, 102.11, 102.2, 102.25, 102.3, 102.4, 102.45
};
std::vector<double> mass1_ (arr3, arr3 + sizeof(arr3) / sizeof(arr3[0]) );
mass1->data = mass1_;
static const double arr4[] = {
100, 101.6, 101.95, 102.0, 102.05, 102.1, 102.12, 102.15, 102.2, 102.25, 102.30
};
std::vector<double> mass2_ (arr4, arr4 + sizeof(arr4) / sizeof(arr4[0]) );
mass2->data = mass2_;
spec1->setMZArray( mass1);
spec1->setIntensityArray(intensity1);
spec2->setMZArray( mass2);
spec2->setIntensityArray(intensity2);
std::vector<OpenSwath::SpectrumPtr> all_spectra;
OpenSwath::SpectrumPtr empty_result = SpectrumAddition::addUpSpectra(all_spectra, 0.1, false);
TEST_EQUAL(empty_result->getMZArray()->data.size(), 0);
all_spectra.clear();
OpenSwath::SpectrumPtr a(new OpenSwath::Spectrum());
OpenSwath::SpectrumPtr b(new OpenSwath::Spectrum());
all_spectra.push_back(a);
all_spectra.push_back(b);
OpenSwath::SpectrumPtr empty2 = SpectrumAddition::addUpSpectra(all_spectra, 0.1, false);
TEST_EQUAL(empty2->getMZArray()->data.size(), 0);
all_spectra.clear();
all_spectra.push_back(spec1);
all_spectra.push_back(spec2);
OpenSwath::SpectrumPtr result = SpectrumAddition::addUpSpectra(all_spectra, 0.1, false);
TEST_EQUAL(result->getMZArray()->data.size(), 25);
OpenSwath::SpectrumPtr result_filtered = SpectrumAddition::addUpSpectra(all_spectra, 0.1, true);
TEST_EQUAL(result_filtered->getMZArray()->data.size(), 9);
TEST_REAL_SIMILAR(result_filtered->getMZArray()->data[0], 100.0);
TEST_REAL_SIMILAR(result_filtered->getIntensityArray()->data[0], 2);
TEST_REAL_SIMILAR(result_filtered->getMZArray()->data[3], 101.9);
TEST_REAL_SIMILAR(result_filtered->getIntensityArray()->data[3], 3 + 5/2.0); // 3 @ 101.9 and 5 @ 101.95
std::cout << " result size " << result->getMZArray()->data.size() << " and result m/z" << std::endl;
std::copy(result_filtered->getMZArray()->data.begin(), result_filtered->getMZArray()->data.end(),
std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl << "and result intensity " << std::endl;
std::copy(result_filtered->getIntensityArray()->data.begin(), result_filtered->getIntensityArray()->data.end(),
std::ostream_iterator<double>(std::cout, " "));
}
END_SECTION
START_SECTION((static OpenMS::MSSpectrum addUpSpectra(std::vector< OpenMS::Spectrum<> all_spectra, double sampling_rate, bool filter_zeros) ))
{
// Intensity
static const double arr1[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};
std::vector<double> intensity1_ (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) );
static const double arr2[] = {
1, 3, 5, 7, 9, 11, 9, 7, 5, 3, 1
};
std::vector<double> intensity2_ (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) );
// Mass
static const double arr3[] = {
100, 101.5, 101.9, 102.0, 102.1, 102.11, 102.2, 102.25, 102.3, 102.4, 102.45
};
std::vector<double> mass1_ (arr3, arr3 + sizeof(arr3) / sizeof(arr3[0]) );
static const double arr4[] = {
100, 101.6, 101.95, 102.0, 102.05, 102.1, 102.12, 102.15, 102.2, 102.25, 102.30
};
std::vector<double> mass2_ (arr4, arr4 + sizeof(arr4) / sizeof(arr4[0]) );
OpenMS::MSSpectrum s1;
for (Size k = 0; k < mass1_.size(); k++)
{
s1.push_back(Peak1D(mass1_[k], intensity1_[k]));
}
OpenMS::MSSpectrum s2;
for (Size k = 0; k < mass2_.size(); k++)
{
s2.push_back(Peak1D(mass2_[k], intensity2_[k]));
}
std::vector<MSSpectrum> all_spectra;
MSSpectrum empty_result = SpectrumAddition::addUpSpectra(all_spectra, 0.1, false);
TEST_EQUAL(empty_result.empty(), true);
all_spectra.clear();
all_spectra.push_back( MSSpectrum() );
all_spectra.push_back( MSSpectrum() );
std::cout << " to do here " << std::endl;
MSSpectrum empty2 = SpectrumAddition::addUpSpectra(all_spectra, 0.1, false);
TEST_EQUAL(empty2.size(), 0);
all_spectra.clear();
all_spectra.push_back(s1);
all_spectra.push_back(s2);
MSSpectrum result = SpectrumAddition::addUpSpectra(all_spectra, 0.1, false);
TEST_EQUAL(result.size(), 25);
MSSpectrum result_filtered = SpectrumAddition::addUpSpectra(all_spectra, 0.1, true);
TEST_EQUAL(result_filtered.size(), 9);
TEST_REAL_SIMILAR(result_filtered[0].getMZ(), 100.0);
TEST_REAL_SIMILAR(result_filtered[0].getIntensity(), 2);
TEST_REAL_SIMILAR(result_filtered[3].getMZ(), 101.9);
TEST_REAL_SIMILAR(result_filtered[3].getIntensity(), 3 + 5/2.0); // 3 @ 101.9 and 5 @ 101.95
// automatic spacing should be the min distance found in the data in each
// spectrum individually, i.e. it should not decrease the resolution
result_filtered = SpectrumAddition::addUpSpectra(all_spectra, 0.01, true);
MSSpectrum result_filtered_auto = SpectrumAddition::addUpSpectra(all_spectra, -1, true);
// this has some numerical stability issues
// TEST_EQUAL(result_filtered, result_filtered_auto)
TEST_EQUAL(result_filtered.size(), 16);
TEST_REAL_SIMILAR(result_filtered[0].getMZ(), 100.0);
TEST_REAL_SIMILAR(result_filtered[0].getIntensity(), 2);
TEST_REAL_SIMILAR(result_filtered[3].getMZ(), 101.9);
TEST_REAL_SIMILAR(result_filtered[3].getIntensity(), 3);
TEST_EQUAL(result_filtered_auto.size(), 28);
TEST_REAL_SIMILAR(result_filtered[0].getMZ(), 100.0);
TEST_REAL_SIMILAR(result_filtered[0].getIntensity(), 2);
TEST_REAL_SIMILAR(result_filtered[3].getMZ(), 101.9);
TEST_REAL_SIMILAR(result_filtered[3].getIntensity(), 3);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/TraceFitter_test.cpp | .cpp | 5,900 | 214 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Stephan Aiche$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FEATUREFINDER/TraceFitter.h>
///////////////////////////
#include <OpenMS/KERNEL/Peak1D.h>
using namespace OpenMS;
using namespace std;
// dummy implementation for the test
class DerivedTraceFitter
: public TraceFitter
{
public:
void fit(FeatureFinderAlgorithmPickedHelperStructs::MassTraces&) override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
double getLowerRTBound() const override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
double getUpperRTBound() const override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
double getHeight() const override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
double getCenter() const override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
double getFWHM() const override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
double getValue(double /* rt */) const override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
bool checkMinimalRTSpan(const std::pair<double, double>&, const double) override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
bool checkMaximalRTSpan(const double) override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
double getArea() override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
String getGnuplotFormula(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace&, const char, const double, const double) override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
void getOptimizedParameters_(const std::vector<double>&) override
{
throw Exception::NotImplemented(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION);
}
};
START_TEST(TraceFitter, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
TraceFitter* ptr = nullptr;
TraceFitter* nullPointer = nullptr;
START_SECTION(TraceFitter())
{
ptr = new DerivedTraceFitter();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~TraceFitter())
{
delete ptr;
}
END_SECTION
START_SECTION((TraceFitter(const TraceFitter& source)))
{
NOT_TESTABLE
// has no public members to check if copy has same proberties
}
END_SECTION
START_SECTION((virtual TraceFitter& operator=(const TraceFitter& source)))
{
NOT_TESTABLE
// has no public members to check if copy has same proberties
}
END_SECTION
DerivedTraceFitter trace_fitter;
START_SECTION((virtual void fit(FeatureFinderAlgorithmPickedHelperStructs::MassTraces& traces)=0))
{
FeatureFinderAlgorithmPickedHelperStructs::MassTraces m;
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.fit(m))
}
END_SECTION
START_SECTION((virtual double getLowerRTBound() const ))
{
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.getLowerRTBound())
}
END_SECTION
START_SECTION((virtual double getUpperRTBound() const ))
{
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.getUpperRTBound())
}
END_SECTION
START_SECTION((virtual double getHeight() const ))
{
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.getHeight())
}
END_SECTION
START_SECTION((virtual double getCenter() const ))
{
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.getCenter())
}
END_SECTION
START_SECTION((virtual double getValue(double rt) const ))
{
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.getValue(0.0))
}
END_SECTION
START_SECTION((double computeTheoretical(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace& trace, Size k)))
{
FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt;
Peak1D p;
mt.peaks.push_back(make_pair(1.0, &p));
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.computeTheoretical(mt, 0))
}
END_SECTION
START_SECTION((virtual bool checkMinimalRTSpan(const std::pair<double, double>& rt_bounds, const double min_rt_span)=0))
{
std::pair<double, double> p;
double x = 0.0;
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.checkMinimalRTSpan(p,x))
}
END_SECTION
START_SECTION((virtual bool checkMaximalRTSpan(const double max_rt_span)=0))
{
double x = 0.0;
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.checkMaximalRTSpan(x))
}
END_SECTION
START_SECTION((virtual double getArea()))
{
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.getArea())
}
END_SECTION
START_SECTION((virtual String getGnuplotFormula(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace& trace, const char function_name, const double baseline, const double rt_shift)=0))
{
FeatureFinderAlgorithmPickedHelperStructs::MassTrace mt;
double shift = 0.0;
double baseline = 0.0;
char f = 'f';
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.getGnuplotFormula(mt, f, baseline, shift))
}
END_SECTION
START_SECTION((virtual double getFWHM() const))
{
TEST_EXCEPTION(Exception::NotImplemented, trace_fitter.getFWHM())
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ConsensusMapNormalizerAlgorithmQuantile_test.cpp | .cpp | 1,900 | 75 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: $
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
///////////////////////////
#include <OpenMS/ANALYSIS/MAPMATCHING/ConsensusMapNormalizerAlgorithmQuantile.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(ConsensusMapNormalizerAlgorithmQuantile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
ConsensusMapNormalizerAlgorithmQuantile* ptr = nullptr;
ConsensusMapNormalizerAlgorithmQuantile* null_ptr = nullptr;
START_SECTION(ConsensusMapNormalizerAlgorithmQuantile())
{
ptr = new ConsensusMapNormalizerAlgorithmQuantile();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~ConsensusMapNormalizerAlgorithmQuantile())
{
delete ptr;
}
END_SECTION
START_SECTION((virtual ~ConsensusMapNormalizerAlgorithmQuantile()))
{
// TODO
}
END_SECTION
START_SECTION((static void normalizeMaps(ConsensusMap &map)))
{
// TODO
}
END_SECTION
START_SECTION((static void resample(const std::vector< double > &data_in, std::vector< double > &data_out, UInt n_resampling_points)))
{
// TODO
}
END_SECTION
START_SECTION((static void extractIntensityVectors(const ConsensusMap &map, std::vector< std::vector< double > > &out_intensities)))
{
// TODO
}
END_SECTION
START_SECTION((static void setNormalizedIntensityValues(const std::vector< std::vector< double > > &feature_ints, ConsensusMap &map)))
{
// TODO
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MobilityPeak2D_test.cpp | .cpp | 18,494 | 618 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/KERNEL/MobilityPeak2D.h>
#include <unordered_set>
#include <unordered_map>
///////////////////////////
START_TEST(MobilityPeak2D<D>, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
static_assert(std::is_trivially_destructible<MobilityPeak2D> {});
// static_assert(std::is_trivially_default_constructible<MobilityPeak2D> {});
static_assert(std::is_trivially_copy_constructible<MobilityPeak2D> {});
static_assert(std::is_trivially_copy_assignable<MobilityPeak2D> {});
static_assert(std::is_trivially_move_constructible<MobilityPeak2D> {});
static_assert(std::is_nothrow_move_constructible<MobilityPeak2D> {});
static_assert(std::is_trivially_move_assignable<MobilityPeak2D> {});
MobilityPeak2D* d10_ptr = nullptr;
MobilityPeak2D* d10_nullPointer = nullptr;
START_SECTION((MobilityPeak2D()))
{
d10_ptr = new MobilityPeak2D;
TEST_NOT_EQUAL(d10_ptr, d10_nullPointer)
}
END_SECTION
START_SECTION((~MobilityPeak2D()))
{
delete d10_ptr;
}
END_SECTION
START_SECTION((MobilityPeak2D(const MobilityPeak2D& p)))
{
MobilityPeak2D::PositionType pos;
pos[0] = 21.21;
pos[1] = 22.22;
MobilityPeak2D p;
p.setIntensity(123.456f);
p.setPosition(pos);
MobilityPeak2D::PositionType pos2;
MobilityPeak2D::IntensityType i2;
MobilityPeak2D copy_of_p(p);
i2 = copy_of_p.getIntensity();
pos2 = copy_of_p.getPosition();
TEST_REAL_SIMILAR(i2, 123.456)
TEST_REAL_SIMILAR(pos2[0], 21.21)
TEST_REAL_SIMILAR(pos2[1], 22.22)
}
END_SECTION
START_SECTION((MobilityPeak2D(MobilityPeak2D && rhs)))
{
// Ensure that MobilityPeak2D has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(MobilityPeak2D(std::declval<MobilityPeak2D&&>())), true)
MobilityPeak2D::PositionType pos;
pos[0] = 21.21;
pos[1] = 22.22;
MobilityPeak2D p;
p.setIntensity(123.456f);
p.setPosition(pos);
MobilityPeak2D::PositionType pos2;
MobilityPeak2D::IntensityType i2;
MobilityPeak2D copy_of_p(std::move(p));
i2 = copy_of_p.getIntensity();
pos2 = copy_of_p.getPosition();
TEST_REAL_SIMILAR(i2, 123.456)
TEST_REAL_SIMILAR(pos2[0], 21.21)
TEST_REAL_SIMILAR(pos2[1], 22.22)
}
END_SECTION
START_SECTION((explicit MobilityPeak2D(const PositionType& pos, const IntensityType in)))
{
MobilityPeak2D p(MobilityPeak2D::PositionType(21.21, 22.22), 123.456f);
MobilityPeak2D copy_of_p(p);
TEST_REAL_SIMILAR(copy_of_p.getIntensity(), 123.456)
TEST_REAL_SIMILAR(copy_of_p.getPosition()[0], 21.21)
TEST_REAL_SIMILAR(copy_of_p.getPosition()[1], 22.22)
}
END_SECTION
START_SECTION((MobilityPeak2D & operator=(const MobilityPeak2D& rhs)))
MobilityPeak2D::PositionType pos;
pos[0] = 21.21;
pos[1] = 22.22;
MobilityPeak2D p;
p.setIntensity(123.456f);
p.setPosition(pos);
MobilityPeak2D::PositionType pos2;
MobilityPeak2D::IntensityType i2;
MobilityPeak2D copy_of_p;
copy_of_p = p;
i2 = copy_of_p.getIntensity();
pos2 = copy_of_p.getPosition();
TEST_REAL_SIMILAR(i2, 123.456)
TEST_REAL_SIMILAR(pos2[0], 21.21)
TEST_REAL_SIMILAR(pos2[1], 22.22)
END_SECTION
START_SECTION((IntensityType getIntensity() const))
TEST_REAL_SIMILAR(MobilityPeak2D().getIntensity(), 0.0)
END_SECTION
START_SECTION((PositionType const& getPosition() const))
const MobilityPeak2D p {};
TEST_REAL_SIMILAR(p.getPosition()[0], 0.0)
TEST_REAL_SIMILAR(p.getPosition()[1], 0.0)
END_SECTION
START_SECTION((CoordinateType getMobility() const))
TEST_REAL_SIMILAR(MobilityPeak2D().getMobility(), 0.0)
END_SECTION
START_SECTION((CoordinateType getMZ() const))
TEST_REAL_SIMILAR(MobilityPeak2D().getMZ(), 0.0)
END_SECTION
START_SECTION((void setMobility(CoordinateTypecoordinate)))
MobilityPeak2D p0;
p0.setMobility(12345.0);
TEST_REAL_SIMILAR(p0.getMobility(), 12345.0)
END_SECTION
START_SECTION((void setMZ(CoordinateTypecoordinate)))
MobilityPeak2D p0;
p0.setMZ(12345.0);
TEST_REAL_SIMILAR(p0.getMZ(), 12345.0)
END_SECTION
START_SECTION((void setPosition(const PositionType& position)))
DPosition<2> p;
p[0] = 876;
p[1] = 12345.0;
MobilityPeak2D p1;
p1.setPosition(p);
TEST_REAL_SIMILAR(p1.getPosition()[0], 876)
TEST_REAL_SIMILAR(p1.getPosition()[1], 12345.0)
END_SECTION
START_SECTION((PositionType & getPosition()))
DPosition<2> p;
p[0] = 876;
p[1] = 12345.0;
MobilityPeak2D p1;
p1.getPosition() = p;
TEST_REAL_SIMILAR(p1.getPosition()[0], 876)
TEST_REAL_SIMILAR(p1.getPosition()[1], 12345.0)
END_SECTION
START_SECTION((void setIntensity(IntensityType intensity)))
MobilityPeak2D p;
p.setIntensity(17.8f);
TEST_REAL_SIMILAR(p.getIntensity(), 17.8)
END_SECTION
START_SECTION((bool operator==(const MobilityPeak2D& rhs) const))
MobilityPeak2D p1;
MobilityPeak2D p2(p1);
TEST_TRUE(p1 == p2)
p1.setIntensity(5.0f);
TEST_EQUAL(p1 == p2, false)
p2.setIntensity(5.0f);
TEST_TRUE(p1 == p2)
p1.getPosition()[0] = 5;
TEST_EQUAL(p1 == p2, false)
p2.getPosition()[0] = 5;
TEST_TRUE(p1 == p2)
END_SECTION
START_SECTION((bool operator!=(const MobilityPeak2D& rhs) const))
MobilityPeak2D p1;
MobilityPeak2D p2(p1);
TEST_EQUAL(p1 != p2, false)
p1.setIntensity(5.0f);
TEST_FALSE(p1 == p2)
p2.setIntensity(5.0f);
TEST_EQUAL(p1 != p2, false)
p1.getPosition()[0] = 5;
TEST_FALSE(p1 == p2)
p2.getPosition()[0] = 5;
TEST_EQUAL(p1 != p2, false)
END_SECTION
START_SECTION(([EXTRA] enum value MobilityPeak2D::IM))
{
TEST_EQUAL(MobilityPeak2D::IM, 0);
}
END_SECTION
START_SECTION(([EXTRA] enum value MobilityPeak2D::MZ))
{
TEST_EQUAL(MobilityPeak2D::MZ, 1);
}
END_SECTION
START_SECTION(([EXTRA] enum value MobilityPeak2D::DIMENSION))
{
TEST_EQUAL(MobilityPeak2D::DIMENSION, 2);
}
END_SECTION
START_SECTION(([EXTRA] enum MobilityPeak2D::DimensionId))
{
MobilityPeak2D::DimensionDescription dim;
dim = MobilityPeak2D::IM;
TEST_EQUAL(dim, MobilityPeak2D::IM);
dim = MobilityPeak2D::MZ;
TEST_EQUAL(dim, MobilityPeak2D::MZ);
dim = MobilityPeak2D::DIMENSION;
TEST_EQUAL(dim, MobilityPeak2D::DIMENSION);
}
END_SECTION
START_SECTION((static char const* shortDimensionName(UInt const dim)))
{
TEST_STRING_EQUAL(MobilityPeak2D::shortDimensionName(MobilityPeak2D::IM), "IM");
TEST_STRING_EQUAL(MobilityPeak2D::shortDimensionName(MobilityPeak2D::MZ), "MZ");
}
END_SECTION
START_SECTION((static char const* shortDimensionNameIM()))
{
TEST_STRING_EQUAL(MobilityPeak2D::shortDimensionNameIM(), "IM");
}
END_SECTION
START_SECTION((static char const* shortDimensionNameMZ()))
{
TEST_STRING_EQUAL(MobilityPeak2D::shortDimensionNameMZ(), "MZ");
}
END_SECTION
START_SECTION((static char const* fullDimensionName(UInt const dim)))
{
TEST_STRING_EQUAL(MobilityPeak2D::fullDimensionName(MobilityPeak2D::IM), "ion mobility");
TEST_STRING_EQUAL(MobilityPeak2D::fullDimensionName(MobilityPeak2D::MZ), "mass-to-charge");
}
END_SECTION
START_SECTION((static char const* fullDimensionNameIM()))
{
TEST_STRING_EQUAL(MobilityPeak2D::fullDimensionNameIM(), "ion mobility");
}
END_SECTION
START_SECTION((static char const* fullDimensionNameMZ()))
{
TEST_STRING_EQUAL(MobilityPeak2D::fullDimensionNameMZ(), "mass-to-charge");
}
END_SECTION
START_SECTION((static char const* shortDimensionUnit(UInt const dim)))
{
TEST_STRING_EQUAL(MobilityPeak2D::shortDimensionUnit(MobilityPeak2D::IM), "?");
TEST_STRING_EQUAL(MobilityPeak2D::shortDimensionUnit(MobilityPeak2D::MZ), "Th");
}
END_SECTION
START_SECTION((static char const* shortDimensionUnitIM()))
{
TEST_STRING_EQUAL(MobilityPeak2D::shortDimensionUnitIM(), "?");
}
END_SECTION
START_SECTION((static char const* shortDimensionUnitMZ()))
{
TEST_STRING_EQUAL(MobilityPeak2D::shortDimensionUnitMZ(), "Th");
}
END_SECTION
START_SECTION((static char const* fullDimensionUnit(UInt const dim)))
{
TEST_STRING_EQUAL(MobilityPeak2D::fullDimensionUnit(MobilityPeak2D::IM), "?");
TEST_STRING_EQUAL(MobilityPeak2D::fullDimensionUnit(MobilityPeak2D::MZ), "Thomson");
}
END_SECTION
START_SECTION((static char const* fullDimensionUnitIM()))
{
TEST_STRING_EQUAL(MobilityPeak2D::fullDimensionUnitIM(), "?");
}
END_SECTION
START_SECTION((static char const* fullDimensionUnitMZ()))
{
TEST_STRING_EQUAL(MobilityPeak2D::fullDimensionUnitMZ(), "Thomson");
}
END_SECTION
/////////////////////////////////////////////////////////////
// Nested Stuff
/////////////////////////////////////////////////////////////
MobilityPeak2D p1;
p1.setIntensity(10.0);
p1.setMZ(10.0);
p1.setMobility(10.0);
MobilityPeak2D p2;
p2.setIntensity(12.0);
p2.setMZ(12.0);
p2.setMobility(12.0);
// IntensityLess
START_SECTION(([MobilityPeak2D::IntensityLess] bool operator()(const MobilityPeak2D& left, const MobilityPeak2D& right) const))
std::vector<MobilityPeak2D> v;
MobilityPeak2D p;
p.setIntensity(2.5f);
v.push_back(p);
p.setIntensity(3.5f);
v.push_back(p);
p.setIntensity(1.5f);
v.push_back(p);
std::sort(v.begin(), v.end(), MobilityPeak2D::IntensityLess());
TEST_REAL_SIMILAR(v[0].getIntensity(), 1.5)
TEST_REAL_SIMILAR(v[1].getIntensity(), 2.5)
TEST_REAL_SIMILAR(v[2].getIntensity(), 3.5)
v[0] = v[2];
v[2] = p;
std::sort(v.begin(), v.end(), MobilityPeak2D::IntensityLess());
TEST_REAL_SIMILAR(v[0].getIntensity(), 1.5)
TEST_REAL_SIMILAR(v[1].getIntensity(), 2.5)
TEST_REAL_SIMILAR(v[2].getIntensity(), 3.5)
//
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p1, p2), true)
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p2, p1), false)
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p2, p2), false)
END_SECTION
START_SECTION(([MobilityPeak2D::IntensityLess] bool operator()(const MobilityPeak2D& left, IntensityType right) const))
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p1, p2.getIntensity()), true)
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p2, p1.getIntensity()), false)
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p2, p2.getIntensity()), false)
END_SECTION
START_SECTION(([MobilityPeak2D::IntensityLess] bool operator()(IntensityType left, const MobilityPeak2D& right) const))
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p1.getIntensity(), p2), true)
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p2.getIntensity(), p1), false)
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p2.getIntensity(), p2), false)
END_SECTION
START_SECTION(([MobilityPeak2D::IntensityLess] bool operator()(IntensityType left, IntensityType right) const))
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p1, p2.getIntensity()), true)
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p2, p1.getIntensity()), false)
TEST_EQUAL(MobilityPeak2D::IntensityLess()(p2, p2.getIntensity()), false)
END_SECTION
// IMLess
START_SECTION(([MobilityPeak2D::IMLess] bool operator()(const MobilityPeak2D& left, const MobilityPeak2D& right) const))
std::vector<MobilityPeak2D> v;
MobilityPeak2D p;
p.getPosition()[0] = 3.0;
p.getPosition()[1] = 2.5;
v.push_back(p);
p.getPosition()[0] = 2.0;
p.getPosition()[1] = 3.5;
v.push_back(p);
p.getPosition()[0] = 1.0;
p.getPosition()[1] = 1.5;
v.push_back(p);
std::sort(v.begin(), v.end(), MobilityPeak2D::IMLess());
TEST_REAL_SIMILAR(v[0].getPosition()[0], 1.0)
TEST_REAL_SIMILAR(v[1].getPosition()[0], 2.0)
TEST_REAL_SIMILAR(v[2].getPosition()[0], 3.0)
TEST_EQUAL(MobilityPeak2D::IMLess()(p1, p2), true)
TEST_EQUAL(MobilityPeak2D::IMLess()(p2, p1), false)
TEST_EQUAL(MobilityPeak2D::IMLess()(p2, p2), false)
END_SECTION
START_SECTION(([MobilityPeak2D::IMLess] bool operator()(const MobilityPeak2D& left, CoordinateType right) const))
TEST_EQUAL(MobilityPeak2D::IMLess()(p1, p2.getMobility()), true)
TEST_EQUAL(MobilityPeak2D::IMLess()(p2, p1.getMobility()), false)
TEST_EQUAL(MobilityPeak2D::IMLess()(p2, p2.getMobility()), false)
END_SECTION
START_SECTION(([MobilityPeak2D::IMLess] bool operator()(CoordinateType left, const MobilityPeak2D& right) const))
TEST_EQUAL(MobilityPeak2D::IMLess()(p1.getMobility(), p2), true)
TEST_EQUAL(MobilityPeak2D::IMLess()(p2.getMobility(), p1), false)
TEST_EQUAL(MobilityPeak2D::IMLess()(p2.getMobility(), p2), false)
END_SECTION
START_SECTION(([MobilityPeak2D::IMLess] bool operator()(CoordinateType left, CoordinateType right) const))
TEST_EQUAL(MobilityPeak2D::IMLess()(p1.getMobility(), p2.getMobility()), true)
TEST_EQUAL(MobilityPeak2D::IMLess()(p2.getMobility(), p1.getMobility()), false)
TEST_EQUAL(MobilityPeak2D::IMLess()(p2.getMobility(), p2.getMobility()), false)
END_SECTION
// PositionLess
START_SECTION(([MobilityPeak2D::PositionLess] bool operator()(const MobilityPeak2D& left, const MobilityPeak2D& right) const))
std::vector<MobilityPeak2D> v;
MobilityPeak2D p;
p.getPosition()[0] = 3.0;
p.getPosition()[1] = 2.5;
v.push_back(p);
p.getPosition()[0] = 2.0;
p.getPosition()[1] = 3.5;
v.push_back(p);
p.getPosition()[0] = 1.0;
p.getPosition()[1] = 1.5;
v.push_back(p);
std::sort(v.begin(), v.end(), MobilityPeak2D::PositionLess());
TEST_REAL_SIMILAR(v[0].getPosition()[0], 1.0)
TEST_REAL_SIMILAR(v[1].getPosition()[0], 2.0)
TEST_REAL_SIMILAR(v[2].getPosition()[0], 3.0)
TEST_REAL_SIMILAR(v[0].getPosition()[1], 1.5)
TEST_REAL_SIMILAR(v[1].getPosition()[1], 3.5)
TEST_REAL_SIMILAR(v[2].getPosition()[1], 2.5)
std::sort(v.begin(), v.end(), MobilityPeak2D::MZLess());
TEST_REAL_SIMILAR(v[0].getPosition()[1], 1.5)
TEST_REAL_SIMILAR(v[1].getPosition()[1], 2.5)
TEST_REAL_SIMILAR(v[2].getPosition()[1], 3.5)
TEST_REAL_SIMILAR(v[0].getPosition()[0], 1.0)
TEST_REAL_SIMILAR(v[1].getPosition()[0], 3.0)
TEST_REAL_SIMILAR(v[2].getPosition()[0], 2.0)
//
TEST_EQUAL(MobilityPeak2D::PositionLess()(p1, p2), true)
TEST_EQUAL(MobilityPeak2D::PositionLess()(p2, p1), false)
TEST_EQUAL(MobilityPeak2D::PositionLess()(p2, p2), false)
END_SECTION
START_SECTION(([MobilityPeak2D::PositionLess] bool operator()(const MobilityPeak2D& left, const PositionType& right) const))
TEST_EQUAL(MobilityPeak2D::PositionLess()(p1, p2.getPosition()), true)
TEST_EQUAL(MobilityPeak2D::PositionLess()(p2, p1.getPosition()), false)
TEST_EQUAL(MobilityPeak2D::PositionLess()(p2, p2.getPosition()), false)
END_SECTION
START_SECTION(([MobilityPeak2D::PositionLess] bool operator()(const PositionType& left, const MobilityPeak2D& right) const))
TEST_EQUAL(MobilityPeak2D::PositionLess()(p1.getPosition(), p2), true)
TEST_EQUAL(MobilityPeak2D::PositionLess()(p2.getPosition(), p1), false)
TEST_EQUAL(MobilityPeak2D::PositionLess()(p2.getPosition(), p2), false)
END_SECTION
START_SECTION(([MobilityPeak2D::PositionLess] bool operator()(const PositionType& left, const PositionType& right) const))
TEST_EQUAL(MobilityPeak2D::PositionLess()(p1.getPosition(), p2.getPosition()), true)
TEST_EQUAL(MobilityPeak2D::PositionLess()(p2.getPosition(), p1.getPosition()), false)
TEST_EQUAL(MobilityPeak2D::PositionLess()(p2.getPosition(), p2.getPosition()), false)
END_SECTION
// MZLess
START_SECTION(([MobilityPeak2D::MZLess] bool operator()(const MobilityPeak2D& left, const MobilityPeak2D& right) const))
std::vector<MobilityPeak2D> v;
MobilityPeak2D p;
p.getPosition()[0] = 3.0;
p.getPosition()[1] = 2.5;
v.push_back(p);
p.getPosition()[0] = 2.0;
p.getPosition()[1] = 3.5;
v.push_back(p);
p.getPosition()[0] = 1.0;
p.getPosition()[1] = 1.5;
v.push_back(p);
std::sort(v.begin(), v.end(), MobilityPeak2D::MZLess());
TEST_REAL_SIMILAR(v[0].getPosition()[1], 1.5)
TEST_REAL_SIMILAR(v[1].getPosition()[1], 2.5)
TEST_REAL_SIMILAR(v[2].getPosition()[1], 3.5)
TEST_EQUAL(MobilityPeak2D::MZLess()(p1, p2), true)
TEST_EQUAL(MobilityPeak2D::MZLess()(p2, p1), false)
TEST_EQUAL(MobilityPeak2D::MZLess()(p2, p2), false)
END_SECTION
START_SECTION(([MobilityPeak2D::MZLess] bool operator()(const MobilityPeak2D& left, CoordinateType right) const))
TEST_EQUAL(MobilityPeak2D::MZLess()(p1, p2.getMZ()), true)
TEST_EQUAL(MobilityPeak2D::MZLess()(p2, p1.getMZ()), false)
TEST_EQUAL(MobilityPeak2D::MZLess()(p2, p2.getMZ()), false)
END_SECTION
START_SECTION(([MobilityPeak2D::MZLess] bool operator()(CoordinateType left, const MobilityPeak2D& right) const))
TEST_EQUAL(MobilityPeak2D::MZLess()(p1.getMZ(), p2), true)
TEST_EQUAL(MobilityPeak2D::MZLess()(p2.getMZ(), p1), false)
TEST_EQUAL(MobilityPeak2D::MZLess()(p2.getMZ(), p2), false)
END_SECTION
START_SECTION(([MobilityPeak2D::MZLess] bool operator()(CoordinateType left, CoordinateType right) const))
TEST_EQUAL(MobilityPeak2D::MZLess()(p1.getMZ(), p2.getMZ()), true)
TEST_EQUAL(MobilityPeak2D::MZLess()(p2.getMZ(), p1.getMZ()), false)
TEST_EQUAL(MobilityPeak2D::MZLess()(p2.getMZ(), p2.getMZ()), false)
END_SECTION
/////////////////////////////////////////////////////////////
// Hash function tests
/////////////////////////////////////////////////////////////
START_SECTION(([EXTRA] std::hash<MobilityPeak2D>))
{
// Test that equal peaks have equal hashes
MobilityPeak2D mp1, mp2;
mp1.setMobility(1.5);
mp1.setMZ(500.5);
mp1.setIntensity(1000.0f);
mp2.setMobility(1.5);
mp2.setMZ(500.5);
mp2.setIntensity(1000.0f);
std::hash<MobilityPeak2D> hasher;
TEST_EQUAL(hasher(mp1), hasher(mp2))
// Test that hash changes when values change
MobilityPeak2D mp3;
mp3.setMobility(2.5);
mp3.setMZ(500.5);
mp3.setIntensity(1000.0f);
TEST_NOT_EQUAL(hasher(mp1), hasher(mp3))
// Test use in unordered_set
std::unordered_set<MobilityPeak2D> peak_set;
peak_set.insert(mp1);
TEST_EQUAL(peak_set.size(), 1)
peak_set.insert(mp2); // same as mp1
TEST_EQUAL(peak_set.size(), 1) // should not increase
peak_set.insert(mp3);
TEST_EQUAL(peak_set.size(), 2)
// Test use in unordered_map
std::unordered_map<MobilityPeak2D, int> peak_map;
peak_map[mp1] = 42;
TEST_EQUAL(peak_map[mp1], 42)
TEST_EQUAL(peak_map[mp2], 42) // mp2 == mp1, should get same value
peak_map[mp3] = 99;
TEST_EQUAL(peak_map[mp3], 99)
TEST_EQUAL(peak_map.size(), 2)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Software_test.cpp | .cpp | 3,957 | 157 | // 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/Software.h>
///////////////////////////
#include <unordered_set>
#include <unordered_map>
using namespace OpenMS;
using namespace std;
START_TEST(Software, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
Software* ptr = nullptr;
Software* nullPointer = nullptr;
START_SECTION(Software())
ptr = new Software();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~Software())
delete ptr;
END_SECTION
START_SECTION(const String& getName() const)
Software tmp;
TEST_EQUAL(tmp.getName(),"");
END_SECTION
START_SECTION(void setName(const String& name))
Software tmp;
tmp.setName("name");
TEST_EQUAL(tmp.getName(),"name");
END_SECTION
START_SECTION(const String& getVersion() const)
Software tmp;
TEST_EQUAL(tmp.getVersion(),"");
END_SECTION
START_SECTION(void setVersion(const String& version))
Software tmp;
tmp.setVersion("0.54");
TEST_EQUAL(tmp.getVersion(),"0.54");
END_SECTION
START_SECTION(Software(const Software& source))
Software tmp;
tmp.setVersion("0.54");
tmp.setName("name");
Software tmp2(tmp);
TEST_EQUAL(tmp2.getVersion(),"0.54");
TEST_EQUAL(tmp2.getName(),"name");
END_SECTION
START_SECTION(Software& operator= (const Software& source))
Software tmp;
tmp.setVersion("0.54");
tmp.setName("name");
Software tmp2;
tmp2 = tmp;
TEST_EQUAL(tmp2.getVersion(),"0.54");
TEST_EQUAL(tmp2.getName(),"name");
tmp2 = Software();
TEST_EQUAL(tmp2.getVersion(),"");
TEST_EQUAL(tmp2.getName(),"");
END_SECTION
START_SECTION(bool operator== (const Software& rhs) const)
Software edit, empty;
TEST_EQUAL(edit==empty,true);
edit = empty;
edit.setVersion("0.54");
TEST_EQUAL(edit==empty,false);
edit = empty;
edit.setName("name");
TEST_EQUAL(edit==empty,false);
END_SECTION
START_SECTION(bool operator!= (const Software& rhs) const)
Software edit, empty;
TEST_EQUAL(edit!=empty,false);
edit = empty;
edit.setVersion("0.54");
TEST_EQUAL(edit!=empty,true);
edit = empty;
edit.setName("name");
TEST_EQUAL(edit!=empty,true);
END_SECTION
START_SECTION(([EXTRA] std::hash<Software>))
{
// Test that equal objects have equal hashes
Software s1("TestSoftware", "1.0");
Software s2("TestSoftware", "1.0");
TEST_EQUAL(s1 == s2, true)
TEST_EQUAL(std::hash<Software>{}(s1), std::hash<Software>{}(s2))
// Test that different names produce different hashes
Software s3("OtherSoftware", "1.0");
TEST_NOT_EQUAL(std::hash<Software>{}(s1), std::hash<Software>{}(s3))
// Test that different versions produce different hashes
Software s4("TestSoftware", "2.0");
TEST_NOT_EQUAL(std::hash<Software>{}(s1), std::hash<Software>{}(s4))
// Test use in unordered_set
std::unordered_set<Software> software_set;
software_set.insert(s1);
software_set.insert(s2); // duplicate, should not increase size
software_set.insert(s3);
TEST_EQUAL(software_set.size(), 2)
TEST_EQUAL(software_set.count(s1), 1)
TEST_EQUAL(software_set.count(s3), 1)
// Test use in unordered_map
std::unordered_map<Software, std::string> software_map;
software_map[s1] = "value1";
TEST_EQUAL(software_map[s2], "value1") // s2 equals s1, should retrieve same value
software_map[s3] = "value3";
TEST_EQUAL(software_map.size(), 2)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/String_test.cpp | .cpp | 31,919 | 1,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 $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/DataValue.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <iostream>
#include <iomanip>
#include <random>
#include <vector>
#include <QtCore/QString>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(String, "$Id$")
/////////////////////////////////////////////////////////////
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wshadow"
#endif
String* s_ptr = nullptr;
String* s_nullPointer = nullptr;
START_SECTION((String()))
s_ptr = new String;
TEST_NOT_EQUAL(s_ptr, s_nullPointer)
END_SECTION
START_SECTION(([EXTRA] ~String()))
delete s_ptr;
END_SECTION
START_SECTION((String(const QString &s)))
QString qs("bla");
String s(qs);
TEST_EQUAL(s=="bla",true)
END_SECTION
START_SECTION((QString toQString() const))
QString qs("bla");
String s("bla");
TEST_EQUAL(s.toQString()==qs,true)
END_SECTION
START_SECTION((String(const char* s, SizeType length)))
String s("abcdedfg",5);
TEST_EQUAL(s,"abcde")
String s2("abcdedfg",0);
TEST_EQUAL(s2,"")
String s3("abcdedfg",8);
TEST_EQUAL(s3,"abcdedfg")
// This function does *not* check for null bytes as these may be part of a
// valid string! If you provide a length that is inaccurate, you are to blame
// (we do not test this since we would cause undefined behavior).
// String s4("abcdedfg", 15);
// TEST_NOT_EQUAL(s4,"abcdedfg")
// Unicode test
// print(b"T\xc3\xbc\x62ingen".decode("utf8"))
// print(b"\xff\xfeT\x00\xfc\x00b\x00i\x00n\x00g\x00e\x00n\x00".decode("utf16"))
// print(b"T\xfc\x62ingen".decode("iso8859"))
char test_utf8[] = "T\xc3\xbc\x62ingen";
char test_utf16[] {'\xff','\xfe','T','\x00','\xfc','\x00','b','\x00','i','\x00','n','\x00','g','\x00','e','\x00','n','\x00'};
char test_iso8859[] = "T\xfc\x62ingen";
String s_utf8(test_utf8, 9);
String s_utf16(test_utf16, 18);
String s_iso8859(test_iso8859, 8);
TEST_EQUAL(s_utf16.size(), 18);
TEST_EQUAL(s_utf8.size(), 9);
TEST_EQUAL(s_iso8859.size(), 8);
TEST_EQUAL(s_iso8859[0], 'T')
TEST_EQUAL(s_iso8859[1], '\xfc') // single byte for u
TEST_EQUAL(s_iso8859[2], 'b')
TEST_EQUAL(s_utf8[0], 'T')
TEST_EQUAL(s_utf8[1], '\xc3')
TEST_EQUAL(s_utf8[2], '\xbc') // two bytes for u
TEST_EQUAL(s_utf8[3], 'b')
// Its very easy to produce nonsense with unicode (e.g. chop string in half
// in the middle of a character)
String nonsense(test_utf8, 2);
TEST_EQUAL(nonsense.size(), 2);
TEST_EQUAL(nonsense[1], '\xc3')
END_SECTION
START_SECTION((String(const std::string& s)))
String s(string("blablabla"));
TEST_EQUAL(s,"blablabla")
// Unicode test
// print(b"T\xc3\xbc\x62ingen".decode("utf8"))
// print(b"\xff\xfeT\x00\xfc\x00b\x00i\x00n\x00g\x00e\x00n\x00".decode("utf16"))
// print(b"T\xfc\x62ingen".decode("iso8859"))
char test_utf8[] = "T\xc3\xbc\x62ingen";
char test_utf16[] {'\xff','\xfe','T','\x00','\xfc','\x00','b','\x00','i','\x00','n','\x00','g','\x00','e','\x00','n','\x00'};
char test_iso8859[] = "T\xfc\x62ingen";
std::string std_s_utf8(test_utf8, 9);
std::string std_s_utf16(test_utf16, 18);
std::string std_s_iso8859(test_iso8859, 8);
String s_utf8(std_s_utf8);
String s_utf16(std_s_utf16);
String s_iso8859(std_s_iso8859);
TEST_EQUAL(s_utf16.size(), 18);
TEST_EQUAL(s_utf8.size(), 9);
TEST_EQUAL(s_iso8859.size(), 8);
TEST_EQUAL(s_iso8859[0], 'T')
TEST_EQUAL(s_iso8859[1], '\xfc') // single byte for u
TEST_EQUAL(s_iso8859[2], 'b')
TEST_EQUAL(s_utf8[0], 'T')
TEST_EQUAL(s_utf8[1], '\xc3')
TEST_EQUAL(s_utf8[2], '\xbc') // two bytes for u
TEST_EQUAL(s_utf8[3], 'b')
END_SECTION
START_SECTION((String(const char* s)))
String s("blablabla");
TEST_EQUAL(s,"blablabla")
END_SECTION
START_SECTION((String(size_t len, char c)))
String s(17,'b');
TEST_EQUAL(s,"bbbbbbbbbbbbbbbbb")
END_SECTION
START_SECTION((String(const char c)))
String s('v');
TEST_EQUAL(s,"v")
END_SECTION
START_SECTION((String(int i)))
String s(int (-17));
TEST_EQUAL(s,"-17")
END_SECTION
START_SECTION((String(unsigned int i)))
String s((unsigned int) (17));
TEST_EQUAL(s,"17")
END_SECTION
START_SECTION((String(long int i)))
String s((long int)(-17));
TEST_EQUAL(s,"-17")
END_SECTION
START_SECTION((String(long unsigned int i)))
String s((long unsigned int)(17));
TEST_EQUAL(s,"17")
END_SECTION
START_SECTION((String(short int i)))
String s((short int)(-17));
TEST_EQUAL(s,"-17")
END_SECTION
START_SECTION((String(short unsigned int i)))
String s((short unsigned int)(17));
TEST_EQUAL(s,"17")
END_SECTION
START_SECTION((String(float f, bool full_precision = true)))
String s(17.0123456f);
TEST_EQUAL(s,"17.012346")
String s2(17.0123f, false);
TEST_EQUAL(s2, "17.012")
END_SECTION
START_SECTION((String(float f)))
float f = 50254.199219;
double d = f;
String s(f);
TEST_EQUAL(s,"5.02542e04")
String s2(d);
TEST_EQUAL(s2, "5.025419921875e04")
// test denormals
constexpr float denorm = std::numeric_limits<float>::min() / 10;
//assert(std::fpclassify(denorm) == FP_SUBNORMAL);
TEST_EQUAL(String(denorm, true), "1.175495e-39")
TEST_EQUAL(String(denorm, false), "1.175e-39")
// we need this special 'NaN' since the default 'nan' is not recognized by downstream tools
// such as any Java-based tool (e.g. KNIME) trying to parse our output files
constexpr float nan = std::numeric_limits<float>::quiet_NaN();
assert(std::isnan(nan));
TEST_EQUAL(String(nan, true), "NaN")
TEST_EQUAL(String(nan, false), "NaN")
END_SECTION
START_SECTION((String(double d, bool full_precision = true)))
String s(double(17.012345));
TEST_EQUAL(s,"17.012345")
String s2(double(17.012345), false);
TEST_EQUAL(s2, "17.012")
// test denormals
constexpr double denorm = std::numeric_limits<double>::min() / 10;
assert(std::fpclassify(denorm) == FP_SUBNORMAL);
TEST_EQUAL(String(denorm, true), "2.225073858507203e-309")
TEST_EQUAL(String(denorm, false), "2.225e-309")
// we need this special 'NaN' since the default 'nan' is not recognized by downstream tools
// such as any Java-based tool (e.g. KNIME) trying to parse our output files
constexpr double nan = std::numeric_limits<double>::quiet_NaN();
assert(std::isnan(nan));
TEST_EQUAL(String(nan, true), "NaN")
TEST_EQUAL(String(nan, false), "NaN")
END_SECTION
START_SECTION((String(long double ld, bool full_precision = true)))
String s(17.012345L); // suffix L indicates long double
TEST_EQUAL(s,"17.012345")
String s2(17.012345L, false); // suffix L indicates long double
TEST_EQUAL(s2, "17.012")
// test denormals
long double denorm = std::numeric_limits<long double>::min() / 10;
assert(std::fpclassify(denorm) == FP_SUBNORMAL);
// we cannot test `long double` since it's size is very platform dependent
// TEST_EQUAL(String(denorm, true), "9.999888671826829e-321")
//TEST_EQUAL(String(denorm, false), "1.0e-320")
// we need this special 'NaN' since the default 'nan' is not recognized by downstream tools
// such as any Java-based tool (e.g. KNIME) trying to parse our output files
constexpr long double nan = std::numeric_limits<long double>::quiet_NaN();
assert(std::isnan(nan));
TEST_EQUAL(String(nan, true), "NaN")
TEST_EQUAL(String(nan, false), "NaN")
END_SECTION
START_SECTION((String(const DataValue& d, bool full_precision = true)))
TEST_EQUAL(String(DataValue(17.012345)), "17.012345")
TEST_EQUAL(String(DataValue(17.012345), false), "17.012")
TEST_EQUAL(String(DataValue(DoubleList({17.012345, 2.0}))), "[17.012345, 2.0]")
TEST_EQUAL(String(DataValue(DoubleList({17.012345, 2.0})), false), "[17.012, 2.0]")
TEST_EQUAL(String(DataValue("bla")), "bla")
TEST_EQUAL(String(DataValue(4711)), "4711")
END_SECTION
START_SECTION((String(long long unsigned int i)))
String s((long long unsigned int)(12345678));
TEST_EQUAL(s,"12345678")
END_SECTION
START_SECTION((String(long long signed int i)))
String s((long long signed int)(-12345678));
TEST_EQUAL(s,"-12345678")
END_SECTION
START_SECTION((static String numberLength(double d, UInt n)))
TEST_EQUAL(String::numberLength(12345678.9123,11),"12345678.91")
TEST_EQUAL(String::numberLength(-12345678.9123,11),"-12345678.9")
TEST_EQUAL(String::numberLength(12345678.9123,10),"12345678.9")
TEST_EQUAL(String::numberLength(-12345678.9123,10),"-1234.5e04")
TEST_EQUAL(String::numberLength(12345678.9123,9),"1234.5e04")
TEST_EQUAL(String::numberLength(-12345678.9123,9),"-123.4e05")
END_SECTION
START_SECTION((static String number(double d, UInt n)))
TEST_EQUAL(String::number(123.1234,0),"123")
TEST_EQUAL(String::number(123.1234,1),"123.1")
TEST_EQUAL(String::number(123.1234,2),"123.12")
TEST_EQUAL(String::number(123.1234,3),"123.123")
TEST_EQUAL(String::number(123.1234,4),"123.1234")
TEST_EQUAL(String::number(123.1234,5),"123.12340")
TEST_EQUAL(String::number(0.0,5),"0.00000")
END_SECTION
START_SECTION((template<class InputIterator> String(InputIterator first, InputIterator last)))
String s("ABCDEFGHIJKLMNOP");
String::Iterator i = s.begin();
String::Iterator j = s.end();
String s2(i,j);
TEST_EQUAL(s,s2)
++i;++i;
--j;--j;
s2 = String(i,j);
TEST_EQUAL(s2,"CDEFGHIJKLMN")
//test cases where the begin is equal to the end
i = s.begin();
j = s.begin();
s2 = String(i,j);
TEST_EQUAL(s2,"")
TEST_EQUAL(s2.size(),0U)
i = s.end();
j = s.end();
s2 = String(i,j);
TEST_EQUAL(s2,"")
TEST_EQUAL(s2.size(),0U)
// Unicode test
// print(b"T\xc3\xbc\x62ingen".decode("utf8"))
// print(b"\xff\xfeT\x00\xfc\x00b\x00i\x00n\x00g\x00e\x00n\x00".decode("utf16"))
// print(b"T\xfc\x62ingen".decode("iso8859"))
char test_utf8[] = "T\xc3\xbc\x62ingen";
char test_utf16[] {'\xff','\xfe','T','\x00','\xfc','\x00','b','\x00','i','\x00','n','\x00','g','\x00','e','\x00','n','\x00'};
char test_iso8859[] = "T\xfc\x62ingen";
std::string std_s_utf8(test_utf8, 9);
std::string std_s_utf16(test_utf16, 18);
std::string std_s_iso8859(test_iso8859, 8);
String s_utf8(std_s_utf8.begin(), std_s_utf8.end());
String s_utf16(std_s_utf16.begin(), std_s_utf16.end());
String s_iso8859(std_s_iso8859.begin(), std_s_iso8859.end());
TEST_EQUAL(s_utf16.size(), 18);
TEST_EQUAL(s_utf8.size(), 9);
TEST_EQUAL(s_iso8859.size(), 8);
TEST_EQUAL(s_iso8859[0], 'T')
TEST_EQUAL(s_iso8859[1], '\xfc') // single byte for u
TEST_EQUAL(s_iso8859[2], 'b')
TEST_EQUAL(s_utf8[0], 'T')
TEST_EQUAL(s_utf8[1], '\xc3')
TEST_EQUAL(s_utf8[2], '\xbc') // two bytes for u
TEST_EQUAL(s_utf8[3], 'b')
// Its very easy to produce nonsense with unicode (e.g. chop string in half
// in the middle of a character)
String nonsense(std_s_utf8.begin(), std_s_utf8.begin() + 2);
TEST_EQUAL(nonsense.size(), 2);
TEST_EQUAL(nonsense[1], '\xc3')
END_SECTION
String s("ACDEFGHIKLMNPQRSTVWY");
START_SECTION((bool hasPrefix(const String& string) const))
TEST_EQUAL(s.hasPrefix(""), true);
TEST_EQUAL(s.hasPrefix("ACDEF"), true);
TEST_EQUAL(s.hasPrefix("ACDEFGHIKLMNPQRSTVWY"), true);
TEST_EQUAL(s.hasPrefix("ABCDEF"), false);
TEST_EQUAL(s.hasPrefix("ACDEFGHIKLMNPQRSTVWYACDEF"), false);
END_SECTION
START_SECTION((bool hasSuffix(const String& string) const))
TEST_EQUAL(s.hasSuffix(""), true);
TEST_EQUAL(s.hasSuffix("TVWY"), true);
TEST_EQUAL(s.hasSuffix("ACDEFGHIKLMNPQRSTVWY"), true);
TEST_EQUAL(s.hasSuffix("WXYZ"), false);
TEST_EQUAL(s.hasSuffix("ACDEFACDEFGHIKLMNPQRSTVWY"), false);
END_SECTION
START_SECTION((bool hasSubstring(const String& string) const))
TEST_EQUAL(s.hasSubstring(""), true);
TEST_EQUAL(s.hasSubstring("GHIKLM"), true);
TEST_EQUAL(s.hasSubstring("ACDEFGHIKLMNPQRSTVWY"), true);
TEST_EQUAL(s.hasSubstring("MLKIGH"), false);
TEST_EQUAL(s.hasSubstring("ACDEFGHIKLMNPQRSTVWYACDEF"), false);
END_SECTION
START_SECTION((bool has(Byte byte) const))
TEST_EQUAL(s.has('A'), true);
TEST_EQUAL(s.has('O'), false);
END_SECTION
START_SECTION((String prefix(Int length) const))
TEST_EQUAL(s.prefix((Int)4), "ACDE");
TEST_EQUAL(s.prefix((Int)0), "");
TEST_EXCEPTION(Exception::IndexOverflow, s.prefix(s.size()+1));
TEST_EXCEPTION(Exception::IndexUnderflow, s.prefix(-1));
END_SECTION
START_SECTION((String suffix(Int length) const))
TEST_EQUAL(s.suffix((Int)4), "TVWY");
TEST_EQUAL(s.suffix((Int)0), "");
TEST_EXCEPTION(Exception::IndexOverflow, s.suffix(s.size()+1));
TEST_EXCEPTION(Exception::IndexUnderflow, s.suffix(-1));
END_SECTION
START_SECTION((String prefix(SizeType length) const))
TEST_EQUAL(s.prefix((String::SizeType)4), "ACDE");
TEST_EQUAL(s.prefix((String::SizeType)0), "");
TEST_EXCEPTION(Exception::IndexOverflow, s.prefix(s.size()+1));
END_SECTION
START_SECTION((String suffix(SizeType length) const))
TEST_EQUAL(s.suffix((String::SizeType)4), "TVWY");
TEST_EQUAL(s.suffix((String::SizeType)0), "");
TEST_EXCEPTION(Exception::IndexOverflow, s.suffix(s.size()+1));
END_SECTION
START_SECTION((String prefix(char delim) const))
TEST_EQUAL(s.prefix('F'), "ACDE");
TEST_EQUAL(s.prefix('A'), "");
TEST_EXCEPTION(Exception::ElementNotFound, s.prefix('Z'));
END_SECTION
START_SECTION((String suffix(char delim) const))
TEST_EQUAL(s.suffix('S'), "TVWY");
TEST_EQUAL(s.suffix('Y'), "");
TEST_EXCEPTION(Exception::ElementNotFound, s.suffix('Z'));
END_SECTION
START_SECTION((String substr(size_t pos=0, size_t n=npos) const))
String s("abcdef");
//std::string functionality
TEST_EQUAL(s.substr(0,4),"abcd");
TEST_EQUAL(s.substr(1,1),"b")
TEST_EQUAL(s.substr(1,3),"bcd")
TEST_EQUAL(s.substr(0,4),"abcd")
TEST_EQUAL(s.substr(0,6),"abcdef")
TEST_EQUAL(s.substr(5,1),"f")
TEST_EQUAL(s.substr(6,1),"")
TEST_EQUAL(s.substr(0,7),"abcdef")
TEST_EQUAL(s.substr(0,String::npos), "abcdef")
// check with defaults
TEST_EQUAL(s.substr(0),"abcdef");
TEST_EQUAL(s.substr(1),"bcdef")
TEST_EQUAL(s.substr(5),"f")
TEST_EQUAL(s.substr(6),"")
END_SECTION
START_SECTION((String chop(Size n) const))
String s("abcdef");
TEST_EQUAL(s.chop(0), "abcdef")
TEST_EQUAL(s.chop(1), "abcde")
TEST_EQUAL(s.chop(2), "abcd")
TEST_EQUAL(s.chop(3), "abc")
TEST_EQUAL(s.chop(4), "ab")
TEST_EQUAL(s.chop(5), "a")
TEST_EQUAL(s.chop(6), "")
TEST_EQUAL(s.chop(9), "")
TEST_EQUAL(s.chop(-1), "")
END_SECTION
START_SECTION((String& reverse()))
s.reverse();
TEST_EQUAL(s, "YWVTSRQPNMLKIHGFEDCA");
s = "";
s.reverse();
TEST_EQUAL(s, "");
END_SECTION
START_SECTION((String& trim()))
String s("\n\r\t test \n\r\t");
s.trim();
TEST_EQUAL(s,"test");
s.trim();
TEST_EQUAL(s,"test");
s = "";
s.trim();
TEST_EQUAL(s,"");
s = " t";
s.trim();
TEST_EQUAL(s,"t");
s = "t ";
s.trim();
TEST_EQUAL(s,"t");
s = "\t\r\n ";
s.trim();
TEST_EQUAL(s,"");
END_SECTION
START_SECTION((String& quote(char q = '"', QuotingMethod method = ESCAPE)))
String s;
s.quote('\'', String::NONE);
TEST_EQUAL(s, "''");
s.quote('\'', String::ESCAPE);
TEST_EQUAL(s, "'\\'\\''");
s = "ab\"cd\\ef";
s.quote('"', String::NONE);
TEST_EQUAL(s, "\"ab\"cd\\ef\"");
s.quote('"', String::ESCAPE);
TEST_EQUAL(s, "\"\\\"ab\\\"cd\\\\ef\\\"\"");
s = "ab\"cd\\ef";
s.quote('"', String::DOUBLE);
TEST_EQUAL(s, "\"ab\"\"cd\\ef\"");
END_SECTION
START_SECTION((String& unquote(char q = '"', QuotingMethod method = ESCAPE)))
String s;
TEST_EXCEPTION(Exception::ConversionError, s.unquote());
s = "''";
s.unquote('\'', String::NONE);
TEST_EQUAL(s, "");
s = "'\\'\\''";
s.unquote('\'', String::ESCAPE);
TEST_EQUAL(s, "''");
s = R"("ab"cd\ef")";
s.unquote('"', String::NONE);
TEST_EQUAL(s, "ab\"cd\\ef");
s = R"("\"ab\"cd\\ef\"")";
s.unquote('"', String::ESCAPE);
TEST_EQUAL(s, "\"ab\"cd\\ef\"");
s = R"("ab""cd\ef")";
s.unquote('"', String::DOUBLE);
TEST_EQUAL(s, "ab\"cd\\ef");
END_SECTION
START_SECTION((String& simplify()))
String s("\n\r\t te\tst \n\r\t");
s.simplify();
TEST_EQUAL(s," te st ");
s.simplify();
TEST_EQUAL(s," te st ");
s = "";
s.simplify();
TEST_EQUAL(s,"");
s = " t";
s.simplify();
TEST_EQUAL(s," t");
s = "t ";
s.simplify();
TEST_EQUAL(s,"t ");
s = "\t\r\n ";
s.simplify();
TEST_EQUAL(s," ");
END_SECTION
START_SECTION((String& fillLeft(char c, UInt size)))
String s("TEST");
s.fillLeft('x',4);
TEST_EQUAL(s,"TEST")
s.fillLeft('y',5);
TEST_EQUAL(s,"yTEST")
s.fillLeft('z',7);
TEST_EQUAL(s,"zzyTEST")
END_SECTION
START_SECTION((String& fillRight(char c, UInt size)))
String s("TEST");
s.fillRight('x',4);
TEST_EQUAL(s,"TEST")
s.fillRight('y',5);
TEST_EQUAL(s,"TESTy")
s.fillRight('z',7);
TEST_EQUAL(s,"TESTyzz")
END_SECTION
START_SECTION((Int toInt() const))
String s;
s = "123";
TEST_EQUAL(s.toInt(),123);
s = "-123";
TEST_EQUAL(s.toInt(),-123);
s = " -123";
TEST_EQUAL(s.toInt(),-123);
s = "-123 ";
TEST_EQUAL(s.toInt(),-123);
s = " -123 ";
TEST_EQUAL(s.toInt(),-123);
// expect errors:
s = "524 starts with an int";
TEST_EXCEPTION(Exception::ConversionError, s.toInt())
s = "not an int";
TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, s.toInt(), String("Could not convert string '") + s + "' to an integer value")
s = "contains an 13135 int";
TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, s.toInt(), String("Could not convert string '") + s + "' to an integer value")
s = "ends with an int 525";
TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, s.toInt(), String("Could not convert string '") + s + "' to an integer value")
END_SECTION
START_SECTION((float toFloat() const))
String s;
s = "123.456";
TEST_REAL_SIMILAR(s.toFloat(),123.456);
s = "-123.456";
TEST_REAL_SIMILAR(s.toFloat(),-123.456);
s = "123.9";
TEST_REAL_SIMILAR(s.toFloat(),123.9);
s = "73629.9";
TEST_EQUAL(String(s.toFloat()),"7.36299e04");
s = "47218.8";
TEST_EQUAL(String(s.toFloat()),"4.72188e04");
s = String("nan");
TEST_EQUAL(std::isnan(s.toFloat()),true);
s = "NaN";
TEST_EQUAL(std::isnan(s.toFloat()),true);
s = "not a number";
TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, s.toFloat(), String("Could not convert string '") + s + "' to a float value")
END_SECTION
START_SECTION((double toDouble() const))
String s;
s = "123.456";
TEST_REAL_SIMILAR(s.toDouble(),123.456);
s = "-123.4567890123";
TEST_REAL_SIMILAR(s.toDouble(),-123.4567890123);
s = "123.99999";
TEST_REAL_SIMILAR(s.toDouble(),123.99999);
s = "73629.980123";
TEST_EQUAL(String(s.toDouble()),"7.3629980123e04");
s = "47218.890000001";
TEST_EQUAL(String(s.toDouble()),"4.7218890000001e04");
s = "nan";
TEST_TRUE(std::isnan(s.toDouble()));
s = "NaN"; // used in INI files, for Java compatibility
TEST_TRUE(std::isnan(s.toDouble()));
s = "not a number";
TEST_EXCEPTION_WITH_MESSAGE(Exception::ConversionError, s.toDouble(), String("Could not convert string '") + s + "' to a double value")
END_SECTION
START_SECTION((static String random(UInt length)))
String s;
String s2 = s.random(10);
TEST_EQUAL(s2.size(),10);
END_SECTION
START_SECTION((bool split(const char splitter, std::vector<String>& substrings, bool quote_protect=false) const))
String s(";1;2;3;4;5;");
vector<String> split;
bool result = s.split(';',split);
TEST_EQUAL(result,true);
TEST_EQUAL(split.size(),7);
TEST_EQUAL(split[0],String(""));
TEST_EQUAL(split[1],String("1"));
TEST_EQUAL(split[2],String("2"));
TEST_EQUAL(split[3],String("3"));
TEST_EQUAL(split[4],String("4"));
TEST_EQUAL(split[5],String("5"));
TEST_EQUAL(split[6],String(""));
s = "1;2;3;4;5";
result = s.split(';', split);
TEST_EQUAL(result,true);
TEST_EQUAL(split.size(),5);
TEST_EQUAL(split[0],String("1"));
TEST_EQUAL(split[1],String("2"));
TEST_EQUAL(split[2],String("3"));
TEST_EQUAL(split[3],String("4"));
TEST_EQUAL(split[4],String("5"));
s = "";
result = s.split(',', split);
TEST_EQUAL(result, false);
TEST_EQUAL(split.size(), 0);
s = ";";
result = s.split(';', split);
TEST_EQUAL(result,true);
TEST_EQUAL(split.size(),2);
TEST_EQUAL(split[0],"");
TEST_EQUAL(split[1],"");
result = s.split(',', split);
TEST_EQUAL(result,false);
TEST_EQUAL(split.size(),1);
s = "nodelim";
result = s.split(';', split);
TEST_EQUAL(result,false);
TEST_EQUAL(split.size(),1);
// testing quoting behaviour
s=" \"hello\", world, 23.3";
result = s.split(',', split, true);
TEST_EQUAL(result,true);
TEST_EQUAL(split.size(),3);
TEST_EQUAL(split[0],"hello");
TEST_EQUAL(split[1],"world");
TEST_EQUAL(split[2],"23.3");
s=R"( "hello", " donot,splitthis ", "23.4 " )";
result = s.split(',', split, true);
TEST_EQUAL(result,true);
TEST_EQUAL(split.size(),3);
TEST_EQUAL(split[0],"hello");
TEST_EQUAL(split[1]," donot,splitthis ");
TEST_EQUAL(split[2],"23.4 ");
s=R"( "hello", " donot,splitthis ", "23.5 " )";
result = s.split(',', split, true);
TEST_EQUAL(result,true);
TEST_EQUAL(split.size(),3);
TEST_EQUAL(split[0],"hello");
TEST_EQUAL(split[1]," donot,splitthis ");
TEST_EQUAL(split[2],"23.5 ");
s=R"( "hello", " donot,splitthis ", "23.6 " )";
result = s.split(',', split, true);
TEST_EQUAL(result,true);
TEST_EQUAL(split.size(),3);
TEST_EQUAL(split[0],"hello");
TEST_EQUAL(split[1]," donot,splitthis ");
TEST_EQUAL(split[2],"23.6 ");
s = " \"nodelim \"";
result = s.split(';', split, true);
TEST_EQUAL(result,false);
TEST_EQUAL(split.size(),1);
// testing invalid quoting...
s = R"( "first", "seconds"<thisshouldnotbehere>, third)";
TEST_EXCEPTION(Exception::ConversionError, s.split(',', split, true));
END_SECTION
START_SECTION((bool split(const String& splitter, std::vector<String>& substrings) const))
String s = "abcdebcfghbc";
vector<String> substrings;
bool result = s.split("bc", substrings);
TEST_EQUAL(result, true);
TEST_EQUAL(substrings.size(), 4);
TEST_EQUAL(substrings[0], "a");
TEST_EQUAL(substrings[1], "de");
TEST_EQUAL(substrings[2], "fgh");
TEST_EQUAL(substrings[3], "");
s = "abcdabcdabcd";
result = s.split("abcd", substrings);
TEST_EQUAL(result, true);
TEST_EQUAL(substrings.size(), 4);
TEST_EQUAL(substrings[0], "");
TEST_EQUAL(substrings[1], "");
TEST_EQUAL(substrings[2], "");
TEST_EQUAL(substrings[3], "");
result = s.split("xy", substrings);
TEST_EQUAL(result, false);
TEST_EQUAL(substrings.size(), 1);
TEST_EQUAL(substrings[0], s);
result = s.split("", substrings);
TEST_EQUAL(result, true);
TEST_EQUAL(s.size(), substrings.size());
TEST_EQUAL(substrings[0], "a");
TEST_EQUAL(substrings[substrings.size() - 1], "d");
result = String("").split(",", substrings);
TEST_EQUAL(result, false);
TEST_EQUAL(substrings.size(), 0);
END_SECTION
START_SECTION((bool split_quoted(const String& splitter, std::vector<String>& substrings, char q = '"', QuotingMethod method = ESCAPE) const))
String s = "abcdebcfghbc";
vector<String> substrings;
bool result = s.split_quoted("bc", substrings);
TEST_EQUAL(result, true);
TEST_EQUAL(substrings.size(), 4);
TEST_EQUAL(substrings[0], "a");
TEST_EQUAL(substrings[1], "de");
TEST_EQUAL(substrings[2], "fgh");
TEST_EQUAL(substrings[3], "");
s = "abcdabcdabcd";
result = s.split_quoted("abcd", substrings);
TEST_EQUAL(result, true);
TEST_EQUAL(substrings.size(), 4);
TEST_EQUAL(substrings[0], "");
TEST_EQUAL(substrings[1], "");
TEST_EQUAL(substrings[2], "");
TEST_EQUAL(substrings[3], "");
result = s.split_quoted("xy", substrings);
TEST_EQUAL(result, false);
TEST_EQUAL(substrings.size(), 1);
TEST_EQUAL(substrings[0], s);
s = R"("a,b,c","d,\",f","")";
result = s.split_quoted(",", substrings, '"', String::ESCAPE);
TEST_EQUAL(result, true);
TEST_EQUAL(substrings.size(), 3);
TEST_EQUAL(substrings[0], "\"a,b,c\"");
TEST_EQUAL(substrings[1], "\"d,\\\",f\"");
TEST_EQUAL(substrings[2], "\"\"");
s = R"("a,"b")";
TEST_EXCEPTION(Exception::ConversionError, s.split_quoted(",", substrings, '"',
String::ESCAPE));
s = R"("ab"___"cd""ef")";
result = s.split_quoted("___", substrings, '"', String::DOUBLE);
TEST_EQUAL(result, true);
TEST_EQUAL(substrings.size(), 2);
TEST_EQUAL(substrings[0], "\"ab\"");
TEST_EQUAL(substrings[1], "\"cd\"\"ef\"");
END_SECTION
START_SECTION((template<class StringIterator> void concatenate(StringIterator first, StringIterator last, const String& glue = "")))
vector<String> split;
String("1;2;3;4;5").split(';',split);
String s;
s.concatenate(split.begin(),split.end(),"g");
TEST_EQUAL(s,"1g2g3g4g5");
String("1;2;3;4;5").split(';',split);
s.concatenate(split.begin(),split.end());
TEST_EQUAL(s,"12345");
String("").split(';',split);
s.concatenate(split.begin(),split.end());
TEST_EQUAL(s,"");
s.concatenate(split.begin(),split.end(),"_");
TEST_EQUAL(s,"");
END_SECTION
START_SECTION((String& toUpper()))
String s;
s = "test45%#.,";
s.toUpper();
TEST_EQUAL(s,"TEST45%#.,");
s = "";
s.toUpper();
TEST_EQUAL(s,"");
END_SECTION
START_SECTION((String& toLower()))
String s;
s = "TEST45%#.,";
s.toLower();
TEST_EQUAL(s,"test45%#.,");
s = "";
s.toLower();
TEST_EQUAL(s,"");
END_SECTION
START_SECTION((String& firstToUpper()))
String s;
s = "test45%#.,";
s.firstToUpper();
TEST_EQUAL(s,"Test45%#.,");
s = " ";
s.firstToUpper();
TEST_EQUAL(s," ");
s = "";
s.firstToUpper();
TEST_EQUAL(s,"");
END_SECTION
START_SECTION((String& substitute(char from, char to)))
String s = "abcdefg";
s.substitute('a','x');
TEST_EQUAL(s,"xbcdefg")
s.substitute('g','y');
TEST_EQUAL(s,"xbcdefy")
s.substitute('c','-');
TEST_EQUAL(s,"xb-defy")
s = ".....";
s.substitute('.',',');
TEST_EQUAL(s,",,,,,")
s = ".....";
s.substitute(',','.');
TEST_EQUAL(s,".....")
END_SECTION
START_SECTION((String& substitute(const String& from, const String& to)))
//single occurence
String s = "abcdefg";
s.substitute("a","x");
TEST_EQUAL(s,"xbcdefg")
s.substitute("bcd","y");
TEST_EQUAL(s,"xyefg")
s.substitute("fg","");
TEST_EQUAL(s,"xye")
s.substitute("e","z!");
TEST_EQUAL(s,"xyz!")
s.substitute("u","blblblblbl");
TEST_EQUAL(s,"xyz!")
s.substitute("","blblblblbl");
TEST_EQUAL(s,"xyz!")
//mutiple occurrences
s = "abcdefgabcdefgabcdefgab";
s.substitute("ab","x");
TEST_EQUAL(s,"xcdefgxcdefgxcdefgx")
s.substitute("x","");
TEST_EQUAL(s,"cdefgcdefgcdefg")
END_SECTION
START_SECTION((String& remove(char what)))
String s = "abcabc";
s.remove('a');
TEST_EQUAL(s, "bcbc");
s.remove('c');
TEST_EQUAL(s, "bb");
s.remove('b');
TEST_EQUAL(s, "");
END_SECTION
START_SECTION((String& ensureLastChar(char end)))
String s = "/";
s.ensureLastChar('/');
TEST_EQUAL(s, "/")
s.ensureLastChar('\\');
TEST_EQUAL(s, "/\\")
s.ensureLastChar('\\');
TEST_EQUAL(s, "/\\")
s.ensureLastChar('/');
TEST_EQUAL(s, "/\\/")
END_SECTION
START_SECTION((String& removeWhitespaces()))
{
String s;
s.removeWhitespaces();
TEST_EQUAL(s,"");
s = " \t \n ";
s.removeWhitespaces();
TEST_EQUAL(s, "");
s = "test";
s.removeWhitespaces();
TEST_EQUAL(s,"test");
s = "\n\r\t test \n\r\t";
s.removeWhitespaces();
TEST_EQUAL(s,"test");
s = "\n\r\t t\ne \ts\rt \n\r\t";
s.removeWhitespaces();
TEST_EQUAL(s,"test");
const std::string test(16 * 1024 + 1, 'x'); // not a multiple of 16, so any SSE code needs to deal with a remainder
s = test + std::string(100, ' ');
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(s.begin(), s.end(), g);
s.removeWhitespaces();
TEST_EQUAL(s, test);
}
END_SECTION
const String fixed("test");
START_SECTION((String operator+ (int i) const))
TEST_EQUAL(fixed + (int)(4), "test4")
END_SECTION
START_SECTION((String operator+ (unsigned int i) const))
TEST_EQUAL(fixed + (unsigned int)(4), "test4")
END_SECTION
START_SECTION((String operator+ (short int i) const))
TEST_EQUAL(fixed + (short int)(4), "test4")
END_SECTION
START_SECTION((String operator+ (short unsigned int i) const))
TEST_EQUAL(fixed + (short unsigned int)(4), "test4")
END_SECTION
START_SECTION((String operator+ (long int i) const))
TEST_EQUAL(fixed + (long int)(4), "test4")
END_SECTION
START_SECTION((String operator+ (long unsigned int i) const))
TEST_EQUAL(fixed + (long unsigned int)(4), "test4")
END_SECTION
START_SECTION((String operator+ (long long unsigned int i) const))
TEST_EQUAL(fixed + (long long unsigned int)(4), "test4")
END_SECTION
START_SECTION((String operator+ (float f) const))
TEST_EQUAL(fixed + (float)(4), "test4.0")
END_SECTION
START_SECTION((String operator+ (double d) const))
TEST_EQUAL(fixed + (double)(4), "test4.0")
END_SECTION
START_SECTION((String operator+(long double ld) const ))
TEST_EQUAL(fixed + (long double)(4), "test4.0")
END_SECTION
START_SECTION((String operator+ (char c) const))
TEST_EQUAL(fixed + '4', "test4")
END_SECTION
START_SECTION((String operator+ (const char* s) const))
TEST_EQUAL(fixed + "bla4", "testbla4")
END_SECTION
START_SECTION((String operator+ (const String& s) const))
TEST_EQUAL(fixed + String("bla4"), "testbla4")
END_SECTION
START_SECTION((String operator+ (const std::string& s) const))
TEST_EQUAL(fixed.operator+(std::string("bla4")), "testbla4")
END_SECTION
START_SECTION((String& operator+= (int i)))
String s = "test";
s += (int)(7);
TEST_EQUAL(s, "test7")
END_SECTION
START_SECTION((String& operator+= (unsigned int i)))
String s = "test";
s += (unsigned int)(7);
TEST_EQUAL(s, "test7")
END_SECTION
START_SECTION((String& operator+= (short int i)))
String s = "test";
s += (short int)(7);
TEST_EQUAL(s, "test7")
END_SECTION
START_SECTION((String& operator+= (short unsigned int i)))
String s = "test";
s += (short unsigned int)(7);
TEST_EQUAL(s, "test7")
END_SECTION
START_SECTION((String& operator+= (long int i)))
String s = "test";
s += (long int)(7);
TEST_EQUAL(s, "test7")
END_SECTION
START_SECTION((String& operator+= (long unsigned int i)))
String s = "test";
s += (long unsigned int)(7);
TEST_EQUAL(s, "test7")
END_SECTION
START_SECTION((String& operator+= (long long unsigned int i)))
String s = "test";
s += (long long unsigned int)(7);
TEST_EQUAL(s, "test7")
END_SECTION
START_SECTION((String& operator+= (float f)))
String s = "test";
s += (float)(7.4);
TEST_EQUAL(s, "test7.4")
END_SECTION
START_SECTION((String& operator+= (double d)))
String s = "test";
s += (double)(7.4);
TEST_EQUAL(s, "test7.4")
END_SECTION
START_SECTION((String& operator+= (long double d)))
{
String s = "test";
// long double x = 7.4; // implictly double (not long double!) => 7.40000000000000036
long double x = 7.4L; // explictly long double => 7.4
s += x;
TEST_EQUAL(s, "test7.4");
}
END_SECTION
START_SECTION((String& operator+= (char c)))
String s = "test";
s += 'x';
TEST_EQUAL(s, "testx")
END_SECTION
START_SECTION((String& operator+= (const char* s)))
String s = "test";
s += 7;
TEST_EQUAL(s, "test7")
END_SECTION
START_SECTION((String& operator+= (const String& s)))
String s = "test";
s += String("7");
TEST_EQUAL(s, "test7")
END_SECTION
START_SECTION((String& operator+= (const std::string& s)))
String s = "test";
s += std::string("7");
TEST_EQUAL(s, "test7")
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SimpleTSGXLMS_test.cpp | .cpp | 19,733 | 561 | // 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/SimpleTSGXLMS.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/ANALYSIS/XLMS/OPXLDataStructs.h>
#include <iostream>
START_TEST(SimpleTSGXLMS, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
SimpleTSGXLMS* ptr = nullptr;
SimpleTSGXLMS* nullPointer = nullptr;
/// mostly copied from TheoreticalSpectrumGenerator_test
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
START_SECTION(SimpleTSGXLMS())
ptr = new SimpleTSGXLMS();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(SimpleTSGXLMS(const SimpleTSGXLMS& source))
SimpleTSGXLMS copy(*ptr);
TEST_EQUAL(copy.getParameters(), ptr->getParameters())
END_SECTION
START_SECTION(~SimpleTSGXLMS())
delete ptr;
END_SECTION
ptr = new SimpleTSGXLMS();
AASequence peptide = AASequence::fromString("IFSQVGK");
START_SECTION(SimpleTSGXLMS& operator = (const SimpleTSGXLMS& tsg))
SimpleTSGXLMS copy;
copy = *ptr;
TEST_EQUAL(copy.getParameters(), ptr->getParameters())
END_SECTION
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
START_SECTION(virtual void getLinearIonSpectrum(PeakSpectrum & spectrum, AASequence & peptide, Size link_pos, int charge = 1, Size link_pos_2 = 0))
std::vector< SimpleTSGXLMS::SimplePeak > spec;
ptr->getLinearIonSpectrum(spec, peptide, 3, 2);
TEST_EQUAL(spec.size(), 18)
TOLERANCE_ABSOLUTE(0.001)
double result[] = {43.55185, 57.54930, 74.06004, 86.09642, 102.57077, 114.09134, 117.08605, 131.08351, 147.11280, 152.10497, 160.60207, 174.59953, 204.13426, 233.16484, 261.15975, 303.20268, 320.19686, 348.19178};
for (Size i = 0; i != spec.size(); ++i)
{
TEST_REAL_SIMILAR(spec[i].mz, result[i])
}
spec.clear();
ptr->getLinearIonSpectrum(spec, peptide, 3, 3);
TEST_EQUAL(spec.size(), 27)
spec.clear();
Param param(ptr->getParameters());
param.setValue("add_a_ions", "true");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "true");
param.setValue("add_x_ions", "true");
param.setValue("add_y_ions", "true");
param.setValue("add_z_ions", "true");
// param.setValue("add_charges", "false");
ptr->setParameters(param);
ptr->getLinearIonSpectrum(spec, peptide, 3, 3);
TEST_EQUAL(spec.size(), 54)
// // test annotation
spec.clear();
param = ptr->getParameters();
param.setValue("add_a_ions", "false");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "false");
param.setValue("add_x_ions", "true");
param.setValue("add_y_ions", "false");
param.setValue("add_z_ions", "false");
// param.setValue("add_charges", "true");
param.setValue("add_losses", "true");
ptr->setParameters(param);
ptr->getLinearIonSpectrum(spec, peptide, 3, 3);
// 6 ion types with 3 charges each are expected
TEST_EQUAL(spec.size(), 30)
int charge_counts[4] = {0, 0, 0, 0};
for (Size i = 0; i != spec.size(); ++i)
{
charge_counts[spec[i].charge]++;
}
TEST_EQUAL(charge_counts[0], 0)
TEST_EQUAL(charge_counts[1], 10)
TEST_EQUAL(charge_counts[2], 10)
TEST_EQUAL(charge_counts[3], 10)
param = ptr->getParameters();
param.setValue("add_losses", "false");
ptr->setParameters(param);
// the smallest examples, that make sense for cross-linking
spec.clear();
AASequence testseq = AASequence::fromString("HA");
ptr->getLinearIonSpectrum(spec, testseq, 0, 1);
TEST_EQUAL(spec.size(), 1)
spec.clear();
ptr->getLinearIonSpectrum(spec, testseq, 1, 1);
TEST_EQUAL(spec.size(), 1)
// loop link
spec.clear();
testseq = AASequence::fromString("PEPTIDESAREWEIRD");
ptr->getLinearIonSpectrum(spec, testseq, 1, 1, 14);
TEST_EQUAL(spec.size(), 2)
spec.clear();
ptr->getLinearIonSpectrum(spec, testseq, 2, 1, 14);
TEST_EQUAL(spec.size(), 3)
// test isotopic peaks
spec.clear();
param = ptr->getParameters();
param.setValue("add_isotopes", "true");
param.setValue("max_isotope", 1);
param.setValue("add_a_ions", "false");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "false");
param.setValue("add_x_ions", "false");
param.setValue("add_y_ions", "true");
param.setValue("add_z_ions", "false");
// param.setValue("add_charges", "false");
ptr->setParameters(param);
ptr->getLinearIonSpectrum(spec, peptide, 3, 3);
// 6 ion types with 3 charges each are expected
TEST_EQUAL(spec.size(), 18)
spec.clear();
param.setValue("add_isotopes", "true");
param.setValue("max_isotope", 2); //
param.setValue("add_losses", "true");
ptr->setParameters(param);
ptr->getLinearIonSpectrum(spec, peptide, 3, 3);
// 6 ion types with 3 charges each are expected, each with a second isotopic peak
// + a few losses
TEST_EQUAL(spec.size(), 48)
spec.clear();
param.setValue("add_isotopes", "true");
param.setValue("max_isotope", 3); // not supported yet, but it should at least run (with the maximal possible number of peaks)
ptr->setParameters(param);
ptr->getLinearIonSpectrum(spec, peptide, 3, 3);
// 6 ion types with 3 charges each are expected, each with a second isotopic peak
// should be the same result as above for now
TEST_EQUAL(spec.size(), 48)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// // for quick benchmarking of implementation chances
// param = ptr->getParameters();
// param.setValue("add_a_ions", "true");
// param.setValue("add_b_ions", "true");
// param.setValue("add_c_ions", "true");
// param.setValue("add_x_ions", "true");
// param.setValue("add_y_ions", "true");
// param.setValue("add_z_ions", "true");
// param.setValue("add_charges", "true");
// param.setValue("add_losses", "true");
// ptr->setParameters(param);
// AASequence tmp_peptide = AASequence::fromString("PEPTIDEPEPTIDEPEPTIDE");
// for (Size i = 0; i != 1e4; ++i)
// {
// PeakSpectrum spec;
// ptr->getLinearIonSpectrum(spec, tmp_peptide, 9, true, 5);
// }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
END_SECTION
START_SECTION(virtual void getXLinkIonSpectrum(PeakSpectrum & spectrum, AASequence & peptide, Size link_pos, double precursor_mass, bool frag_alpha, int mincharge, int maxcharge, Size link_pos_2 = 0))
// reinitialize TSG to standard parameters
Param param(ptr->getParameters());
param.setValue("add_isotopes", "false");
param.setValue("max_isotope", 2);
param.setValue("add_a_ions", "false");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "false");
param.setValue("add_x_ions", "false");
param.setValue("add_y_ions", "true");
param.setValue("add_z_ions", "false");
param.setValue("add_losses", "false");
ptr->setParameters(param);
std::vector< SimpleTSGXLMS::SimplePeak > spec;
ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, 2, 3);
TEST_EQUAL(spec.size(), 17)
param.setValue("add_losses", "true");
ptr->setParameters(param);
spec.clear();
ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, 2, 3);
TEST_EQUAL(spec.size(), 39)
TOLERANCE_ABSOLUTE(0.001)
param.setValue("add_losses", "false");
ptr->setParameters(param);
spec.clear();
ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, 2, 3);
double result[] = {442.55421, 551.94577, 566.94214, 580.95645, 599.96494, 618.97210, 629.97925, 661.67042, 661.99842, 663.32768, 667.67394, 827.41502, 849.90957, 870.93103, 899.44378, 927.95451, 944.46524};
for (Size i = 0; i != spec.size(); ++i)
{
TEST_REAL_SIMILAR(spec[i].mz, result[i])
}
spec.clear();
ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, 2, 4);
TEST_EQUAL(spec.size(), 24)
spec.clear();
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");
ptr->setParameters(param);
ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, 2, 4);
TEST_EQUAL(spec.size(), 60)
// test annotation
spec.clear();
param = ptr->getParameters();
param.setValue("add_a_ions", "false");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "false");
param.setValue("add_x_ions", "true");
param.setValue("add_y_ions", "false");
param.setValue("add_z_ions", "false");
param.setValue("add_losses", "true");
ptr->setParameters(param);
ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, 2, 5);
// 6 ion types with 4 charges each are expected
// + KLinked ions and precursors
TEST_EQUAL(spec.size(), 75)
int charge_counts[6] = {0, 0, 0, 0, 0, 0};
for (Size i = 0; i != spec.size(); ++i)
{
charge_counts[spec[i].charge]++;
}
TEST_EQUAL(charge_counts[1], 0)
TEST_EQUAL(charge_counts[2], 18)
TEST_EQUAL(charge_counts[3], 18)
TEST_EQUAL(charge_counts[4], 18)
TEST_EQUAL(charge_counts[5], 21) // 18 ion types + precursors
param = ptr->getParameters();
param.setValue("add_a_ions", "false");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "false");
param.setValue("add_x_ions", "false");
param.setValue("add_y_ions", "true");
param.setValue("add_z_ions", "false");
param.setValue("add_losses", "false");
param.setValue("add_precursor_peaks", "false");
param.setValue("add_k_linked_ions", "false");
ptr->setParameters(param);
// the smallest examples, that make sense for cross-linking
spec.clear();
AASequence testseq = AASequence::fromString("HA");
ptr->getXLinkIonSpectrum(spec, testseq, 0, 2000.0, 1, 1);
TEST_EQUAL(spec.size(), 1)
spec.clear();
ptr->getXLinkIonSpectrum(spec, testseq, 1, 2000.0, 1, 1);
TEST_EQUAL(spec.size(), 1)
// loop link
spec.clear();
testseq = AASequence::fromString("PEPTIDESAREWEIRD");
ptr->getXLinkIonSpectrum(spec, testseq, 1, 2000.0, 1, 1, 14);
TEST_EQUAL(spec.size(), 2)
spec.clear();
ptr->getXLinkIonSpectrum(spec, testseq, 2, 2000.0, 1, 1, 14);
TEST_EQUAL(spec.size(), 3)
spec.clear();
ptr->getXLinkIonSpectrum(spec, testseq, 2, 2000.0, 1, 1, 13);
TEST_EQUAL(spec.size(), 4)
// test isotopic peaks
spec.clear();
param = ptr->getParameters();
param.setValue("add_isotopes", "true");
param.setValue("max_isotope", 1);
param.setValue("add_a_ions", "false");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "false");
param.setValue("add_x_ions", "false");
param.setValue("add_y_ions", "true");
param.setValue("add_z_ions", "false");
ptr->setParameters(param);
ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, 2, 5);
// 6 ion types with 4 charges each are expected
TEST_EQUAL(spec.size(), 24)
spec.clear();
param.setValue("add_isotopes", "true");
param.setValue("max_isotope", 2); //
ptr->setParameters(param);
ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, 2, 5);
// 6 ion types with 4 charges each are expected, each with a second isotopic peak
TEST_EQUAL(spec.size(), 48)
spec.clear();
param.setValue("add_isotopes", "true");
param.setValue("max_isotope", 3); // not supported yet, but it should at least run (with the maximal possible number of peaks)
ptr->setParameters(param);
ptr->getXLinkIonSpectrum(spec, peptide, 3, 2000.0, 2, 5);
// 6 ion types with 4 charges each are expected, each with a second isotopic peak
TEST_EQUAL(spec.size(), 48)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// // for quick benchmarking of implementation chances
// param = ptr->getParameters();
// param.setValue("add_a_ions", "true");
// param.setValue("add_b_ions", "true");
// param.setValue("add_c_ions", "true");
// param.setValue("add_x_ions", "true");
// param.setValue("add_y_ions", "true");
// param.setValue("add_z_ions", "true");
// param.setValue("add_charges", "true");
// param.setValue("add_losses", "false");
// ptr->setParameters(param);
// AASequence tmp_peptide = AASequence::fromString("PEPTIDEPEPTIDEPEPTIDE");
// for (Size i = 0; i != 1e3; ++i)
// {
// PeakSpectrum spec;
// ptr->getXLinkIonSpectrum(spec, tmp_peptide, 9, 2000.0, false, 2, 5);
// }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
END_SECTION
START_SECTION(virtual void getXLinkIonSpectrum(PeakSpectrum & spectrum, OPXLDataStructs::ProteinProteinCrossLink & crosslink, bool frag_alpha, int mincharge, int maxcharge))
// reinitialize TSG to standard parameters
Param param(ptr->getParameters());
param.setValue("add_isotopes", "false");
param.setValue("max_isotope", 2);
param.setValue("add_a_ions", "false");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "false");
param.setValue("add_x_ions", "false");
param.setValue("add_y_ions", "true");
param.setValue("add_z_ions", "false");
param.setValue("add_losses", "false");
param.setValue("add_precursor_peaks", "true");
param.setValue("add_k_linked_ions", "true");
ptr->setParameters(param);
OPXLDataStructs::ProteinProteinCrossLink test_link;
test_link.alpha = &peptide;
AASequence beta = AASequence::fromString("TESTPEP");
test_link.beta = β
test_link.cross_link_position = std::make_pair<SignedSize, SignedSize> (3, 4);
test_link.cross_linker_mass = 150.0;
std::vector< SimpleTSGXLMS::SimplePeak > spec;
ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 3);
TEST_EQUAL(spec.size(), 17)
param.setValue("add_losses", "true");
ptr->setParameters(param);
spec.clear();
ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 3);
TEST_EQUAL(spec.size(), 41)
TOLERANCE_ABSOLUTE(0.001)
param.setValue("add_losses", "false");
ptr->setParameters(param);
spec.clear();
ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 3);
double result[] = {338.14327, 447.53482, 462.53119, 476.54550, 495.55399, 506.71126, 514.56115, 525.56830, 557.25947, 557.58748, 563.26299, 670.79860, 693.29315, 714.31461, 742.82736, 771.33809, 787.84882};
for (Size i = 0; i != spec.size(); ++i)
{
TEST_REAL_SIMILAR(spec[i].mz, result[i])
}
spec.clear();
ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 4);
TEST_EQUAL(spec.size(), 24)
spec.clear();
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");
ptr->setParameters(param);
ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 4);
TEST_EQUAL(spec.size(), 60)
// test annotation
spec.clear();
param = ptr->getParameters();
param.setValue("add_a_ions", "false");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "false");
param.setValue("add_x_ions", "true");
param.setValue("add_y_ions", "false");
param.setValue("add_z_ions", "false");
param.setValue("add_losses", "true");
ptr->setParameters(param);
ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 5);
// 6 ion types with 4 charges each are expected
// + KLinked ions and precursors
TEST_EQUAL(spec.size(), 79)
int charge_counts[6] = {0, 0, 0, 0, 0, 0};
for (Size i = 0; i != spec.size(); ++i)
{
charge_counts[spec[i].charge]++;
}
TEST_EQUAL(charge_counts[1], 0)
TEST_EQUAL(charge_counts[2], 19)
TEST_EQUAL(charge_counts[3], 19)
TEST_EQUAL(charge_counts[4], 19)
TEST_EQUAL(charge_counts[5], 22)
param = ptr->getParameters();
param.setValue("add_a_ions", "false");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "false");
param.setValue("add_x_ions", "false");
param.setValue("add_y_ions", "true");
param.setValue("add_z_ions", "false");
param.setValue("add_losses", "false");
param.setValue("add_precursor_peaks", "false");
param.setValue("add_k_linked_ions", "false");
ptr->setParameters(param);
// the smallest examples, that make sense for cross-linking
spec.clear();
AASequence testseq = AASequence::fromString("HA");
OPXLDataStructs::ProteinProteinCrossLink test_link_short;
test_link_short.alpha = &testseq;
// AASequence beta = AASequence::fromString("TESTPEP");
test_link_short.beta = β
test_link_short.cross_link_position = std::make_pair<SignedSize, SignedSize> (1, 4);
test_link_short.cross_linker_mass = 150.0;
ptr->getXLinkIonSpectrum(spec, test_link_short, true, 1, 1);
TEST_EQUAL(spec.size(), 1)
spec.clear();
ptr->getXLinkIonSpectrum(spec, test_link_short, true, 1, 1);
TEST_EQUAL(spec.size(), 1)
// test isotopic peaks
spec.clear();
param = ptr->getParameters();
param.setValue("add_isotopes", "true");
param.setValue("max_isotope", 1);
param.setValue("add_a_ions", "false");
param.setValue("add_b_ions", "true");
param.setValue("add_c_ions", "false");
param.setValue("add_x_ions", "false");
param.setValue("add_y_ions", "true");
param.setValue("add_z_ions", "false");
ptr->setParameters(param);
ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 5);
// 6 ion types with 4 charges each are expected
TEST_EQUAL(spec.size(), 24)
spec.clear();
param.setValue("add_isotopes", "true");
param.setValue("max_isotope", 2); //
ptr->setParameters(param);
ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 5);
// 6 ion types with 4 charges each are expected, each with a second isotopic peak
TEST_EQUAL(spec.size(), 48)
spec.clear();
param.setValue("add_isotopes", "true");
param.setValue("max_isotope", 3); // not supported yet, but it should at least run (with the maximal possible number of peaks)
ptr->setParameters(param);
ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 5);
// 6 ion types with 4 charges each are expected, each with a second isotopic peak
TEST_EQUAL(spec.size(), 48)
// // Benchmarking of generating cross-linked ion spectra using different sorting algorithms (minimal value in sec)
// // std::sort 19.9
// // rev + std::sort 21.5
// // std::stable_sort 21.9
// // rev + std::stable_sort 20.5
// // boost::spinsort: 45
// // rev + boost::spinsort 19.25
// // boost::pdqsort: 18.52
// // rev + boost::pdqsort 18.46 + better average
// for (Size i = 0; i <= 2000000; i++)
// {
// spec.clear();
// ptr->getXLinkIonSpectrum(spec, test_link, true, 2, 5);
// }
// // Linear spectra
// // std::sort 23
// // std::stable_sort: 19.24
// // boost::spinsort 20.45
// // boost::pdqsort: 18.5
//
// AASequence tmp_peptide = AASequence::fromString("PEPTIDEPEPTIDEPEPTIDE");
// for (Size i = 0; i <= 2000000; i++)
// {
// spec.clear();
// ptr->getLinearIonSpectrum(spec, tmp_peptide, 9, true, 2);
// }
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
delete ptr;
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/OMSSAXMLFile_test.cpp | .cpp | 2,809 | 80 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/OMSSAXMLFile.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <vector>
///////////////////////////
START_TEST(OMSSAXMLFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
OMSSAXMLFile xml_file;
OMSSAXMLFile* ptr;
OMSSAXMLFile* nullPointer = nullptr;
ProteinIdentification protein_identification;
PeptideIdentificationList peptide_identifications;
PeptideIdentificationList peptide_identifications2;
String date_string_1;
String date_string_2;
PeptideHit peptide_hit;
START_SECTION((OMSSAXMLFile()))
ptr = new OMSSAXMLFile();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~OMSSAXMLFile())
delete ptr;
END_SECTION
ptr = new OMSSAXMLFile();
START_SECTION(void setModificationDefinitionsSet(const ModificationDefinitionsSet &rhs))
ModificationDefinitionsSet mod_set(ListUtils::create<String>(""), ListUtils::create<String>("Carbamidomethyl (C),Oxidation (M),Carboxymethyl (C)"));
ptr->setModificationDefinitionsSet(mod_set);
NOT_TESTABLE
END_SECTION
START_SECTION(void load(const String& filename, ProteinIdentification& protein_identification, PeptideIdentificationList& id_data, bool load_proteins=true, bool load_empty_hits = true))
// two spectra, first with some hits (mapping to 4 proteins), second is empty
xml_file.load(OPENMS_GET_TEST_DATA_PATH("OMSSAXMLFile_test_1.xml"), protein_identification, peptide_identifications);
TEST_EQUAL(protein_identification.getHits().size(), 4)
TEST_EQUAL(peptide_identifications.size(), 2)
xml_file.load(OPENMS_GET_TEST_DATA_PATH("OMSSAXMLFile_test_1.xml"), protein_identification, peptide_identifications, false);
TEST_EQUAL(protein_identification.getHits().size(), 0)
TEST_EQUAL(peptide_identifications.size(), 2)
xml_file.load(OPENMS_GET_TEST_DATA_PATH("OMSSAXMLFile_test_1.xml"), protein_identification, peptide_identifications, false, false);
TEST_EQUAL(protein_identification.getHits().size(), 0)
TEST_EQUAL(peptide_identifications.size(), 1)
END_SECTION
delete ptr;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/FeatureGroupingAlgorithmLabeled_test.cpp | .cpp | 3,743 | 141 | // 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/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmLabeled.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(FeatureGroupingAlgorithmLabeled, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
FeatureGroupingAlgorithmLabeled* ptr = nullptr;
FeatureGroupingAlgorithmLabeled* nullPointer = nullptr;
START_SECTION((FeatureGroupingAlgorithmLabeled()))
ptr = new FeatureGroupingAlgorithmLabeled();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~FeatureGroupingAlgorithmLabeled()))
delete ptr;
END_SECTION
START_SECTION((virtual void group(const std::vector< FeatureMap > &maps, ConsensusMap &out)))
TOLERANCE_ABSOLUTE(0.001)
FeatureGroupingAlgorithmLabeled fga;
std::vector< FeatureMap > in;
ConsensusMap out;
//test exception (no input)
TEST_EXCEPTION(Exception::IllegalArgument, fga.group(in,out));
//real test
in.resize(1);
in[0].resize(10);
//start
in[0][0].setRT(1.0f);
in[0][0].setMZ(1.0f);
in[0][0].setCharge(1);
in[0][0].setOverallQuality(1);
in[0][0].setIntensity(4.0f);
//best
in[0][1].setRT(1.5f);
in[0][1].setMZ(5.0f);
in[0][1].setCharge(1);
in[0][1].setOverallQuality(1);
in[0][1].setIntensity(2.0f);
//inside (down, up, left, right)
in[0][2].setRT(1.0f);
in[0][2].setMZ(5.0f);
in[0][2].setCharge(1);
in[0][2].setOverallQuality(1);
in[0][3].setRT(3.0f);
in[0][3].setMZ(5.0f);
in[0][3].setCharge(1);
in[0][3].setOverallQuality(1);
in[0][4].setRT(1.5f);
in[0][4].setMZ(4.8f);
in[0][4].setCharge(1);
in[0][4].setOverallQuality(1);
in[0][5].setRT(1.5f);
in[0][5].setMZ(5.2f);
in[0][5].setCharge(1);
in[0][5].setOverallQuality(1);
//outside (down, up, left, right)
in[0][6].setRT(0.0f);
in[0][6].setMZ(5.0f);
in[0][6].setCharge(1);
in[0][6].setOverallQuality(1);
in[0][7].setRT(4.0f);
in[0][7].setMZ(5.0f);
in[0][7].setCharge(1);
in[0][7].setOverallQuality(1);
in[0][8].setRT(1.5f);
in[0][8].setMZ(4.0f);
in[0][8].setCharge(1);
in[0][8].setOverallQuality(1);
in[0][9].setRT(1.5f);
in[0][9].setMZ(6.0f);
in[0][9].setCharge(1);
in[0][9].setOverallQuality(1);
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);
fga.setParameters(p);
//test exception (no file name set in out)
TEST_EXCEPTION(Exception::IllegalArgument, fga.group(in,out));
out.getColumnHeaders()[5].label = "light";
out.getColumnHeaders()[5].filename = "filename";
out.getColumnHeaders()[8] = out.getColumnHeaders()[5];
out.getColumnHeaders()[8].label = "heavy";
fga.group(in,out);
TEST_EQUAL(out.size(),1)
TEST_REAL_SIMILAR(out[0].getQuality(),0.959346);
TEST_EQUAL(out[0].size(),2)
ConsensusFeature::HandleSetType::const_iterator it = out[0].begin();
TEST_REAL_SIMILAR(it->getMZ(),1.0f);
TEST_REAL_SIMILAR(it->getRT(),1.0f);
++it;
TEST_REAL_SIMILAR(it->getMZ(),5.0f);
TEST_REAL_SIMILAR(it->getRT(),1.5f);
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/FeatureFileOptions_test.cpp | .cpp | 2,479 | 153 | // 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/OPTIONS/FeatureFileOptions.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(FeatureFileOptions, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
FeatureFileOptions* ptr = nullptr;
FeatureFileOptions* null_ptr = nullptr;
START_SECTION(FeatureFileOptions())
{
ptr = new FeatureFileOptions();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~FeatureFileOptions())
{
delete ptr;
}
END_SECTION
START_SECTION((void setIntensityRange(const DRange< 1 > &range)))
{
// TODO
}
END_SECTION
START_SECTION((bool hasIntensityRange() const ))
{
// TODO
}
END_SECTION
START_SECTION((const DRange<1>& getIntensityRange() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setLoadConvexHull(bool convex)))
{
// TODO
}
END_SECTION
START_SECTION((bool getLoadConvexHull() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setLoadSubordinates(bool sub)))
{
// TODO
}
END_SECTION
START_SECTION((bool getLoadSubordinates() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setMetadataOnly(bool only)))
{
// TODO
}
END_SECTION
START_SECTION((bool getMetadataOnly() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setSizeOnly(bool only)))
{
// TODO
}
END_SECTION
START_SECTION((bool getSizeOnly() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setRTRange(const DRange< 1 > &range)))
{
// TODO
}
END_SECTION
START_SECTION((bool hasRTRange() const ))
{
// TODO
}
END_SECTION
START_SECTION((const DRange<1>& getRTRange() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setMZRange(const DRange< 1 > &range)))
{
// TODO
}
END_SECTION
START_SECTION((bool hasMZRange() const ))
{
// TODO
}
END_SECTION
START_SECTION((const DRange<1>& getMZRange() const ))
{
// TODO
}
END_SECTION
START_SECTION((~FeatureFileOptions()))
{
// TODO
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MetaboliteSpectralMatching_test.cpp | .cpp | 1,412 | 63 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: $
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
///////////////////////////
#include <OpenMS/ANALYSIS/ID/MetaboliteSpectralMatching.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MetaboliteSpectralMatching, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MetaboliteSpectralMatching* ptr = nullptr;
MetaboliteSpectralMatching* null_ptr = nullptr;
START_SECTION(MetaboliteSpectralMatching())
{
ptr = new MetaboliteSpectralMatching();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~MetaboliteSpectralMatching())
{
delete ptr;
}
END_SECTION
START_SECTION((virtual ~MetaboliteSpectralMatching()))
{
// TODO
}
END_SECTION
START_SECTION((double computeHyperScore(MSSpectrum, MSSpectrum, const double &, const double &)))
{
// TODO
}
END_SECTION
START_SECTION((void run(PeakMap &, MzTab &)))
{
// TODO
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ElutionModelFitter_test.cpp | .cpp | 2,891 | 90 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FEATUREFINDER/ElutionModelFitter.h>
#include <OpenMS/FORMAT/FeatureXMLFile.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(ElutionModelFitter, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
ElutionModelFitter* ptr = nullptr;
ElutionModelFitter* null_ptr = nullptr;
START_SECTION((ElutionModelFitter()))
{
ptr = new ElutionModelFitter();
TEST_NOT_EQUAL(ptr, null_ptr);
}
END_SECTION
START_SECTION((~ElutionModelFitter()))
{
delete ptr;
}
END_SECTION
START_SECTION((void fitElutionModels(FeatureMap& features)))
{
ElutionModelFitter emf;
FeatureMap features;
// test if exception is thrown on empty featuremap
TEST_EXCEPTION(Exception::MissingInformation, emf.fitElutionModels(features));
FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("ElutionModelFitter_test.featureXML"), features);
ABORT_IF(features.size() != 25);
// symmetric model (default):
emf.fitElutionModels(features);
TEST_EQUAL(features.size(), 25);
for (FeatureMap::ConstIterator it = features.begin(); it != features.end();
++it)
{
TEST_EQUAL(it->metaValueExists("model_area"), true);
TEST_EQUAL(it->metaValueExists("model_status"), true);
TEST_EQUAL(it->metaValueExists("raw_intensity"), true);
TEST_NOT_EQUAL(it->getIntensity(), it->getMetaValue("raw_intensity"));
TEST_EQUAL(it->metaValueExists("model_Gauss_sigma"), true);
}
FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("ElutionModelFitter_test.featureXML"), features);
ABORT_IF(features.size() != 25);
// asymmetric model:
Param params;
params.setValue("asymmetric", "true");
emf.setParameters(params);
emf.fitElutionModels(features);
TEST_EQUAL(features.size(), 25);
for (FeatureMap::ConstIterator it = features.begin(); it != features.end();
++it)
{
TEST_EQUAL(it->metaValueExists("model_area"), true);
TEST_EQUAL(it->metaValueExists("model_status"), true);
TEST_EQUAL(it->metaValueExists("raw_intensity"), true);
TEST_NOT_EQUAL(it->getIntensity(), it->getMetaValue("raw_intensity"));
TEST_EQUAL(it->metaValueExists("model_EGH_tau"), true);
TEST_EQUAL(it->metaValueExists("model_EGH_sigma"), true);
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/EnzymaticDigestion_test.cpp | .cpp | 24,431 | 527 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Marc Sturm, Chris Bielow, Jeremi Maciejewski $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <OpenMS/DATASTRUCTURES/StringView.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <vector>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(EnzymaticDigestion, "$Id$")
/////////////////////////////////////////////////////////////
EnzymaticDigestion* ed_ptr = nullptr;
EnzymaticDigestion* ed_null = nullptr;
START_SECTION((EnzymaticDigestion()))
ed_ptr = new EnzymaticDigestion;
TEST_NOT_EQUAL(ed_ptr, ed_null)
END_SECTION
START_SECTION([EXTRA] virtual ~EnzymaticDigestion())
delete ed_ptr;
NOT_TESTABLE
END_SECTION
START_SECTION(([EXTRA] EnzymaticDigestion(const EnzymaticDigestion& rhs)))
EnzymaticDigestion ed;
ed.setMissedCleavages(1234);
ed.setEnzyme(ProteaseDB::getInstance()->getEnzyme("no cleavage"));
ed.setSpecificity(EnzymaticDigestion::SPEC_SEMI);
EnzymaticDigestion ed2(ed);
TEST_EQUAL(ed.getMissedCleavages(), ed2.getMissedCleavages());
TEST_EQUAL(ed.getEnzymeName(), ed2.getEnzymeName());
TEST_EQUAL(ed.getSpecificity(), ed2.getSpecificity());
END_SECTION
START_SECTION(([EXTRA] EnzymaticDigestion(const EnzymaticDigestion& rhs)))
EnzymaticDigestion ed;
ed.setMissedCleavages(1234);
ed.setEnzyme(ProteaseDB::getInstance()->getEnzyme("no cleavage"));
ed.setSpecificity(EnzymaticDigestion::SPEC_SEMI);
EnzymaticDigestion ed2(ed);
TEST_EQUAL(ed.getMissedCleavages(), ed2.getMissedCleavages());
TEST_EQUAL(ed.getEnzymeName(), ed2.getEnzymeName());
TEST_EQUAL(ed.getSpecificity(), ed2.getSpecificity());
END_SECTION
START_SECTION((Size getMissedCleavages() const))
TEST_EQUAL(EnzymaticDigestion().getMissedCleavages(), 0)
END_SECTION
START_SECTION((String getEnzymeName() const))
TEST_EQUAL(EnzymaticDigestion().getEnzymeName(), "Trypsin")
END_SECTION
START_SECTION((void setMissedCleavages(Size missed_cleavages)))
EnzymaticDigestion ed;
ed.setMissedCleavages(5);
TEST_EQUAL(ed.getMissedCleavages(), 5)
END_SECTION
START_SECTION((void setEnzyme(const DigestionEnzyme* enzyme)))
EnzymaticDigestion ed;
ed.setEnzyme(ProteaseDB::getInstance()->getEnzyme("Trypsin/P"));
TEST_EQUAL(ed.getEnzymeName(), "Trypsin/P");
END_SECTION
START_SECTION((Specificity getSpecificity() const))
EnzymaticDigestion ed;
TEST_EQUAL(ed.getSpecificity(), EnzymaticDigestion::SPEC_FULL);
ed.setSpecificity(EnzymaticDigestion::SPEC_NONE);
TEST_EQUAL(ed.getSpecificity(), EnzymaticDigestion::SPEC_NONE);
ed.setSpecificity(EnzymaticDigestion::SPEC_SEMI);
TEST_EQUAL(ed.getSpecificity(), EnzymaticDigestion::SPEC_SEMI);
END_SECTION
START_SECTION((void setSpecificity(Specificity spec)))
NOT_TESTABLE // tested above
END_SECTION
START_SECTION((static Specificity getSpecificityByName(const String& name)))
TEST_EQUAL(EnzymaticDigestion::getSpecificityByName(EnzymaticDigestion::NamesOfSpecificity[2]), EnzymaticDigestion::SPEC_FULL);
TEST_EQUAL(EnzymaticDigestion::getSpecificityByName(EnzymaticDigestion::NamesOfSpecificity[1]), EnzymaticDigestion::SPEC_SEMI);
TEST_EQUAL(EnzymaticDigestion::getSpecificityByName(EnzymaticDigestion::NamesOfSpecificity[0]), EnzymaticDigestion::SPEC_NONE);
TEST_EQUAL(EnzymaticDigestion::getSpecificityByName("DoesNotExist"), EnzymaticDigestion::SPEC_UNKNOWN);
END_SECTION
START_SECTION((Size digestUnmodified(const StringView sequence, std::vector<StringView>& output, Size min_length, Size max_length)))
{
EnzymaticDigestion ed;
vector<StringView> out;
// end without cutting site
std::string s = "ACDE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 1)
TEST_EQUAL(out[0].getString(), s)
// end with cutting site
s = "ACDEK";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 1)
TEST_EQUAL(out[0].getString(), "ACDEK")
s = "ACKDE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 2)
TEST_EQUAL(out[0].getString(), "ACK")
TEST_EQUAL(out[1].getString(), "DE")
s = "ACRDE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 2)
TEST_EQUAL(out[0].getString(), "ACR")
TEST_EQUAL(out[1].getString(), "DE")
s = "ACKPDE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 1)
TEST_EQUAL(out[0].getString(), "ACKPDE")
s = "ACRPDE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 1)
TEST_EQUAL(out[0].getString(), "ACRPDE")
s = "ARCRDRE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 4)
TEST_EQUAL(out[0].getString(), "AR")
TEST_EQUAL(out[1].getString(), "CR")
TEST_EQUAL(out[2].getString(), "DR")
TEST_EQUAL(out[3].getString(), "E")
s = "RKR";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 3)
TEST_EQUAL(out[0].getString(), "R")
TEST_EQUAL(out[1].getString(), "K")
TEST_EQUAL(out[2].getString(), "R")
ed.setMissedCleavages(1);
s = "ACDE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 1)
TEST_EQUAL(out[0].getString(), "ACDE")
s = "ACRDE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 3)
TEST_EQUAL(out[0].getString(), "ACR")
TEST_EQUAL(out[1].getString(), "DE")
TEST_EQUAL(out[2].getString(), "ACRDE")
s = "ARCDRE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 5)
TEST_EQUAL(out[0].getString(), "AR")
TEST_EQUAL(out[1].getString(), "CDR")
TEST_EQUAL(out[2].getString(), "E")
TEST_EQUAL(out[3].getString(), "ARCDR")
TEST_EQUAL(out[4].getString(), "CDRE")
s = "ARCDRER";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 5)
TEST_EQUAL(out[0].getString(), "AR")
TEST_EQUAL(out[1].getString(), "CDR")
TEST_EQUAL(out[2].getString(), "ER")
TEST_EQUAL(out[3].getString(), "ARCDR")
TEST_EQUAL(out[4].getString(), "CDRER")
s = "RKR";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 5)
TEST_EQUAL(out[0].getString(), "R")
TEST_EQUAL(out[1].getString(), "K")
TEST_EQUAL(out[2].getString(), "R")
TEST_EQUAL(out[3].getString(), "RK")
TEST_EQUAL(out[4].getString(), "KR")
s = "(ICPL:2H(4))ARCDRE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 5)
TEST_EQUAL(out[0].getString(), "(ICPL:2H(4))AR")
TEST_EQUAL(out[1].getString(), "CDR")
TEST_EQUAL(out[2].getString(), "E")
TEST_EQUAL(out[3].getString(), "(ICPL:2H(4))ARCDR")
TEST_EQUAL(out[4].getString(), "CDRE")
s = "ARCDRE(Amidated)";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 5)
TEST_EQUAL(out[0].getString(), "AR")
TEST_EQUAL(out[1].getString(), "CDR")
TEST_EQUAL(out[2].getString(), "E(Amidated)")
TEST_EQUAL(out[3].getString(), "ARCDR")
TEST_EQUAL(out[4].getString(), "CDRE(Amidated)")
ed.setMissedCleavages(2);
s = "RKR";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 6)
TEST_EQUAL(out[0].getString(), "R")
TEST_EQUAL(out[1].getString(), "K")
TEST_EQUAL(out[2].getString(), "R")
TEST_EQUAL(out[3].getString(), "RK")
TEST_EQUAL(out[4].getString(), "KR")
TEST_EQUAL(out[5].getString(), "RKR")
// min size
ed.digestUnmodified(s, out, 2);
TEST_EQUAL(out.size(), 3)
TEST_EQUAL(out[0].getString(), "RK")
TEST_EQUAL(out[1].getString(), "KR")
TEST_EQUAL(out[2].getString(), "RKR")
ed.digestUnmodified(s, out, 3);
TEST_EQUAL(out.size(), 1)
TEST_EQUAL(out[0].getString(), "RKR")
// max size
ed.digestUnmodified(s, out, 2,2);
TEST_EQUAL(out.size(), 2)
TEST_EQUAL(out[0].getString(), "RK")
TEST_EQUAL(out[1].getString(), "KR")
// ------------------------
// Trypsin/P
// ------------------------
ed.setMissedCleavages(0);
ed.setEnzyme(ProteaseDB::getInstance()->getEnzyme("Trypsin/P"));
s = "ACKPDE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 2)
TEST_EQUAL(out[0].getString(), "ACK")
TEST_EQUAL(out[1].getString(), "PDE")
s = "ACRPDE";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 2)
TEST_EQUAL(out[0].getString(), "ACR")
TEST_EQUAL(out[1].getString(), "PDE")
// ------------------------
// unspecific cleavage
// ------------------------
s = "ABCDEFGHIJ";
ed.setEnzyme(ProteaseDB::getInstance()->getEnzyme("unspecific cleavage"));
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 11 * 10 / 2)
// digest with min/max length
ed.digestUnmodified(s, out, 5, 6);
for (auto & a : out)
{
TEST_EQUAL(a.getString().size() == 5
|| a.getString().size() == 6, true)
}
s = "ABC";
ed.digestUnmodified(s, out);
TEST_EQUAL(out.size(), 4 * 3 / 2);
}
END_SECTION
START_SECTION((Size semiSpecificDigestion_(const std::vector<int>& cleavage_positions, std::vector<std::pair<Size, Size>>& output, Size min_length, Size max_length) const))
{
class TempChild : public EnzymaticDigestion
{
public:
Size tmpSemiSpecificDigestion_(const std::vector<int>& cleavage_positions, std::vector<std::pair<Size, Size>>& output, Size min_length = 1, Size max_length = 100) const
{
return this->semiSpecificDigestion_(cleavage_positions, output, min_length, max_length);
}
};
TempChild tmp;
tmp.setEnzyme(ProteaseDB::getInstance()->getEnzyme("Trypsin"));
std::vector<std::pair<size_t,size_t>> output = {};
// Test normal behaviour
std::vector<int> cleavage_positions = {0, 3, 5};
tmp.tmpSemiSpecificDigestion_(cleavage_positions, output);
TEST_EQUAL(output.size(), 6) // {1,3},{3,4},{2,3},{0,2},{4,5},{0,1}
// Test too few cleavage sites exception
cleavage_positions = {};
TEST_EXCEPTION(Exception::InvalidValue,
tmp.tmpSemiSpecificDigestion_(cleavage_positions, output));
// Test cleavage positions vector not sorted exception
cleavage_positions = {0, 12, 7};
TEST_EXCEPTION(Exception::Precondition,
tmp.tmpSemiSpecificDigestion_(cleavage_positions, output));
}
END_SECTION
START_SECTION((bool isValidProduct(const String& sequence, int pos, int length, bool ignore_missed_cleavages)))
{
EnzymaticDigestion ed;
ed.setEnzyme(ProteaseDB::getInstance()->getEnzyme("Trypsin"));
ed.setSpecificity(EnzymaticDigestion::SPEC_FULL); // require both sides
String prot = "ABCDEFGKABCRAAAKAARPBBBB";
TEST_EQUAL(ed.isValidProduct(prot, 100, 3), false); // invalid position
TEST_EQUAL(ed.isValidProduct(prot, 10, 300), false); // invalid length
TEST_EQUAL(ed.isValidProduct(prot, 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct("", 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct(prot, 0, 3), false); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, 8), true); // valid N-term
TEST_EQUAL(ed.isValidProduct(prot, 8, 4), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 8, 8), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 0, 19), false); // invalid C-term - followed by proline
TEST_EQUAL(ed.isValidProduct(prot, 8, 3), false); // invalid C-term
TEST_EQUAL(ed.isValidProduct(prot, 3, 6), false); // invalid C+N-term
TEST_EQUAL(ed.isValidProduct(prot, 1, 7), false); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, prot.size()), true); // the whole thing
//################################################
// same as above, just with other specificity
ed.setSpecificity(EnzymaticDigestion::SPEC_SEMI); // require one special cleavage site
TEST_EQUAL(ed.isValidProduct(prot, 100, 3), false); // invalid position
TEST_EQUAL(ed.isValidProduct(prot, 10, 300), false); // invalid length
TEST_EQUAL(ed.isValidProduct(prot, 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct("", 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct(prot, 0, 3), true); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, 8), true); // valid N-term
TEST_EQUAL(ed.isValidProduct(prot, 8, 4), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 8, 8), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 0, 19), true); // invalid C-term - followed by proline
TEST_EQUAL(ed.isValidProduct(prot, 8, 3), true); // invalid C-term
TEST_EQUAL(ed.isValidProduct(prot, 3, 6), false); // invalid C+N-term
TEST_EQUAL(ed.isValidProduct(prot, 1, 7), true); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, prot.size()), true); // the whole thing
//################################################
// same as above, just with other specificity
ed.setSpecificity(EnzymaticDigestion::SPEC_NONE); // require no special cleavage site
TEST_EQUAL(ed.isValidProduct(prot, 100, 3), false); // invalid position
TEST_EQUAL(ed.isValidProduct(prot, 10, 300), false); // invalid length
TEST_EQUAL(ed.isValidProduct(prot, 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct("", 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct(prot, 0, 3), true); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, 8), true); // valid N-term
TEST_EQUAL(ed.isValidProduct(prot, 8, 4), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 8, 8), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 0, 19), true); // invalid C-term - followed by proline
TEST_EQUAL(ed.isValidProduct(prot, 8, 3), true); // invalid C-term
TEST_EQUAL(ed.isValidProduct(prot, 3, 6), true); // invalid C+N-term
TEST_EQUAL(ed.isValidProduct(prot, 1, 7), true); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, prot.size()), true); // the whole thing
// ------------------------
// Trypsin/P
// ------------------------
ed.setEnzyme(ProteaseDB::getInstance()->getEnzyme("Trypsin/P"));
ed.setSpecificity(EnzymaticDigestion::SPEC_FULL); // require both sides
TEST_EQUAL(ed.isValidProduct(prot, 100, 3), false); // invalid position
TEST_EQUAL(ed.isValidProduct(prot, 10, 300), false); // invalid length
TEST_EQUAL(ed.isValidProduct(prot, 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct("", 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct(prot, 0, 3), false); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, 8), true); // valid N-term
TEST_EQUAL(ed.isValidProduct(prot, 8, 4), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 8, 8), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 0, 19), true); // valid C-term - followed by proline
TEST_EQUAL(ed.isValidProduct(prot, 8, 3), false); // invalid C-term
TEST_EQUAL(ed.isValidProduct(prot, 3, 6), false); // invalid C+N-term
TEST_EQUAL(ed.isValidProduct(prot, 1, 7), false); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, prot.size()), true); // the whole thing
// test with different missed cleavages when this is not ignored (ignore_missed_cleavages = false)
// |8 |12 |16|19
prot = "ABCDEFGKABCRAAAKAARPBBBB"; // 4 cleavages at {(0),8,12,16,19}
ed.setMissedCleavages(0); // redundant, by default zero, should be zero
TEST_EQUAL(ed.isValidProduct(prot, 8, 4, false), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 8, 8, false), false); // invalid, fully-tryptic but with a missing cleavage
ed.setMissedCleavages(1);
TEST_EQUAL(ed.isValidProduct(prot, 8, 8, false), true); // valid, fully-tryptic with 1 missing cleavage (allow)
TEST_EQUAL(ed.isValidProduct(prot, 8, 11, false), false);// invalid, fully-tryptic but with 2 missing cleavages
ed.setMissedCleavages(2);
TEST_EQUAL(ed.isValidProduct(prot, 8, 11, false), true); // valid, fully-tryptic with 2 missing cleavages
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, true), true); // boundary case, length of protein (no checking of MCs)
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), false);// boundary case, this exceeds missing cleavages
TEST_EQUAL(ed.isValidProduct(prot, 0, 19, false), false);// start-boundary case, 2 allowed, 3 required
ed.setMissedCleavages(3);
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), false);// boundary case, invalid: 3 allowed, 4 required
TEST_EQUAL(ed.isValidProduct(prot, 0, 19, false), true); // start-boundary case, 3 allowed, 3 required
ed.setMissedCleavages(4); // maximum cleavages for this peptide
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), true); // boundary case, accepted: 4 allowed, 4 required
TEST_EQUAL(ed.isValidProduct(prot, 0, 19, false), true); // start-boundary case, 4 allowed, 3 required
ed.setMissedCleavages(5); // allow even more ...
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), true); // boundary case, accepted: 5 allowed, 4 required
ed.setMissedCleavages(0); // set back to default
//################################################
// same as above, just with other specificity
ed.setSpecificity(EnzymaticDigestion::SPEC_SEMI); // require one special cleavage site
TEST_EQUAL(ed.isValidProduct(prot, 100, 3), false); // invalid position
TEST_EQUAL(ed.isValidProduct(prot, 10, 300), false); // invalid length
TEST_EQUAL(ed.isValidProduct(prot, 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct("", 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct(prot, 0, 3), true); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, 8), true); // valid N-term
TEST_EQUAL(ed.isValidProduct(prot, 8, 4), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 8, 8), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 0, 19), true); // valid C-term - followed by proline
TEST_EQUAL(ed.isValidProduct(prot, 8, 3), true); // invalid C-term
TEST_EQUAL(ed.isValidProduct(prot, 3, 6), false); // invalid C+N-term
TEST_EQUAL(ed.isValidProduct(prot, 1, 7), true); // invalid N-term valid C-term
TEST_EQUAL(ed.isValidProduct(prot, 0, prot.size()), true); // the whole thing
// test with different missed cleavages when this is not ignored (ignore_missed_cleavages = false)
// |8 |12 |16|19
prot = "ABCDEFGKABCRAAAKAARPBBBB"; // 4 cleavages at {(0),8,12,16,19}
ed.setMissedCleavages(0); // redundant, by default zero, should be zero
TEST_EQUAL(ed.isValidProduct(prot, 8, 3, false), true); // valid semi-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 8, 5, false), false); // invalid, semi-tryptic but with a missing cleavage
ed.setMissedCleavages(1);
TEST_EQUAL(ed.isValidProduct(prot, 8, 5, false), true); // valid, semi-tryptic with 1 missing cleavage (allow)
TEST_EQUAL(ed.isValidProduct(prot, 8, 10, false), false);// invalid, semi-tryptic but with 2 missing cleavages
ed.setMissedCleavages(2);
TEST_EQUAL(ed.isValidProduct(prot, 8, 10, false), true); // valid, semi-tryptic with 2 missing cleavages
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, true), true); // boundary case, length of protein (no checking of MCs)
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), false);// boundary case, this exceeds missing cleavages
TEST_EQUAL(ed.isValidProduct(prot, 0, 18, false), false);// start-boundary case, 2 allowed, 3 required
ed.setMissedCleavages(3);
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), false);// boundary case, invalid: 3 allowed, 4 required
TEST_EQUAL(ed.isValidProduct(prot, 0, 18, false), true); // start-boundary case, 3 allowed, 3 required
ed.setMissedCleavages(4); // maximum cleavages for this peptide
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), true); // boundary case, accepted: 4 allowed, 4 required
TEST_EQUAL(ed.isValidProduct(prot, 0, 18, false), true); // start-boundary case, 4 allowed, 3 required
ed.setMissedCleavages(5); // allow even more ...
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), true); // boundary case, accepted: 5 allowed, 4 required
ed.setMissedCleavages(0); // set back to default
//################################################
// same as above, just with other specificity
ed.setSpecificity(EnzymaticDigestion::SPEC_NONE); // require no special cleavage site
TEST_EQUAL(ed.isValidProduct(prot, 100, 3), false); // invalid position
TEST_EQUAL(ed.isValidProduct(prot, 10, 300), false); // invalid length
TEST_EQUAL(ed.isValidProduct(prot, 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct("", 10, 0), false); // invalid size
TEST_EQUAL(ed.isValidProduct(prot, 0, 3), true); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, 8), true); // valid N-term
TEST_EQUAL(ed.isValidProduct(prot, 8, 4), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 8, 8), true); // valid fully-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 0, 19), true); // valid C-term - followed by proline
TEST_EQUAL(ed.isValidProduct(prot, 8, 3), true); // invalid C-term
TEST_EQUAL(ed.isValidProduct(prot, 3, 6), true); // invalid C+N-term
TEST_EQUAL(ed.isValidProduct(prot, 1, 7), true); // invalid N-term
TEST_EQUAL(ed.isValidProduct(prot, 0, prot.size()), true); // the whole thing
// test with different missed cleavages when this is not ignored (ignore_missed_cleavages = false)
// |8 |12 |16|19
prot = "ABCDEFGKABCRAAAKAARPBBBB"; // 4 cleavages at {(0),8,12,16,19}
ed.setMissedCleavages(0); // redundant, by default zero, should be zero
TEST_EQUAL(ed.isValidProduct(prot, 9, 2, false), true); // valid not-tryptic
TEST_EQUAL(ed.isValidProduct(prot, 9, 5, false), false); // invalid, not-tryptic but with a missing cleavage
ed.setMissedCleavages(1);
TEST_EQUAL(ed.isValidProduct(prot, 9, 5, false), true); // valid, not-tryptic with 1 missing cleavage (allow)
TEST_EQUAL(ed.isValidProduct(prot, 9, 9, false), false); // invalid, semi-tryptic but with 2 missing cleavages
ed.setMissedCleavages(2);
TEST_EQUAL(ed.isValidProduct(prot, 9, 9, false), true); // valid, semi-tryptic with 2 missing cleavages
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, true), true); // boundary case, length of protein (no checking of MCs)
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), false);// boundary case, this exceeds missing cleavages
ed.setMissedCleavages(3);
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), false);// boundary case, invalid: 3 allowed, 4 required
ed.setMissedCleavages(4); // maximum cleavages for this peptide
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), true); // boundary case, accepted: 4 allowed, 4 required
ed.setMissedCleavages(5); // allow even more ...
TEST_EQUAL(ed.isValidProduct(prot, 0, 24, false), true); // boundary case, accepted: 5 allowed, 4 required
ed.setMissedCleavages(0); // set back to default
}
END_SECTION
START_SECTION([EXTRA] Size countMissedCleavages_(const std::vector<int>& cleavage_positions, Size pep_start, Size pep_end) const)
EnzymaticDigestion ed;
ed.setMissedCleavages(2);
TEST_EQUAL(ed.isValidProduct("KKKK", 0, 4, false), false); // has 3 MC's, should not be valid
ed.setMissedCleavages(3);
TEST_EQUAL(ed.isValidProduct("KKKK", 0, 4, false), true); // has 3 MC's, should be valid
END_SECTION
START_SECTION(Size countInternalCleavageSites(const String& sequence) )
EnzymaticDigestion ed;
ed.setMissedCleavages(0); // setting max missed cleavages should not have any impact
TEST_EQUAL(ed.countInternalCleavageSites("PEEKEEKEEPKEEPK"), 3); // has 3 internal cleavage sites
ed.setMissedCleavages(2);
TEST_EQUAL(ed.countInternalCleavageSites("PEEKEEKEEPKEEPK"), 3); // has 3 internal cleavage sites
TEST_EQUAL(ed.countInternalCleavageSites("EEEEEEEEEEEEEEE"), 0); // has 0 internal cleavage sites
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/NonNegativeLeastSquaresSolver_test.cpp | .cpp | 2,321 | 98 | // 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/ML/NNLS/NonNegativeLeastSquaresSolver.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(NonNegativeLeastSquaresSolver, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
NonNegativeLeastSquaresSolver* ptr = nullptr;
NonNegativeLeastSquaresSolver* nullPointer = nullptr;
START_SECTION(NonNegativeLeastSquaresSolver())
{
ptr = new NonNegativeLeastSquaresSolver();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~NonNegativeLeastSquaresSolver())
{
delete ptr;
}
END_SECTION
START_SECTION((static Int solve(const Matrix< double > &A, const Matrix< double > &b, Matrix< double > &x)))
{
// CASE 1
double A_1[3][4] =
{
{1, 10, 4, 10},
{4, 5 , 1, 12},
{5, 1 , 9, 20},
};
double b_1[3][1] = {{4},{7},{4}};
double x_1[4][1] = {{0.931153},{0.36833},{0},{0}};
Matrix<double> A,b,x;
A.setMatrix<double,3,4>(A_1);
b.setMatrix<double,3,1>(b_1);
x.resize(4,1);
TOLERANCE_ABSOLUTE(0.0005);
NonNegativeLeastSquaresSolver::solve(A,b,x);
for (Size i = 0; i < x.rows(); ++i)
{
TEST_REAL_SIMILAR(x(i,0), x_1[i][0]);
}
// CASE 2
double A_2[4][4] =
{
{0.9290, 0.0200, 0, 0},
{0.0590, 0.9230, 0.0300, 0.0010},
{0.0020, 0.0560, 0.9240, 0.0400},
{ 0, 0.0010, 0.0450, 0.9240}
};
double b_2[4][1] = {{5},{45},{4},{31}};
double x_2[4][1] = {{4.3395},{48.4364},{0},{33.4945}};
A.setMatrix<double,4,4>(A_2);
b.setMatrix<double,4,1>(b_2);
x.resize(4,1);
NonNegativeLeastSquaresSolver::solve(A,b,x);
for (Size i = 0; i < x.rows(); ++i)
{
TEST_REAL_SIMILAR(x(i,0), x_2[i][0]);
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/TIC_test.cpp | .cpp | 3,175 | 116 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow$
// $Authors: Tom Waschischeck $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/QC/TIC.h>
///////////////////////////
START_TEST(TIC, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
TIC* ptr = nullptr;
TIC* nullPointer = nullptr;
START_SECTION(TIC())
ptr = new TIC();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~TIC())
delete ptr;
END_SECTION
TIC tic;
START_SECTION(const String& getName() const override)
TEST_EQUAL(tic.getName(), "TIC")
END_SECTION
START_SECTION(Status requirements() const override)
TEST_EQUAL((tic.requirements() == QCBase::Status(QCBase::Requires::RAWMZML)), true);
END_SECTION
START_SECTION(void compute(const MSExperiment& exp, float bin_size))
// build an experiment with a few MS1 spectra to verify the computed TIC metrics
MSExperiment exp;
{
MSSpectrum spec;
spec.setMSLevel(1);
spec.setRT(0.5);
spec.emplace_back(100.0, 30.0f);
spec.emplace_back(150.0, 70.0f);
exp.addSpectrum(spec);
}
{
MSSpectrum spec;
spec.setMSLevel(1);
spec.setRT(1.0);
spec.emplace_back(200.0, 500.0f);
spec.emplace_back(250.0, 2000.0f);
exp.addSpectrum(spec);
}
{
MSSpectrum spec;
spec.setMSLevel(1);
spec.setRT(1.5);
spec.emplace_back(300.0, 5.0f);
spec.emplace_back(350.0, 15.0f);
exp.addSpectrum(spec);
}
{
MSSpectrum spec;
spec.setMSLevel(1);
spec.setRT(2.0);
spec.emplace_back(400.0, 1000.0f);
spec.emplace_back(450.0, 3000.0f);
exp.addSpectrum(spec);
}
TIC::Result result = tic.compute(exp, 0);
TEST_EQUAL(result.intensities.size(), 4);
TEST_EQUAL(result.retention_times.size(), 4);
TEST_EQUAL(result.relative_intensities.size(), 4);
TEST_EQUAL(result.intensities[0], 100);
TEST_EQUAL(result.intensities[1], 2500);
TEST_EQUAL(result.intensities[2], 20);
TEST_EQUAL(result.intensities[3], 4000);
TEST_REAL_SIMILAR(result.relative_intensities[0], 2.5);
TEST_REAL_SIMILAR(result.relative_intensities[1], 62.5);
TEST_REAL_SIMILAR(result.relative_intensities[2], 0.5);
TEST_REAL_SIMILAR(result.relative_intensities[3], 100.0);
TEST_REAL_SIMILAR(result.retention_times[0], 0.5);
TEST_REAL_SIMILAR(result.retention_times[1], 1.0);
TEST_REAL_SIMILAR(result.retention_times[2], 1.5);
TEST_REAL_SIMILAR(result.retention_times[3], 2.0);
TEST_EQUAL(result.area, 6620);
TEST_EQUAL(result.jump, 2);
TEST_EQUAL(result.fall, 1);
// empty experiment still yields an empty result
MSExperiment empty_exp;
TEST_EQUAL(tic.compute(empty_exp, 0) == TIC::Result(), true)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Exception_Base_test.cpp | .cpp | 1,592 | 64 | // 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>
///////////////////////////
using namespace OpenMS;
START_TEST(Exception::Base, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
Exception::BaseException* e_ptr = nullptr;
Exception::BaseException* e_nullPointer = nullptr;
START_SECTION(Base() )
e_ptr = new Exception::BaseException;
TEST_NOT_EQUAL(e_ptr, e_nullPointer)
END_SECTION
START_SECTION(~Base() )
delete e_ptr;
END_SECTION
START_SECTION(Base(const Base& exception) )
// ???
END_SECTION
START_SECTION((Base(const char* file, int line, const char* function) ))
// ???
END_SECTION
START_SECTION((Base(const char* file, int line, const char* function, const std::string& name, const std::string& message) ))
// ???
END_SECTION
START_SECTION(const char* getFile() const )
// ???
END_SECTION
START_SECTION(const char* getName() const )
// ???
END_SECTION
START_SECTION(const char* what() const )
// ???
END_SECTION
START_SECTION(int getLine() const )
// ???
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Peak1D_test.cpp | .cpp | 10,541 | 384 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/KERNEL/Peak1D.h>
#include <unordered_set>
#include <unordered_map>
///////////////////////////
START_TEST(Peak1D, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
Peak1D* d10_ptr = nullptr;
Peak1D* d10_nullPointer = nullptr;
static_assert(std::is_trivially_destructible<Peak1D> {});
// static_assert(std::is_trivially_default_constructible<Peak1D> {});
static_assert(std::is_trivially_copy_constructible<Peak1D> {});
static_assert(std::is_trivially_copy_assignable<Peak1D> {});
static_assert(std::is_trivially_move_constructible<Peak1D> {});
static_assert(std::is_nothrow_move_constructible<Peak1D> {});
static_assert(std::is_trivially_move_assignable<Peak1D> {});
START_SECTION((Peak1D()))
d10_ptr = new Peak1D;
TEST_NOT_EQUAL(d10_ptr, d10_nullPointer)
END_SECTION
START_SECTION((~Peak1D()))
delete d10_ptr;
END_SECTION
START_SECTION((IntensityType getIntensity() const))
TEST_REAL_SIMILAR(Peak1D().getIntensity(), 0.0)
END_SECTION
START_SECTION((PositionType const& getPosition() const))
TEST_REAL_SIMILAR(Peak1D().getPosition()[0], 0.0)
END_SECTION
START_SECTION((CoordinateType getMZ() const))
TEST_REAL_SIMILAR(Peak1D().getMZ(), 0.0)
END_SECTION
START_SECTION((CoordinateType getPos() const))
TEST_REAL_SIMILAR(Peak1D().getPos(), 0.0)
END_SECTION
START_SECTION((void setIntensity(IntensityType intensity)))
Peak1D p;
p.setIntensity(17.8f);
TEST_REAL_SIMILAR(p.getIntensity(), 17.8)
END_SECTION
START_SECTION((void setPosition(PositionType const &position)))
Peak1D::PositionType pos;
pos[0] = 1.0;
Peak1D p;
p.setPosition(pos);
TEST_REAL_SIMILAR(p.getPosition()[0], 1.0)
END_SECTION
START_SECTION((PositionType& getPosition()))
Peak1D::PositionType pos;
pos[0] = 1.0;
Peak1D p;
p.getPosition() = pos;
TEST_REAL_SIMILAR(p.getPosition()[0], 1.0)
END_SECTION
START_SECTION((void setMZ(CoordinateTypemz)))
Peak1D p;
p.setMZ(5.0);
TEST_REAL_SIMILAR(p.getMZ(), 5.0)
END_SECTION
START_SECTION((void setPos(CoordinateTypepos)))
Peak1D p;
p.setPos(5.0);
TEST_REAL_SIMILAR(p.getPos(), 5.0)
END_SECTION
START_SECTION((Peak1D(const Peak1D& p)))
Peak1D::PositionType pos;
pos[0] = 21.21;
Peak1D p;
p.setIntensity(123.456f);
p.setPosition(pos);
Peak1D::PositionType pos2;
Peak1D::IntensityType i2;
Peak1D copy_of_p(p);
i2 = copy_of_p.getIntensity();
pos2 = copy_of_p.getPosition();
TEST_REAL_SIMILAR(i2, 123.456)
TEST_REAL_SIMILAR(pos2[0], 21.21)
END_SECTION
START_SECTION((Peak1D& operator = (const Peak1D& rhs)))
Peak1D::PositionType pos;
pos[0] = 21.21;
Peak1D p;
p.setIntensity(123.456f);
p.setPosition(pos);
Peak1D::PositionType pos2;
Peak1D::IntensityType i2;
Peak1D copy_of_p;
copy_of_p = p;
i2 = copy_of_p.getIntensity();
pos2 = copy_of_p.getPosition();
TEST_REAL_SIMILAR(i2, 123.456)
TEST_REAL_SIMILAR(pos2[0], 21.21)
END_SECTION
START_SECTION((bool operator == (const Peak1D& rhs) const))
Peak1D p1;
Peak1D p2(p1);
TEST_TRUE(p1 == p2)
p1.setIntensity(5.0f);
TEST_EQUAL(p1==p2, false)
p2.setIntensity(5.0f);
TEST_TRUE(p1 == p2)
p1.getPosition()[0]=5;
TEST_EQUAL(p1==p2, false)
p2.getPosition()[0]=5;
TEST_TRUE(p1 == p2)
END_SECTION
START_SECTION((bool operator != (const Peak1D& rhs) const))
Peak1D p1;
Peak1D p2(p1);
TEST_EQUAL(p1!=p2, false)
p1.setIntensity(5.0f);
TEST_FALSE(p1 == p2)
p2.setIntensity(5.0f);
TEST_EQUAL(p1!=p2, false)
p1.getPosition()[0]=5;
TEST_FALSE(p1 == p2)
p2.getPosition()[0]=5;
TEST_EQUAL(p1!=p2, false)
END_SECTION
/////////////////////////////////////////////////////////////
// Nested stuff
/////////////////////////////////////////////////////////////
Peak1D p1;
p1.setIntensity(10.0);
p1.setMZ(10.0);
Peak1D p2;
p2.setIntensity(12.0);
p2.setMZ(12.0);
// IntensityLess
START_SECTION(([Peak1D::IntensityLess] bool operator()(Peak1D const &left, Peak1D const &right) const))
std::vector<Peak1D > v;
Peak1D p;
p.setIntensity(2.5f);
v.push_back(p);
p.setIntensity(3.5f);
v.push_back(p);
p.setIntensity(1.5f);
v.push_back(p);
std::sort(v.begin(), v.end(), Peak1D::IntensityLess());
TEST_REAL_SIMILAR(v[0].getIntensity(), 1.5)
TEST_REAL_SIMILAR(v[1].getIntensity(), 2.5)
TEST_REAL_SIMILAR(v[2].getIntensity(), 3.5)
v[0]=v[2];
v[2]=p;
std::sort(v.begin(), v.end(), Peak1D::IntensityLess());
TEST_REAL_SIMILAR(v[0].getIntensity(), 1.5)
TEST_REAL_SIMILAR(v[1].getIntensity(), 2.5)
TEST_REAL_SIMILAR(v[2].getIntensity(), 3.5)
// some more
TEST_EQUAL(Peak1D::IntensityLess()(p1,p2), true)
TEST_EQUAL(Peak1D::IntensityLess()(p2,p1), false)
TEST_EQUAL(Peak1D::IntensityLess()(p2,p2), false)
END_SECTION
START_SECTION(([Peak1D::IntensityLess] bool operator()(Peak1D const &left, IntensityType right) const))
TEST_EQUAL(Peak1D::IntensityLess()(p1,p2.getIntensity()), true)
TEST_EQUAL(Peak1D::IntensityLess()(p2,p1.getIntensity()), false)
TEST_EQUAL(Peak1D::IntensityLess()(p2,p2.getIntensity()), false)
END_SECTION
START_SECTION(([Peak1D::IntensityLess] bool operator()(IntensityType left, Peak1D const &right) const))
TEST_EQUAL(Peak1D::IntensityLess()(p1.getIntensity(),p2), true)
TEST_EQUAL(Peak1D::IntensityLess()(p2.getIntensity(),p1), false)
TEST_EQUAL(Peak1D::IntensityLess()(p2.getIntensity(),p2), false)
END_SECTION
START_SECTION(([Peak1D::IntensityLess] bool operator()(IntensityType left, IntensityType right) const))
TEST_EQUAL(Peak1D::IntensityLess()(p1.getIntensity(),p2.getIntensity()), true)
TEST_EQUAL(Peak1D::IntensityLess()(p2.getIntensity(),p1.getIntensity()), false)
TEST_EQUAL(Peak1D::IntensityLess()(p2.getIntensity(),p2.getIntensity()), false)
END_SECTION
// MZLess
START_SECTION(([Peak1D::MZLess] bool operator()(const Peak1D &left, const Peak1D &right) const))
std::vector<Peak1D > v;
Peak1D p;
p.setMZ(3.0);
v.push_back(p);
p.setMZ(2.0);
v.push_back(p);
p.setMZ(1.0);
v.push_back(p);
std::sort(v.begin(), v.end(), Peak1D::MZLess());
TEST_REAL_SIMILAR(v[0].getPosition()[0], 1.0)
TEST_REAL_SIMILAR(v[1].getPosition()[0], 2.0)
TEST_REAL_SIMILAR(v[2].getPosition()[0], 3.0)
//
TEST_EQUAL(Peak1D::MZLess()(p1,p2), true)
TEST_EQUAL(Peak1D::MZLess()(p2,p1), false)
TEST_EQUAL(Peak1D::MZLess()(p2,p2), false)
END_SECTION
START_SECTION(([Peak1D::MZLess] bool operator()(Peak1D const &left, CoordinateType right) const))
TEST_EQUAL(Peak1D::MZLess()(p1,p2.getMZ()), true)
TEST_EQUAL(Peak1D::MZLess()(p2,p1.getMZ()), false)
TEST_EQUAL(Peak1D::MZLess()(p2,p2.getMZ()), false)
END_SECTION
START_SECTION(([Peak1D::MZLess] bool operator()(CoordinateType left, Peak1D const &right) const))
TEST_EQUAL(Peak1D::MZLess()(p1.getMZ(),p2), true)
TEST_EQUAL(Peak1D::MZLess()(p2.getMZ(),p1), false)
TEST_EQUAL(Peak1D::MZLess()(p2.getMZ(),p2), false)
END_SECTION
START_SECTION(([Peak1D::MZLess] bool operator()(CoordinateType left, CoordinateType right) const))
TEST_EQUAL(Peak1D::MZLess()(p1.getMZ(),p2.getMZ()), true)
TEST_EQUAL(Peak1D::MZLess()(p2.getMZ(),p1.getMZ()), false)
TEST_EQUAL(Peak1D::MZLess()(p2.getMZ(),p2.getMZ()), false)
END_SECTION
// PositionLess
START_SECTION(([Peak1D::PositionLess] bool operator()(const Peak1D &left, const Peak1D &right) const))
std::vector<Peak1D > v;
Peak1D p;
p.getPosition()[0]=3.0;
v.push_back(p);
p.getPosition()[0]=2.0;
v.push_back(p);
p.getPosition()[0]=1.0;
v.push_back(p);
std::sort(v.begin(), v.end(), Peak1D::PositionLess());
TEST_REAL_SIMILAR(v[0].getPosition()[0], 1.0)
TEST_REAL_SIMILAR(v[1].getPosition()[0], 2.0)
TEST_REAL_SIMILAR(v[2].getPosition()[0], 3.0)
//
TEST_EQUAL(Peak1D::PositionLess()(p1,p2), true)
TEST_EQUAL(Peak1D::PositionLess()(p2,p1), false)
TEST_EQUAL(Peak1D::PositionLess()(p2,p2), false)
END_SECTION
START_SECTION(([Peak1D::PositionLess] bool operator()(const Peak1D &left, const PositionType &right) const))
TEST_EQUAL(Peak1D::PositionLess()(p1,p2.getPosition()), true)
TEST_EQUAL(Peak1D::PositionLess()(p2,p1.getPosition()), false)
TEST_EQUAL(Peak1D::PositionLess()(p2,p2.getPosition()), false)
END_SECTION
START_SECTION(([Peak1D::PositionLess] bool operator()(const PositionType &left, const Peak1D &right) const))
TEST_EQUAL(Peak1D::PositionLess()(p1.getPosition(),p2), true)
TEST_EQUAL(Peak1D::PositionLess()(p2.getPosition(),p1), false)
TEST_EQUAL(Peak1D::PositionLess()(p2.getPosition(),p2), false)
END_SECTION
START_SECTION(([Peak1D::PositionLess] bool operator()(const PositionType &left, const PositionType &right) const))
TEST_EQUAL(Peak1D::PositionLess()(p1.getPosition(),p2.getPosition()), true)
TEST_EQUAL(Peak1D::PositionLess()(p2.getPosition(),p1.getPosition()), false)
TEST_EQUAL(Peak1D::PositionLess()(p2.getPosition(),p2.getPosition()), false)
END_SECTION
/////////////////////////////////////////////////////////////
// Hash function tests
/////////////////////////////////////////////////////////////
START_SECTION(([EXTRA] std::hash<Peak1D>))
{
// Test that equal peaks have equal hashes
Peak1D p1, p2;
p1.setMZ(100.5);
p1.setIntensity(1000.0f);
p2.setMZ(100.5);
p2.setIntensity(1000.0f);
std::hash<Peak1D> hasher;
TEST_EQUAL(hasher(p1), hasher(p2))
// Test that hash changes when values change
Peak1D p3;
p3.setMZ(200.5);
p3.setIntensity(1000.0f);
TEST_NOT_EQUAL(hasher(p1), hasher(p3))
// Test use in unordered_set
std::unordered_set<Peak1D> peak_set;
peak_set.insert(p1);
TEST_EQUAL(peak_set.size(), 1)
peak_set.insert(p2); // same as p1
TEST_EQUAL(peak_set.size(), 1) // should not increase
peak_set.insert(p3);
TEST_EQUAL(peak_set.size(), 2)
// Test use in unordered_map
std::unordered_map<Peak1D, int> peak_map;
peak_map[p1] = 42;
TEST_EQUAL(peak_map[p1], 42)
TEST_EQUAL(peak_map[p2], 42) // p2 == p1, should get same value
peak_map[p3] = 99;
TEST_EQUAL(peak_map[p3], 99)
TEST_EQUAL(peak_map.size(), 2)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/DocumentIdentifier_test.cpp | .cpp | 4,207 | 147 | // 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/METADATA/DocumentIdentifier.h>
#include <OpenMS/FORMAT/FileTypes.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(DocumentIdentifier, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
DocumentIdentifier* ptr = nullptr;
DocumentIdentifier* nullPointer = nullptr;
START_SECTION(DocumentIdentifier())
{
ptr = new DocumentIdentifier();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~DocumentIdentifier())
{
delete ptr;
}
END_SECTION
START_SECTION((DocumentIdentifier(const DocumentIdentifier &source)))
{
DocumentIdentifier di1;
di1.setIdentifier("this is a test");
di1.setLoadedFilePath( OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"));
di1.setLoadedFileType( OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"));
DocumentIdentifier di2(di1);
TEST_EQUAL(di2.getIdentifier(), "this is a test");
TEST_EQUAL(di2.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"))
TEST_EQUAL(FileTypes::typeToName(di2.getLoadedFileType()) == "unknown", true)
}
END_SECTION
START_SECTION((DocumentIdentifier& operator=(const DocumentIdentifier &source)))
{
DocumentIdentifier di1;
di1.setIdentifier("this is a test");
di1.setLoadedFilePath( OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"));
di1.setLoadedFileType( OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"));
DocumentIdentifier di2 = di1;
TEST_EQUAL(di2.getIdentifier(), "this is a test");
TEST_EQUAL(di2.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"))
TEST_EQUAL(FileTypes::typeToName(di2.getLoadedFileType()) == "unknown", true)
}
END_SECTION
START_SECTION((bool operator==(const DocumentIdentifier &rhs) const))
{
DocumentIdentifier di1;
di1.setIdentifier("this is a test");
DocumentIdentifier di2(di1);
TEST_TRUE(di1 == di2)
}
END_SECTION
START_SECTION((void setIdentifier(const String &id)))
{
DocumentIdentifier di1;
di1.setIdentifier("this is a test");
TEST_EQUAL(di1.getIdentifier(), "this is a test")
}
END_SECTION
START_SECTION((const String& getIdentifier() const))
{
// tested above
NOT_TESTABLE
}
END_SECTION
START_SECTION((void setLoadedFileType(const String &file_name)))
{
DocumentIdentifier di1;
di1.setLoadedFileType( OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"));
TEST_EQUAL(FileTypes::typeToName(di1.getLoadedFileType()), "unknown")
}
END_SECTION
START_SECTION((const FileTypes::Type& getLoadedFileType() const))
{
// tested above
NOT_TESTABLE
}
END_SECTION
START_SECTION((void setLoadedFilePath(const String &file_name)))
{
DocumentIdentifier di1;
di1.setLoadedFilePath( OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"));
TEST_EQUAL(di1.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"))
}
END_SECTION
START_SECTION((const String& getLoadedFilePath() const))
{
// tested above
NOT_TESTABLE
}
END_SECTION
START_SECTION((void swap(DocumentIdentifier& from)))
{
DocumentIdentifier di1;
di1.setIdentifier("this is a test");
di1.setLoadedFilePath( OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"));
di1.setLoadedFileType( OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"));
DocumentIdentifier di2;
di1.swap(di2);
TEST_EQUAL(di1.getIdentifier().empty(), true)
TEST_EQUAL(di1.getIdentifier().empty(), true)
TEST_EQUAL(di1.getIdentifier().empty(), true)
TEST_EQUAL(di2.getIdentifier() == "this is a test", true)
TEST_EQUAL(di2.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("File_test_empty.txt"))
TEST_EQUAL(FileTypes::typeToName(di2.getLoadedFileType()) == "unknown", true)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/GumbelDistributionFitter_test.cpp | .cpp | 6,613 | 188 | // 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/CsvFile.h>
///////////////////////////
#include <OpenMS/MATH/STATISTICS/GumbelDistributionFitter.h>
#include <OpenMS/MATH/STATISTICS/GumbelMaxLikelihoodFitter.h>
///////////////////////////
using namespace OpenMS;
using namespace Math;
using namespace std;
START_TEST(GumbelDistributionFitter, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
GumbelDistributionFitter* ptr = nullptr;
GumbelDistributionFitter* nullPointer = nullptr;
START_SECTION(GumbelDistributionFitter())
ptr = new GumbelDistributionFitter();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~GumbelDistributionFitter()))
delete ptr;
NOT_TESTABLE
END_SECTION
START_SECTION((GumbelDistributionFitResult fit(std::vector<DPosition<2> >& points)))
DPosition<2> pos;
vector<DPosition<2> > points;
pos.setX(-2.7); pos.setY(0.017); points.push_back(pos);
pos.setX(-2.5); pos.setY(0.025); points.push_back(pos);
pos.setX(-2); pos.setY(0.052); points.push_back(pos);
pos.setX(-1); pos.setY(0.127); points.push_back(pos);
pos.setX(-0.7); pos.setY(0.147); points.push_back(pos);
pos.setX(-0.01); pos.setY(0.178); points.push_back(pos);
pos.setX(0); pos.setY(0.178); points.push_back(pos);
pos.setX(0.2); pos.setY(0.182); points.push_back(pos);
pos.setX(0.5); pos.setY(0.184); points.push_back(pos);
pos.setX(1); pos.setY(0.179); points.push_back(pos);
pos.setX(1.3); pos.setY(0.171); points.push_back(pos);
pos.setX(1.9); pos.setY(0.151); points.push_back(pos);
pos.setX(2.5); pos.setY(0.127); points.push_back(pos);
pos.setX(2.6); pos.setY(0.123); points.push_back(pos);
pos.setX(2.7); pos.setY(0.119); points.push_back(pos);
pos.setX(2.8); pos.setY(0.115); points.push_back(pos);
pos.setX(2.9); pos.setY(0.111); points.push_back(pos);
pos.setX(3); pos.setY(0.108); points.push_back(pos);
pos.setX(3.5); pos.setY(0.089); points.push_back(pos);
pos.setX(3.9); pos.setY(0.076); points.push_back(pos);
pos.setX(4.01); pos.setY(0.073); points.push_back(pos);
pos.setX(4.22); pos.setY(0.067); points.push_back(pos);
pos.setX(4.7); pos.setY(0.054); points.push_back(pos);
pos.setX(4.9); pos.setY(0.05); points.push_back(pos);
pos.setX(5); pos.setY(0.047); points.push_back(pos);
pos.setX(6); pos.setY(0.03); points.push_back(pos);
pos.setX(7); pos.setY(0.017); points.push_back(pos);
pos.setX(7.5); pos.setY(0.015); points.push_back(pos);
pos.setX(7.9); pos.setY(0.012); points.push_back(pos);
pos.setX(8.03); pos.setY(0.011); points.push_back(pos);
//a= 0.5, b = 2
ptr = new GumbelDistributionFitter;
GumbelDistributionFitter::GumbelDistributionFitResult init_param;
init_param.a = 1.0;
init_param.b = 3.0;
ptr->setInitialParameters(init_param);
GumbelDistributionFitter::GumbelDistributionFitResult result = ptr->fit(points);
TOLERANCE_ABSOLUTE(0.1)
TEST_REAL_SIMILAR(result.a, 0.5)
TEST_REAL_SIMILAR(result.b, 2.0)
vector<DPosition<2> > points2;
pos.setX(0); pos.setY(0.18); points2.push_back(pos);
pos.setX(0.2); pos.setY(0.24); points2.push_back(pos);
pos.setX(0.5); pos.setY(0.32); points2.push_back(pos);
pos.setX(1); pos.setY(0.37); points2.push_back(pos);
pos.setX(1.3); pos.setY(0.35); points2.push_back(pos);
pos.setX(1.9); pos.setY(0.27); points2.push_back(pos);
pos.setX(2.5); pos.setY(0.18); points2.push_back(pos);
pos.setX(2.6); pos.setY(0.16); points2.push_back(pos);
pos.setX(3); pos.setY(0.12); points2.push_back(pos);
pos.setX(5); pos.setY(0.02); points2.push_back(pos);
//a = 1, b = 1
init_param.a = 3.0;
init_param.b = 3.0;
ptr->setInitialParameters(init_param);
GumbelDistributionFitter::GumbelDistributionFitResult result2 = ptr->fit(points2);
TOLERANCE_ABSOLUTE(0.1)
TEST_REAL_SIMILAR(result2.a, 1.0)
TEST_REAL_SIMILAR(result2.b, 1.0)
delete ptr;
END_SECTION
START_SECTION((void setInitialParameters(const GumbelDistributionFitResult& result)))
{
GumbelDistributionFitter f1;
GumbelDistributionFitter::GumbelDistributionFitResult result;
f1.setInitialParameters(result);
NOT_TESTABLE //implicitly tested in fit method
}
END_SECTION
START_SECTION((GumbelDistributionFitter(const GumbelDistributionFitter& rhs)))
NOT_TESTABLE
END_SECTION
START_SECTION((GumbelDistributionFitter& operator = (const GumbelDistributionFitter& rhs)))
NOT_TESTABLE
END_SECTION
GumbelDistributionFitter::GumbelDistributionFitResult* p = nullptr;
START_SECTION((GumbelDistributionFitter::GumbelDistributionFitResult()))
p = new GumbelDistributionFitter::GumbelDistributionFitResult;
TEST_NOT_EQUAL(ptr, nullPointer)
TEST_REAL_SIMILAR(p->a, 1.0)
TEST_REAL_SIMILAR(p->b, 2.0)
END_SECTION
START_SECTION((GumbelDistributionFitter::GumbelDistributionFitResult(const GumbelDistributionFitter::GumbelDistributionFitResult& rhs)))
p-> a = 5.0;
p->b = 4.0;
GumbelDistributionFitter::GumbelDistributionFitResult obj(*p);
TEST_REAL_SIMILAR(obj.a, 5.0)
TEST_REAL_SIMILAR(obj.b, 4.0)
END_SECTION
START_SECTION((GumbelDistributionFitter::GumbelDistributionFitResult& operator = (const GumbelDistributionFitter::GumbelDistributionFitResult& rhs)))
p-> a = 3.0;
p->b = 2.2;
GumbelDistributionFitter::GumbelDistributionFitResult obj = *p;
TEST_REAL_SIMILAR(obj.a, 3.0)
TEST_REAL_SIMILAR(obj.b, 2.2)
delete p;
END_SECTION
START_SECTION(MLE)
vector<double> rand_score_vector;
CsvFile gumbeldata (OPENMS_GET_TEST_DATA_PATH("Gumbel_1D.csv"));
StringList gumbeldata_strings;
gumbeldata.getRow(0, gumbeldata_strings);
// Load mixture of Gumbel and Gaussian (1D) from provided csv
for (StringList::const_iterator it = gumbeldata_strings.begin(); it != gumbeldata_strings.end(); ++it)
{
if(!it->empty())
{
rand_score_vector.push_back(it->toDouble());
}
}
vector<double> w (rand_score_vector.size(),1.0);
TEST_EQUAL(rand_score_vector.size(),1200)
GumbelMaxLikelihoodFitter gmlf({4.0,2.0});
auto res = gmlf.fitWeighted(rand_score_vector, w);
TEST_REAL_SIMILAR(res.a, 2)
TEST_REAL_SIMILAR(res.b, 0.6)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/LinearInterpolation_test.cpp | .cpp | 15,390 | 582 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
///////////////////////////
// This one is going to be tested.
#include <OpenMS/ML/INTERPOLATION/LinearInterpolation.h>
///////////////////////////
// More headers
#include <iostream>
#include <iterator>
#include <vector>
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/DATASTRUCTURES/ListUtilsIO.h>
#include <OpenMS/test_config.h>
#include <OpenMS/MATH/MathFunctions.h>
///////////////////////////
using namespace OpenMS;
using namespace OpenMS::Math;
/////////////////////////////////////////////////////////////
START_TEST( LinearInterpolation, "$Id$" )
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION([EXTRA] typedefs )
{
typedef LinearInterpolation < float, double > LIFD;
LIFD::ValueType * value = new LIFD::ValueType();
LIFD::KeyType * key = new LIFD::KeyType();
LIFD::ContainerType * container = new LIFD::ContainerType();
LIFD::ContainerType::value_type * containerValue = new LIFD::ContainerType::value_type();
LIFD::ValueType * nullValue = nullptr;
LIFD::KeyType * nullKey = nullptr;
LIFD::ContainerType * nullContainer = nullptr;
LIFD::ContainerType::value_type * nullContainerValue = nullptr;
TEST_NOT_EQUAL(value, nullValue)
TEST_NOT_EQUAL(key, nullKey)
TEST_NOT_EQUAL(container, nullContainer)
TEST_NOT_EQUAL(containerValue, nullContainerValue)
delete value;
delete key;
delete container;
delete containerValue;
delete nullValue;
delete nullKey;
delete nullContainer;
delete nullContainerValue;
}
END_SECTION
typedef LinearInterpolation < float, double > LIFD;
//-----------------------------------------------------------
// Without these extra parens, check_test will not recognize this test...
START_SECTION((LinearInterpolation(KeyType scale=1., KeyType offset=0.)))
{
LIFD lifd0;
LIFD lifd1 ( 1.125 );
LIFD lifd2 ( 1.125, 3.5 );
TEST_EQUAL ( lifd0.getScale(), 1 );
TEST_EQUAL ( lifd0.getOffset(), 0 );
TEST_EQUAL ( lifd1.getScale(), 1.125 );
TEST_EQUAL ( lifd1.getOffset(), 0 );
TEST_EQUAL ( lifd2.getScale(), 1.125 );
TEST_EQUAL ( lifd2.getOffset(), 3.5 );
}
END_SECTION
LIFD * lifd_nullPointer = nullptr;
START_SECTION(~LinearInterpolation())
{
LIFD * lifd_ptr = nullptr;
lifd_ptr = new LIFD;
TEST_NOT_EQUAL(lifd_ptr,lifd_nullPointer);
delete lifd_ptr;
}
END_SECTION
START_SECTION(ContainerType const& getData() const )
{
LIFD lifd;
std::vector < LIFD::ValueType > v;
v.push_back(17);
v.push_back(18.9);
v.push_back(20.333);
v.push_back(-.1);
lifd.setData(v);
TEST_EQUAL(lifd.getData().size(),v.size());
for ( UInt i = 0; i < v.size(); ++i )
TEST_EQUAL(lifd.getData()[i],v[i]);
}
END_SECTION
START_SECTION(template< typename SourceContainer > void setData( SourceContainer const & data ) )
{
// see above, getData()
NOT_TESTABLE;
}
END_SECTION
START_SECTION(ContainerType& getData() )
{
LIFD lifd;
std::vector < LIFD::ValueType > v;
v.push_back(17);
v.push_back(18.9);
v.push_back(20.333);
v.push_back(-.1);
lifd.setData(v);
LIFD const & lifd_cr = lifd;
TEST_EQUAL(lifd_cr.getData().size(),v.size());
for ( UInt i = 0; i < v.size(); ++i )
TEST_EQUAL(lifd_cr.getData()[i],v[i]);
}
END_SECTION
START_SECTION(bool empty() const )
{
LIFD lifd;
TEST_EQUAL(lifd.getData().empty(),true);
lifd.getData().push_back(3);
TEST_EQUAL(lifd.getData().empty(),false);
lifd.getData().push_back(3);
TEST_EQUAL(lifd.getData().empty(),false);
lifd.getData().push_back(3);
TEST_EQUAL(lifd.getData().empty(),false);
lifd.getData().clear();
TEST_EQUAL(lifd.getData().empty(),true);
}
END_SECTION
START_SECTION((void setMapping( KeyType const & scale, KeyType const & inside, KeyType const & outside )))
{
LIFD lifd;
lifd.setMapping( 13, 23, 53 );
TEST_REAL_SIMILAR(lifd.getScale(), 13)
TEST_REAL_SIMILAR(lifd.getInsideReferencePoint(), 23)
TEST_REAL_SIMILAR(lifd.getOutsideReferencePoint(), 53)
}
END_SECTION
START_SECTION(KeyType const& getScale() const )
{
LIFD lifd;
lifd.setMapping( 13, 23, 53 );
TEST_REAL_SIMILAR(lifd.getScale(), 13.F);
}
END_SECTION
START_SECTION(KeyType const& getInsideReferencePoint() const )
{
LIFD lifd;
lifd.setMapping( 13, 23, 53 );
TEST_REAL_SIMILAR(lifd.getInsideReferencePoint(), 23.F)
}
END_SECTION
START_SECTION(KeyType const& getOutsideReferencePoint() const )
{
LIFD lifd;
lifd.setMapping( 13, 23, 53 );
TEST_REAL_SIMILAR(lifd.getOutsideReferencePoint(), 53.F)
}
END_SECTION
START_SECTION(void setScale( KeyType const & scale ) )
{
LIFD lifd;
lifd.setMapping( 13, 23, 53 );
TEST_REAL_SIMILAR(lifd.getScale(), 13.f);
lifd.setScale(88.88f);
TEST_REAL_SIMILAR(lifd.getScale(), 88.88f);
}
END_SECTION
START_SECTION(KeyType const& getOffset() const )
{
LIFD lifd ( 1.125, 3.5 );
TEST_EQUAL ( lifd.getOffset(), 3.5f );
}
END_SECTION
START_SECTION(void setOffset( KeyType const & offset ) )
{
LIFD lifd ( 1.125, 3.5 );
TEST_EQUAL ( lifd.getOffset(), 3.5f );
lifd.setOffset(88.88f);
TEST_EQUAL ( lifd.getOffset(), 88.88f );
}
END_SECTION
START_SECTION((void setMapping( KeyType const & inside_low, KeyType const & outside_low, KeyType const & inside_high, KeyType const & outside_high )))
{
LIFD lifd;
lifd.setMapping( 13, 130, 14, 140 );
TEST_REAL_SIMILAR(lifd.getScale(), 10)
TEST_REAL_SIMILAR(lifd.getInsideReferencePoint(), 13)
TEST_REAL_SIMILAR(lifd.getOutsideReferencePoint(), 130)
}
END_SECTION
START_SECTION(LinearInterpolation( LinearInterpolation const & arg ))
{
LIFD lifd;
lifd.setMapping( 13, 130, 14, 140 );
LIFD::ContainerType v;
v.push_back(17);
v.push_back(18.9);
v.push_back(20.333);
v.push_back(-.1);
lifd.setData(v);
LIFD lifd2 = lifd;
TEST_REAL_SIMILAR(lifd2.getScale(), 10);
TEST_REAL_SIMILAR(lifd2.getInsideReferencePoint(), 13);
TEST_REAL_SIMILAR(lifd2.getOutsideReferencePoint(), 130);
for ( UInt i = 0; i < v.size(); ++i )
TEST_EQUAL(lifd2.getData()[i],v[i]);
}
END_SECTION
START_SECTION(LinearInterpolation& operator= ( LinearInterpolation const & arg ))
{
LIFD lifd;
lifd.setMapping( 13, 130, 14, 140 );
LIFD::ContainerType v;
v.push_back(17);
v.push_back(18.9);
v.push_back(20.333);
v.push_back(-.1);
lifd.setData(v);
LIFD lifd2;
lifd2 = lifd;
TEST_REAL_SIMILAR(lifd2.getScale(), 10);
TEST_REAL_SIMILAR(lifd2.getInsideReferencePoint(), 13);
TEST_REAL_SIMILAR(lifd2.getOutsideReferencePoint(), 130);
for ( UInt i = 0; i < v.size(); ++i )
TEST_EQUAL(lifd2.getData()[i],v[i]);
}
END_SECTION
START_SECTION(KeyType index2key( KeyType pos ) const )
{
LIFD lifd(100,3456);
TEST_REAL_SIMILAR(lifd.index2key(0),3456);
TEST_REAL_SIMILAR(lifd.index2key(-1),3356);
TEST_REAL_SIMILAR(lifd.index2key(1),3556);
}
END_SECTION
START_SECTION(KeyType key2index( KeyType pos ) const )
{
LIFD lifd(100,3456);
TEST_REAL_SIMILAR(lifd.key2index(3456),0);
TEST_REAL_SIMILAR(lifd.key2index(3356),-1);
TEST_REAL_SIMILAR(lifd.key2index(3556),1);
lifd.setScale(0);
TEST_REAL_SIMILAR(lifd.key2index(3456),0);
TEST_REAL_SIMILAR(lifd.key2index(3356),0);
TEST_REAL_SIMILAR(lifd.key2index(3556),0);
}
END_SECTION
START_SECTION(KeyType supportMin() const )
{
LIFD lifd ( 1.125, 3.5 );
TEST_REAL_SIMILAR ( lifd.supportMin(), 3.5 );
lifd.getData().push_back(11111);
TEST_REAL_SIMILAR ( lifd.supportMin(), 3.5-1.125 );
lifd.getData().push_back(99999);
TEST_REAL_SIMILAR ( lifd.supportMin(), 3.5-1.125 );
lifd.getData().clear();
TEST_REAL_SIMILAR ( lifd.supportMin(), 3.5 );
}
END_SECTION
START_SECTION(KeyType supportMax() const )
{
LIFD lifd ( 1.125, 3.5 );
TEST_REAL_SIMILAR ( lifd.supportMax(), 3.5 );
lifd.getData().push_back(11111);
TEST_REAL_SIMILAR ( lifd.supportMax(), 3.5+1.125 );
lifd.getData().push_back(99999);
TEST_REAL_SIMILAR ( lifd.supportMax(), 3.5+2*1.125 );
lifd.getData().clear();
TEST_REAL_SIMILAR ( lifd.supportMax(), 3.5 );
}
END_SECTION
//-----------------------------------------------------------
START_SECTION(ValueType value( KeyType arg_pos ) const )
{
LIFD lifd0;
double values[] = { 1, 2, 0, 1 };
int const num_values = sizeof (values) / sizeof (*values);
std::copy ( values, values + num_values, std::back_inserter ( lifd0.getData() ) );
TEST_EQUAL ( (int) lifd0.getData().size(), num_values );
for ( int i = 0; i < num_values; ++i )
{
TEST_EQUAL ( lifd0.value ( LIFD::KeyType(i) ), values[i] );
}
double inter_values[] =
{ 0, 0.00, 0.00, 0.00,
0, 0.25, 0.50, 0.75,
1, 1.25, 1.50, 1.75,
2, 1.50, 1.00, 0.50,
0, 0.25, 0.50, 0.75,
1, 0.75, 0.50, 0.25,
0, 0.00, 0.00, 0.00,
0
};
for ( int i = 0; i < num_values+4; ++i )
{
TEST_REAL_SIMILAR ( lifd0.value ( i-2.f ), inter_values[4*i] );
}
int const num_inter_values = sizeof (inter_values) / sizeof (*inter_values);
for ( int i = 0; i < num_inter_values; ++i )
{
TEST_REAL_SIMILAR ( lifd0.value ( (i-8.f)/4.f ), inter_values[i] );
}
LIFD lifd1 (lifd0);
float const scale = 1;
float const offset = 100;
lifd1.setScale( scale );
lifd1.setOffset( offset );
for ( int i = -8; i < num_inter_values-8; ++i )
{
float pos = i/4.f;
TEST_REAL_SIMILAR ( lifd1.key2index(lifd1.index2key(pos)), pos );
}
for ( int i = -8; i < num_inter_values-8; ++i )
{
float pos = i/4.f;
TEST_REAL_SIMILAR ( lifd1.value ( pos*scale+offset ), lifd0.value ( pos ) ) ;
}
{
TOLERANCE_ABSOLUTE(0.001);
LIFD lifd_small;
lifd_small.getData().resize(5,0);
lifd_small.setMapping( 0, 0, 5, 5 );
LIFD lifd_big;
lifd_big.getData().resize(15,0);
lifd_big.setMapping( 5, 0, 10, 5 );
for ( int i = 0; i < 5; ++i )
{
lifd_small.getData()[i] = lifd_big.getData()[i+5] = i * 25 + 100;
}
STATUS(" " << lifd_small.getData());
STATUS(lifd_big.getData());
for ( int i = -50; i <= 100; ++i )
{
float pos = i / 10.f;
STATUS(i);
TEST_REAL_SIMILAR(lifd_small.value(pos),lifd_big.value(pos));
}
}
}
END_SECTION
//-----------------------------------------------------------
START_SECTION(ValueType derivative( KeyType arg_pos ) const )
{
typedef LinearInterpolation < float, double > LIFD;
LIFD lifd0;
double values[] = { 1, 2, 0, 1 };
int const num_values = sizeof (values) / sizeof (*values);
std::copy ( values, values + num_values, std::back_inserter ( lifd0.getData() ) );
TEST_EQUAL ( (int) lifd0.getData().size(), num_values );
for ( int i = 0; i < num_values; ++i )
{
TEST_EQUAL ( lifd0.value ( float(i) ), values[i] );
}
double inter_values[] = // left .. (derivative) .. right
{ +0.00, 0.00, 0.00, 0.25, // 0 .. (0) .. 0
+0.50, 0.75, 1.00, 1.00, // 0 .. (1) .. 1
+1.00, 1.00, 1.00, 0.25, // 1 .. (1) .. 2
-0.50, -1.25, -2.00, -1.25, // 2 .. (-2) .. 0
-0.50, 0.25, 1.00, 0.50, // 0 .. (1) .. 1
+0.00, -0.50, -1.00, -0.75, // 1 .. (-1) .. 0
-0.50, -0.25, 0.00, 0.00, // 0 .. (0) .. 0
0
};
int const num_inter_values = sizeof (inter_values) / sizeof (*inter_values);
for ( int i = -8; i < num_inter_values-8; ++i )
{
float key = i/4.f;
int index = i+8;
STATUS( "key:" << key << " index:" << index << '\n')
TEST_REAL_SIMILAR ( lifd0.derivative ( key ), inter_values[index] );
}
}
END_SECTION
//-----------------------------------------------------------
START_SECTION((void addValue( KeyType arg_pos, ValueType arg_value ) ))
{
{
LinearInterpolation < double, double > lininterpol;
lininterpol.getData().resize(5);
lininterpol.addValue(2.3,10);
for ( UInt i = 0; i != lininterpol.getData().size(); ++i )
{
STATUS(i << ": " << lininterpol.getData()[i]);
}
TEST_REAL_SIMILAR(lininterpol.getData()[2],7);
TEST_REAL_SIMILAR(lininterpol.getData()[3],3);
}
{
LinearInterpolation < double, double > lininterpol;
lininterpol.getData().resize(5);
lininterpol.addValue(0.3,10);
for ( UInt i = 0; i != lininterpol.getData().size(); ++i )
{
STATUS(i << ": " << lininterpol.getData()[i]);
}
TEST_REAL_SIMILAR(lininterpol.getData()[0],7);
TEST_REAL_SIMILAR(lininterpol.getData()[1],3);
}
{
LinearInterpolation < double, double > lininterpol;
lininterpol.getData().resize(5);
lininterpol.addValue(-0.7,10);
for ( UInt i = 0; i != lininterpol.getData().size(); ++i )
{
STATUS(i << ": " << lininterpol.getData()[i]);
}
TEST_REAL_SIMILAR(lininterpol.getData()[0],3);
}
{
LinearInterpolation < double, double > lininterpol;
lininterpol.getData().resize(5);
lininterpol.addValue(-1.7,10);
for ( UInt i = 0; i != lininterpol.getData().size(); ++i )
{
STATUS(i << ": " << lininterpol.getData()[i]);
}
TEST_REAL_SIMILAR(lininterpol.getData()[0],0);
}
{
LinearInterpolation < double, double > lininterpol;
lininterpol.getData().resize(5);
lininterpol.addValue(3.3,10);
for ( UInt i = 0; i != lininterpol.getData().size(); ++i )
{
STATUS(i << ": " << lininterpol.getData()[i])
}
TEST_REAL_SIMILAR(lininterpol.getData()[3],7);
TEST_REAL_SIMILAR(lininterpol.getData()[4],3);
}
{
LinearInterpolation < double, double > lininterpol;
lininterpol.getData().resize(5);
lininterpol.addValue(4.3,10);
for ( UInt i = 0; i != lininterpol.getData().size(); ++i )
{
STATUS(i << ": " << lininterpol.getData()[i]);
}
TEST_REAL_SIMILAR(lininterpol.getData()[4],7);
}
{
LinearInterpolation < double, double > lininterpol;
lininterpol.getData().resize(5);
lininterpol.addValue(5.3,10);
for ( UInt i = 0; i != lininterpol.getData().size(); ++i )
{
STATUS(i << ": " << lininterpol.getData()[i]);
}
TEST_REAL_SIMILAR(lininterpol.getData()[4],0);
}
{
for ( int i = -50; i <= 100; ++i )
{
float pos = i / 10.f;
STATUS(i);
LIFD lifd_small;
lifd_small.getData().resize(5);
lifd_small.setMapping( 0, 0, 5, 5 );
lifd_small.addValue( pos, 10 );
for ( LIFD::ContainerType::iterator iter = lifd_small.getData().begin(); iter != lifd_small.getData().end(); ++ iter ) *iter = Math::round(*iter);
STATUS(" " << lifd_small.getData());
LIFD lifd_big;
lifd_big.getData().resize(15);
lifd_big.setMapping( 5, 0, 10, 5 );
lifd_big.addValue( pos, 10 );
for ( LIFD::ContainerType::iterator iter = lifd_big.getData().begin(); iter != lifd_big.getData().end(); ++ iter ) *iter = Math::round(*iter);
STATUS(lifd_big.getData());
std::vector < LIFD::ContainerType::value_type > big_infix ( lifd_big.getData().begin()+5, lifd_big.getData().begin()+10 );
TEST_EQUAL(lifd_small.getData().size(), big_infix.size())
ABORT_IF(lifd_small.getData().size() != big_infix.size())
// test in loop to avoid clang++ compiler error
LIFD::ContainerType::const_iterator lifd_it = lifd_small.getData().begin();
std::vector < LIFD::ContainerType::value_type >::const_iterator big_infix_it = big_infix.begin();
for( ; lifd_it != lifd_small.getData().end() && big_infix_it != big_infix.end() ; ++lifd_it , ++big_infix_it)
{
TEST_EQUAL(*lifd_it,*big_infix_it);
}
}
}
}
END_SECTION
//-----------------------------------------------------------
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MRMFeatureFinderScoring_test.cpp | .cpp | 17,231 | 376 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <memory>
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/FORMAT/TraMLFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h>
///////////////////////////
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
typedef std::map<String, MRMTransitionGroup< MSChromatogram, OpenSwath::LightTransition > > TransitionGroupMapType;
START_TEST(MRMFeatureFinderScoring, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MRMFeatureFinderScoring* ptr = nullptr;
MRMFeatureFinderScoring* nullPointer = nullptr;
START_SECTION(MRMFeatureFinderScoring())
{
ptr = new MRMFeatureFinderScoring();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~MRMFeatureFinderScoring())
{
delete ptr;
}
END_SECTION
START_SECTION(void pickExperiment(OpenSwath::SpectrumAccessPtr input, FeatureMap< Feature > &output, OpenSwath::LightTargetedExperiment &transition_exp, TransformationDescription trafo, OpenSwath::SpectrumAccessPtr swath_map, TransitionGroupMapType &transition_group_map))
{
MRMFeatureFinderScoring ff;
// Param picker_param = ff.getDefaults();
// picker_param.setValue("TransitionGroupPicker:PeakPickerChromatogram:method", "legacy"); // old parameters
// picker_param.setValue("TransitionGroupPicker:PeakPickerChromatogram:peak_width", 40.0); // old parameters
// ff.setParameters(picker_param);
MRMFeature feature;
FeatureMap featureFile;
TransformationDescription trafo;
std::shared_ptr<PeakMap> swath_map (new PeakMap);
TransitionGroupMapType transition_group_map;
MRMFeatureFinderScoring::MRMTransitionGroupType transition_group;
// Load the chromatograms (mzML) and the meta-information (TraML)
std::shared_ptr<PeakMap> exp (new PeakMap);
OpenSwath::LightTargetedExperiment transitions;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("OpenSwath_generic_input.mzML"), *exp);
{
TargetedExperiment transition_exp_;
TraMLFile().load(OPENMS_GET_TEST_DATA_PATH("OpenSwath_generic_input.TraML"), transition_exp_);
OpenSwathDataAccessHelper::convertTargetedExp(transition_exp_, transitions);
}
// Pick features in the experiment
#ifdef USE_SP_INTERFACE
OpenSwath::SpectrumAccessPtr swath_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_map);
OpenSwath::SpectrumAccessPtr chromatogram_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp);
std::vector< OpenSwath::SwathMap > swath_maps(1);
swath_maps[0].sptr = swath_ptr;
ff.pickExperiment(chromatogram_ptr, featureFile, transitions, trafo, swath_maps, transition_group_map);
#else
ff.pickExperiment(exp, featureFile, transitions, trafo, *swath_map, transition_group_map);
#endif
// Test the number of features found
TEST_EQUAL(transition_group_map.size(), 2)
///////////////////////////////////////////////////////////////////////////
//// Scores for the first group
transition_group = transition_group_map["tr_gr1"];
TEST_EQUAL(transition_group.size(), 2)
TEST_EQUAL(transition_group.getFeatures().size(), 1)
// Look closely at the feature we found in the first group
feature = transition_group.getFeatures()[0];
TOLERANCE_ABSOLUTE(0.1);
TEST_REAL_SIMILAR (feature.getRT(), 3119.092);
TEST_REAL_SIMILAR (feature.getIntensity(), 3615);
// feature attributes
TEST_REAL_SIMILAR(feature.getMetaValue("leftWidth" ), 3089.42993164062);
TEST_REAL_SIMILAR(feature.getMetaValue("rightWidth"), 3154.53002929688);
TEST_REAL_SIMILAR(feature.getMetaValue("total_xic"), 3680.16);
// feature scores
TEST_REAL_SIMILAR(feature.getMetaValue("var_xcorr_coelution"), 0);
TEST_REAL_SIMILAR(feature.getMetaValue("var_xcorr_shape"), 0.9981834605);
TEST_REAL_SIMILAR(feature.getMetaValue("var_library_rmsd"), 0.108663236);
TEST_REAL_SIMILAR(feature.getMetaValue("var_library_corr"), 1);
TEST_REAL_SIMILAR(feature.getMetaValue("var_elution_model_fit_score"), 0.9854);
TEST_REAL_SIMILAR(feature.getMetaValue("var_intensity_score"), 0.971);
TEST_REAL_SIMILAR(feature.getMetaValue("sn_ratio"), 86.0);
TEST_REAL_SIMILAR(feature.getMetaValue("var_log_sn_score"), 4.45439541136954);
TOLERANCE_RELATIVE(1.001);
TEST_REAL_SIMILAR(feature.getMetaValue("rt_score"), 3118.651968);
TOLERANCE_ABSOLUTE(0.1);
///////////////////////////////////////////////////////////////////////////
//// Scores for the second group
transition_group = transition_group_map["tr_gr2"];
TEST_EQUAL(transition_group.size(), 3)
TEST_EQUAL(transition_group.getFeatures().size(), 2)
TEST_EQUAL(featureFile.size(), 3)
// Look closely at the feature we found in the second group
feature = transition_group.getFeatures()[0];
TOLERANCE_ABSOLUTE(0.1);
TEST_REAL_SIMILAR(feature.getRT(), 3119.092);
TEST_REAL_SIMILAR(feature.getIntensity(), 1077.92);
// feature attributes
TEST_REAL_SIMILAR(feature.getMetaValue("leftWidth" ), 3092.85009765625);
TEST_REAL_SIMILAR(feature.getMetaValue("rightWidth"), 3151.10009765625);
TEST_REAL_SIMILAR(feature.getMetaValue("total_xic"), 1610.27);
// feature scores
TEST_REAL_SIMILAR(feature.getMetaValue("var_xcorr_coelution"), 5.70936);
TEST_REAL_SIMILAR(feature.getMetaValue("var_xcorr_shape"), 0.7245);
TEST_REAL_SIMILAR(feature.getMetaValue("var_library_rmsd"), 0.43566);
TEST_REAL_SIMILAR(feature.getMetaValue("var_library_corr"), -0.784);
TEST_REAL_SIMILAR(feature.getMetaValue("var_elution_model_fit_score"), 0.902);
TEST_REAL_SIMILAR(feature.getMetaValue("var_intensity_score"), 0.642);
TEST_REAL_SIMILAR(feature.getMetaValue("sn_ratio"), 30.18);
TEST_REAL_SIMILAR(feature.getMetaValue("var_log_sn_score"), 3.40718216971789);
// test legacy parameters
{
Param picker_param = ff.getDefaults();
picker_param.setValue("TransitionGroupPicker:PeakPickerChromatogram:method", "legacy"); // old parameters
picker_param.setValue("TransitionGroupPicker:PeakPickerChromatogram:peak_width", 40.0); // old parameters
ff.setParameters(picker_param);
transition_group_map.clear();
featureFile.clear();
// Pick features in the experiment
#ifdef USE_SP_INTERFACE
OpenSwath::SpectrumAccessPtr swath_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_map);
OpenSwath::SpectrumAccessPtr chromatogram_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp);
std::vector< OpenSwath::SwathMap > swath_maps(1);
swath_maps[0].sptr = swath_ptr;
ff.pickExperiment(chromatogram_ptr, featureFile, transitions, trafo, swath_maps, transition_group_map);
#else
ff.pickExperiment(exp, featureFile, transitions, trafo, *swath_map, transition_group_map);
#endif
///////////////////////////////////////////////////////////////////////////
//// Scores for the first group
transition_group = transition_group_map["tr_gr1"];
TEST_EQUAL(transition_group.size(), 2)
TEST_EQUAL(transition_group.getFeatures().size(), 1)
// Look closely at the feature we found in the first group
feature = transition_group.getFeatures()[0];
TOLERANCE_ABSOLUTE(0.1);
TEST_REAL_SIMILAR (feature.getRT(), 3119.092);
TEST_REAL_SIMILAR (feature.getIntensity(), 3574.23);
// feature attributes
TEST_REAL_SIMILAR(feature.getMetaValue("leftWidth" ), 3096.28);
TEST_REAL_SIMILAR(feature.getMetaValue("rightWidth"), 3147.68);
TEST_REAL_SIMILAR(feature.getMetaValue("total_xic"), 3680.16);
///////////////////////////////////////////////////////////////////////////
//// Scores for the second group
transition_group = transition_group_map["tr_gr2"];
TEST_EQUAL(transition_group.size(), 3)
TEST_EQUAL(transition_group.getFeatures().size(), 2)
TEST_EQUAL(featureFile.size(), 3)
// Look closely at the feature we found in the second group
feature = transition_group.getFeatures()[0];
TOLERANCE_ABSOLUTE(0.1);
TEST_REAL_SIMILAR(feature.getRT(), 3119.092);
TEST_REAL_SIMILAR(feature.getIntensity(), 1034.55);
// feature attributes
TEST_REAL_SIMILAR(feature.getMetaValue("leftWidth" ), 3099.7);
TEST_REAL_SIMILAR(feature.getMetaValue("rightWidth"), 3147.68);
TEST_REAL_SIMILAR(feature.getMetaValue("total_xic"), 1610.27);
TEST_REAL_SIMILAR(feature.getMetaValue("var_xcorr_coelution"), 2.265);
}
}
END_SECTION
START_SECTION(void pickExperiment(OpenSwath::SpectrumAccessPtr input, FeatureMap< Feature > &output, OpenSwath::LightTargetedExperiment &transition_exp, TransformationDescription trafo, OpenSwath::SpectrumAccessPtr swath_map, TransitionGroupMapType &transition_group_map))
{
MRMFeatureFinderScoring ff;
Param ff_param = MRMFeatureFinderScoring().getDefaults();
Param scores_to_use;
scores_to_use.setValue("use_uis_scores", "true", "Use UIS scores for peptidoform identification ", {"advanced"});
scores_to_use.setValidStrings("use_uis_scores", {"true","false"});
ff_param.insert("Scores:", scores_to_use);
ff_param.setValue("TransitionGroupPicker:PeakPickerChromatogram:method", "legacy"); // old parameters
ff_param.setValue("TransitionGroupPicker:PeakPickerChromatogram:peak_width", 40.0); // old parameters
ff.setParameters(ff_param);
MRMFeature feature;
FeatureMap featureFile;
TransformationDescription trafo;
std::shared_ptr<PeakMap> swath_map (new PeakMap);
TransitionGroupMapType transition_group_map;
// Load the chromatograms (mzML) and the meta-information (TraML)
std::shared_ptr<PeakMap> exp (new PeakMap);
OpenSwath::LightTargetedExperiment transitions;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("OpenSwath_generic_input.mzML"), *exp);
{
TargetedExperiment transition_exp_;
TraMLFile().load(OPENMS_GET_TEST_DATA_PATH("OpenSwath_identification_input.TraML"), transition_exp_);
OpenSwathDataAccessHelper::convertTargetedExp(transition_exp_, transitions);
}
// Pick features in the experiment
#ifdef USE_SP_INTERFACE
OpenSwath::SpectrumAccessPtr swath_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_map);
OpenSwath::SpectrumAccessPtr chromatogram_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp);
std::vector< OpenSwath::SwathMap > swath_maps(1);
swath_maps[0].sptr = swath_ptr;
ff.pickExperiment(chromatogram_ptr, featureFile, transitions, trafo, swath_maps, transition_group_map);
#else
ff.pickExperiment(exp, featureFile, transitions, trafo, *swath_map, transition_group_map);
#endif
// Test the number of features found
TEST_EQUAL(transition_group_map.size(), 2)
///////////////////////////////////////////////////////////////////////////
//// Scores for the second group
MRMFeatureFinderScoring::MRMTransitionGroupType transition_group;
transition_group = transition_group_map["tr_gr2"];
TEST_EQUAL(transition_group.size(), 3)
TEST_EQUAL(transition_group.getFeatures().size(), 2)
TEST_EQUAL(featureFile.size(), 3)
// Look closely at the feature we found in the second group
feature = transition_group.getFeatures()[0];
TOLERANCE_ABSOLUTE(0.1);
TEST_REAL_SIMILAR(feature.getRT(), 3119.092);
TEST_REAL_SIMILAR(feature.getIntensity(), 1034.55);
// feature attributes
TEST_REAL_SIMILAR(feature.getMetaValue("leftWidth" ), 3099.7);
TEST_REAL_SIMILAR(feature.getMetaValue("rightWidth"), 3147.68);
TEST_REAL_SIMILAR(feature.getMetaValue("total_xic"), 1610.27);
// feature scores
TEST_REAL_SIMILAR(feature.getMetaValue("var_xcorr_coelution"), 2.265);
TEST_REAL_SIMILAR(feature.getMetaValue("var_xcorr_shape"), 0.7245);
TEST_REAL_SIMILAR(feature.getMetaValue("var_library_rmsd"), 0.43566);
TEST_REAL_SIMILAR(feature.getMetaValue("var_library_corr"), -0.784);
TEST_REAL_SIMILAR(feature.getMetaValue("var_elution_model_fit_score"), 0.902);
TEST_REAL_SIMILAR(feature.getMetaValue("var_intensity_score"), 2.36342573991536);
TEST_REAL_SIMILAR(feature.getMetaValue("sn_ratio"), 30.18);
TEST_REAL_SIMILAR(feature.getMetaValue("var_log_sn_score"), 3.40718216971789);
// feature identification scores
TEST_EQUAL(feature.getMetaValue("id_target_transition_names").toStringList()[0], "tr5");
TEST_EQUAL(feature.getMetaValue("id_target_transition_names").toStringList()[1], "tr2");
TEST_REAL_SIMILAR(feature.getMetaValue("id_target_ind_log_intensity").toDoubleList()[0], 5.03352);
TEST_REAL_SIMILAR(feature.getMetaValue("id_target_ind_log_intensity").toDoubleList()[1], 7.92704);
TEST_REAL_SIMILAR(feature.getMetaValue("id_target_num_transitions"), 2);
TEST_REAL_SIMILAR(feature.getMetaValue("id_target_ind_xcorr_coelution").toDoubleList()[0], 1);
TEST_REAL_SIMILAR(feature.getMetaValue("id_target_ind_xcorr_coelution").toDoubleList()[1], 1.66667);
TEST_REAL_SIMILAR(feature.getMetaValue("id_target_ind_xcorr_shape").toDoubleList()[0], 0.68631);
TEST_REAL_SIMILAR(feature.getMetaValue("id_target_ind_xcorr_shape").toDoubleList()[1], 0.690494);
TEST_REAL_SIMILAR(feature.getMetaValue("id_target_ind_log_sn_score").toDoubleList()[0], 1.16692);
TEST_REAL_SIMILAR(feature.getMetaValue("id_target_ind_log_sn_score").toDoubleList()[1], 4.45008);
TEST_EQUAL(feature.getMetaValue("id_target_ind_isotope_correlation").toDoubleList().size(), 0);
TEST_EQUAL(feature.getMetaValue("id_target_ind_isotope_overlap").toDoubleList().size(), 0);
TEST_EQUAL(feature.getMetaValue("id_target_ind_massdev_score").toDoubleList().size(), 0);
}
END_SECTION
START_SECTION(void mapExperimentToTransitionList(OpenSwath::SpectrumAccessPtr input, OpenSwath::LightTargetedExperiment &transition_exp, TransitionGroupMapType &transition_group_map, TransformationDescription trafo, double rt_extraction_window))
{
MRMFeatureFinderScoring ff;
MRMFeature feature;
FeatureMap featureFile;
TransformationDescription trafo;
PeakMap swath_map;
TransitionGroupMapType transition_group_map;
MRMFeatureFinderScoring::MRMTransitionGroupType transition_group;
// Load the chromatograms (mzML) and the meta-information (TraML)
std::shared_ptr<PeakMap> exp (new PeakMap);
OpenSwath::LightTargetedExperiment transitions;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("OpenSwath_generic_input.mzML"), *exp);
{
TargetedExperiment transition_exp_;
TraMLFile().load(OPENMS_GET_TEST_DATA_PATH("OpenSwath_generic_input.TraML"), transition_exp_);
OpenSwathDataAccessHelper::convertTargetedExp(transition_exp_, transitions);
}
// Pick features in the experiment
ff.prepareProteinPeptideMaps_(transitions);
#ifdef USE_SP_INTERFACE
OpenSwath::SpectrumAccessPtr chromatogram_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp);
ff.mapExperimentToTransitionList(chromatogram_ptr, transitions, transition_group_map, trafo, -1);
#else
ff.mapExperimentToTransitionList(exp, transitions, transition_group_map, trafo, -1);
#endif
// Test the number of features found
TEST_EQUAL(transition_group_map.size(), 2)
///////////////////////////////////////////////////////////////////////////
//// The first group
transition_group = transition_group_map["tr_gr1"];
TEST_EQUAL(transition_group.size(), 2)
TEST_EQUAL(transition_group.getTransitions().size(), 2)
TEST_EQUAL(transition_group.getChromatograms().size(), 2)
TEST_EQUAL(transition_group.hasChromatogram("tr1"), true)
TEST_EQUAL(transition_group.hasChromatogram("tr2"), true)
TEST_EQUAL(transition_group.getChromatogram("tr2").getNativeID(), "tr2")
TEST_EQUAL(transition_group.getTransition("tr2").getNativeID(), "tr2")
///////////////////////////////////////////////////////////////////////////
//// The second group
transition_group = transition_group_map["tr_gr2"];
TEST_EQUAL(transition_group.size(), 3)
TEST_EQUAL(transition_group.getTransitions().size(), 3)
TEST_EQUAL(transition_group.getChromatograms().size(), 3)
TEST_EQUAL(transition_group.hasChromatogram("tr3"), true)
TEST_EQUAL(transition_group.hasChromatogram("tr4"), true)
TEST_EQUAL(transition_group.hasChromatogram("tr5"), true)
TEST_EQUAL(transition_group.getChromatogram("tr5").getNativeID(), "tr5")
TEST_EQUAL(transition_group.getTransition("tr5").getNativeID(), "tr5")
}
END_SECTION
START_SECTION( void scorePeakgroups(MRMTransitionGroupType& transition_group, TransformationDescription & trafo, OpenSwath::SpectrumAccessPtr swath_map, FeatureMap& output) )
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION(void prepareProteinPeptideMaps_(OpenSwath::LightTargetedExperiment& transition_exp) )
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void setStrictFlag(bool f))
NOT_TESTABLE
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/TMTTenPlexQuantitationMethod_test.cpp | .cpp | 8,762 | 244 | // 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/TMTTenPlexQuantitationMethod.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/Matrix.h>
using namespace OpenMS;
using namespace std;
START_TEST(TMTTenPlexQuantitationMethod, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
TMTTenPlexQuantitationMethod* ptr = nullptr;
TMTTenPlexQuantitationMethod* null_ptr = nullptr;
START_SECTION(TMTTenPlexQuantitationMethod())
{
ptr = new TMTTenPlexQuantitationMethod();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~TMTTenPlexQuantitationMethod())
{
delete ptr;
}
END_SECTION
START_SECTION((const String& getMethodName() const ))
{
TMTTenPlexQuantitationMethod quant_meth;
TEST_EQUAL(quant_meth.getMethodName(), "tmt10plex")
}
END_SECTION
START_SECTION((const IsobaricChannelList& getChannelInformation() const ))
{
TMTTenPlexQuantitationMethod quant_meth;
IsobaricQuantitationMethod::IsobaricChannelList channel_list = quant_meth.getChannelInformation();
TEST_EQUAL(channel_list.size(), 10)
ABORT_IF(channel_list.size() != 10)
// descriptions are empty by default
TEST_STRING_EQUAL(channel_list[0].description, "")
TEST_STRING_EQUAL(channel_list[1].description, "")
TEST_STRING_EQUAL(channel_list[2].description, "")
TEST_STRING_EQUAL(channel_list[3].description, "")
TEST_STRING_EQUAL(channel_list[4].description, "")
TEST_STRING_EQUAL(channel_list[5].description, "")
TEST_STRING_EQUAL(channel_list[6].description, "")
TEST_STRING_EQUAL(channel_list[7].description, "")
TEST_STRING_EQUAL(channel_list[8].description, "")
TEST_STRING_EQUAL(channel_list[9].description, "")
// check masses&co
TEST_EQUAL(channel_list[0].name, "126")
TEST_EQUAL(channel_list[0].id, 0)
TEST_EQUAL(channel_list[0].center, 126.127726)
TEST_EQUAL(channel_list[0].affected_channels[0], -1)
TEST_EQUAL(channel_list[0].affected_channels[1], -1)
TEST_EQUAL(channel_list[0].affected_channels[2], 2)
TEST_EQUAL(channel_list[0].affected_channels[3], 4)
TEST_EQUAL(channel_list[1].name, "127N")
TEST_EQUAL(channel_list[1].id, 1)
TEST_EQUAL(channel_list[1].center, 127.124761)
TEST_EQUAL(channel_list[1].affected_channels[0], -1)
TEST_EQUAL(channel_list[1].affected_channels[1], -1)
TEST_EQUAL(channel_list[1].affected_channels[2], 3)
TEST_EQUAL(channel_list[1].affected_channels[3], 5)
TEST_EQUAL(channel_list[2].name, "127C")
TEST_EQUAL(channel_list[2].id, 2)
TEST_EQUAL(channel_list[2].center, 127.131081)
TEST_EQUAL(channel_list[2].affected_channels[0], -1)
TEST_EQUAL(channel_list[2].affected_channels[1], 0)
TEST_EQUAL(channel_list[2].affected_channels[2], 4)
TEST_EQUAL(channel_list[2].affected_channels[3], 6)
TEST_EQUAL(channel_list[3].name, "128N")
TEST_EQUAL(channel_list[3].id, 3)
TEST_EQUAL(channel_list[3].center, 128.128116)
TEST_EQUAL(channel_list[3].affected_channels[0], -1)
TEST_EQUAL(channel_list[3].affected_channels[1], 1)
TEST_EQUAL(channel_list[3].affected_channels[2], 5)
TEST_EQUAL(channel_list[3].affected_channels[3], 7)
TEST_EQUAL(channel_list[4].name, "128C")
TEST_EQUAL(channel_list[4].id, 4)
TEST_EQUAL(channel_list[4].center, 128.134436)
TEST_EQUAL(channel_list[4].affected_channels[0], 0)
TEST_EQUAL(channel_list[4].affected_channels[1], 2)
TEST_EQUAL(channel_list[4].affected_channels[2], 6)
TEST_EQUAL(channel_list[4].affected_channels[3], 8)
TEST_EQUAL(channel_list[5].name, "129N")
TEST_EQUAL(channel_list[5].id, 5)
TEST_EQUAL(channel_list[5].center, 129.131471)
TEST_EQUAL(channel_list[5].affected_channels[0], 1)
TEST_EQUAL(channel_list[5].affected_channels[1], 3)
TEST_EQUAL(channel_list[5].affected_channels[2], 7)
TEST_EQUAL(channel_list[5].affected_channels[3], 9)
TEST_EQUAL(channel_list[6].name, "129C")
TEST_EQUAL(channel_list[6].id, 6)
TEST_EQUAL(channel_list[6].center, 129.137790)
TEST_EQUAL(channel_list[6].affected_channels[0], 2)
TEST_EQUAL(channel_list[6].affected_channels[1], 4)
TEST_EQUAL(channel_list[6].affected_channels[2], 8)
TEST_EQUAL(channel_list[6].affected_channels[3], -1)
TEST_EQUAL(channel_list[7].name, "130N")
TEST_EQUAL(channel_list[7].id, 7)
TEST_EQUAL(channel_list[7].center, 130.134825)
TEST_EQUAL(channel_list[7].affected_channels[0], 3)
TEST_EQUAL(channel_list[7].affected_channels[1], 5)
TEST_EQUAL(channel_list[7].affected_channels[2], 9)
TEST_EQUAL(channel_list[7].affected_channels[3], -1)
TEST_EQUAL(channel_list[8].name, "130C")
TEST_EQUAL(channel_list[8].id, 8)
TEST_EQUAL(channel_list[8].center, 130.141145)
TEST_EQUAL(channel_list[8].affected_channels[0], 4)
TEST_EQUAL(channel_list[8].affected_channels[1], 6)
TEST_EQUAL(channel_list[8].affected_channels[2], -1)
TEST_EQUAL(channel_list[8].affected_channels[3], -1)
TEST_EQUAL(channel_list[9].name, "131")
TEST_EQUAL(channel_list[9].id, 9)
TEST_EQUAL(channel_list[9].center, 131.138180)
TEST_EQUAL(channel_list[9].affected_channels[0], 5)
TEST_EQUAL(channel_list[9].affected_channels[1], 7)
TEST_EQUAL(channel_list[9].affected_channels[2], -1)
TEST_EQUAL(channel_list[9].affected_channels[3], -1)
}
END_SECTION
START_SECTION((Size getNumberOfChannels() const ))
{
TMTTenPlexQuantitationMethod quant_meth;
TEST_EQUAL(quant_meth.getNumberOfChannels(), 10)
}
END_SECTION
START_SECTION((virtual Matrix<double> getIsotopeCorrectionMatrix() const ))
{
double test_matrix[10][10] = {{0.9491,0,0.0037,0,0.0008,0,0,0,0,0},
{0,0.9448,0,0.0065,0,0.0001,0,0,0,0},
{0.0509,0,0.9412,0,0.0049,0,0,0,0,0},
{0,0.0527,0,0.9508,0,0.0071,0,0.0002,0,0},
{0,0,0.0536,0,0.9637,0,0.0132,0,0.0003,0},
{0,0,0,0.0417,0,0.9621,0,0.0128,0,0.0008},
{0,0,0.0015,0,0.0306,0,0.9606,0,0.0208,0},
{0,0,0,0.001,0,0.0307,0,0.9342,0,0.0199},
{0,0,0,0,0,0,0.0262,0,0.9566,0},
{0,0,0,0,0,0,0,0.0275,0,0.9628}};
Matrix<double> test_Matrix;
test_Matrix.setMatrix<double,10,10>(test_matrix);
TMTTenPlexQuantitationMethod quant_meth;
// we only check the default matrix here which is an identity matrix
// for tmt10plex
Matrix<double> m = quant_meth.getIsotopeCorrectionMatrix();
TEST_EQUAL(m.rows(), 10)
TEST_EQUAL(m.cols(), 10)
ABORT_IF(m.rows() != 10)
ABORT_IF(m.cols() != 10)
for (Size i = 0; i < m.rows(); ++i)
{
for (Size j = 0; j < m.cols(); ++j)
{
if (i == j) TEST_REAL_SIMILAR(m(i,j), test_Matrix(i,j))
else TEST_REAL_SIMILAR(m(i,j), test_Matrix(i,j))
}
}
}
END_SECTION
START_SECTION((Size getReferenceChannel() const ))
{
TMTTenPlexQuantitationMethod quant_meth;
TEST_EQUAL(quant_meth.getReferenceChannel(), 0)
Param p;
p.setValue("reference_channel","128N");
quant_meth.setParameters(p);
TEST_EQUAL(quant_meth.getReferenceChannel(), 3)
}
END_SECTION
START_SECTION((TMTTenPlexQuantitationMethod(const TMTTenPlexQuantitationMethod &other)))
{
TMTTenPlexQuantitationMethod qm;
Param p = qm.getParameters();
p.setValue("channel_127N_description", "new_description");
p.setValue("reference_channel", "129C");
qm.setParameters(p);
TMTTenPlexQuantitationMethod qm2(qm);
IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation();
TEST_STRING_EQUAL(channel_list[1].description, "new_description")
TEST_EQUAL(qm2.getReferenceChannel(), 6)
}
END_SECTION
START_SECTION((TMTTenPlexQuantitationMethod& operator=(const TMTTenPlexQuantitationMethod &rhs)))
{
TMTTenPlexQuantitationMethod qm;
Param p = qm.getParameters();
p.setValue("channel_127N_description", "new_description");
p.setValue("reference_channel", "130C");
qm.setParameters(p);
TMTTenPlexQuantitationMethod qm2 = qm;
IsobaricQuantitationMethod::IsobaricChannelList channel_list = qm2.getChannelInformation();
TEST_STRING_EQUAL(channel_list[1].description, "new_description")
TEST_EQUAL(qm2.getReferenceChannel(), 8)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MRMMapping_test.cpp | .cpp | 4,690 | 163 | // 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 <boost/assign/std/vector.hpp>
#include <OpenMS/ANALYSIS/TARGETED/MRMMapping.h>
using namespace OpenMS;
using namespace std;
START_TEST(MRMMapping, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MRMMapping* ptr = nullptr;
MRMMapping* nullPointer = nullptr;
START_SECTION(MRMMapping())
{
ptr = new MRMMapping();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~MRMMapping())
{
delete ptr;
}
END_SECTION
START_SECTION(void mapExperiment(const OpenMS::PeakMap& input_chromatograms, const OpenMS::TargetedExperiment& targeted_exp, OpenMS::PeakMap& output))
{
MRMMapping m;
MSExperiment exp;
exp.setComment("comment1");
MSChromatogram c;
exp.addChromatogram(c);
TEST_EQUAL(exp.getNrChromatograms(), 1)
TargetedExperiment targ;
ReactionMonitoringTransition t;
targ.addTransition(t);
MSExperiment out;
m.mapExperiment(exp, targ, out);
TEST_EQUAL(out.getNrChromatograms(), 0)
{
Param p = m.getDefaults();
p.setValue("map_multiple_assays", "true");
m.setParameters(p);
m.mapExperiment(exp, targ, out);
TEST_EQUAL(out.getNrChromatograms(), 1) // both transition and chromatogram have zero m/z
TEST_EQUAL(out.getComment(), "comment1") // should preserve the meta data
}
exp.setComment("comment2");
{
Param p = m.getDefaults();
p.setValue("map_multiple_assays", "true");
p.setValue("precursor_tolerance", 9999.0);
p.setValue("product_tolerance", 9999.0);
m.setParameters(p);
m.mapExperiment(exp, targ, out);
TEST_EQUAL(out.getNrChromatograms(), 1)
TEST_EQUAL(out.getComment(), "comment2") // should preserve the meta data
}
// Now set some precursor and fragment ion values, and check whether we can map one chromatogram to two transitions
exp.getChromatograms()[0].getPrecursor().setMZ(500);
exp.getChromatograms()[0].getProduct().setMZ(500);
targ.addTransition(t);
auto tr = targ.getTransitions();
tr[0].setPrecursorMZ(500);
tr[0].setProductMZ(500.1);
tr[0].setNativeID("tr1");
tr[1].setPrecursorMZ(500);
tr[1].setProductMZ(500.0);
tr[1].setNativeID("tr2");
targ.setTransitions(tr);
{
Param p = m.getDefaults();
p.setValue("map_multiple_assays", "true");
p.setValue("precursor_tolerance", 1.0);
p.setValue("product_tolerance", 1.0);
m.setParameters(p);
m.mapExperiment(exp, targ, out);
TEST_EQUAL(exp.getNrChromatograms(), 1)
TEST_EQUAL(out.getNrChromatograms(), 2)
TEST_EQUAL(out.getChromatograms()[0].getNativeID(), "tr1")
TEST_EQUAL(out.getChromatograms()[1].getNativeID(), "tr2")
}
// test that we cannot map when we don't allow multiple assays per chromatogram
{
Param p = m.getDefaults();
p.setValue("map_multiple_assays", "false");
p.setValue("precursor_tolerance", 1.0);
p.setValue("product_tolerance", 1.0);
m.setParameters(p);
TEST_EXCEPTION(Exception::IllegalArgument, m.mapExperiment(exp, targ, out) )
}
// with a smaller mapping tolerance, we should only see a 1:1 mapping
{
Param p = m.getDefaults();
p.setValue("map_multiple_assays", "true");
p.setValue("precursor_tolerance", 0.05);
p.setValue("product_tolerance", 0.05);
m.setParameters(p);
MSExperiment out2;
m.mapExperiment(exp, targ, out2);
TEST_EQUAL(exp.getNrChromatograms(), 1)
TEST_EQUAL(out2.getNrChromatograms(), 1)
TEST_EQUAL(out2.getChromatograms()[0].getNativeID(), "tr2")
}
// test error on unmapped chromatograms
exp.getChromatograms()[0].getPrecursor().setMZ(600);
exp.getChromatograms()[0].getProduct().setMZ(700);
{
Param p = m.getDefaults();
p.setValue("map_multiple_assays", "true");
p.setValue("precursor_tolerance", 1.0);
p.setValue("product_tolerance", 1.0);
m.setParameters(p);
// that should still work
MSExperiment out2;
m.mapExperiment(exp, targ, out2);
// not this
p.setValue("error_on_unmapped", "true");
m.setParameters(p);
TEST_EXCEPTION(Exception::IllegalArgument, m.mapExperiment(exp, targ, out2) )
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ResidueDB_test.cpp | .cpp | 5,233 | 124 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg$
// --------------------------------------------------------------------------
//
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CHEMISTRY/ResidueDB.h>
#include <OpenMS/CHEMISTRY/Residue.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(ResidueDB, "$Id$")
/////////////////////////////////////////////////////////////
ResidueDB* ptr = nullptr;
ResidueDB* nullPointer = nullptr;
START_SECTION(ResidueDB* getInstance())
ptr = ResidueDB::getInstance();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(virtual ~ResidueDB())
NOT_TESTABLE
END_SECTION
START_SECTION((const Residue* getResidue(const String& name) const))
TEST_EQUAL(ptr->getResidue("C")->getOneLetterCode(), "C")
END_SECTION
START_SECTION((const Residue* getResidue(const unsigned char& one_letter_code) const))
TEST_EQUAL(ptr->getResidue('C')->getOneLetterCode(), "C")
END_SECTION
START_SECTION((bool hasResidue(const String& name) const))
TEST_EQUAL(ptr->hasResidue("BLUBB"), false)
TEST_EQUAL(ptr->hasResidue("Lys"), true)
TEST_EQUAL(ptr->hasResidue("K"), true)
END_SECTION
START_SECTION(bool hasResidue(const Residue* residue) const)
TEST_EXCEPTION(Exception::InvalidValue, ptr->hasResidue(ptr->getResidue("BLUBB")))
TEST_EQUAL(ptr->hasResidue(ptr->getResidue("Lys")), true)
TEST_EQUAL(ptr->hasResidue(ptr->getResidue("K")), true)
END_SECTION
START_SECTION(Size getNumberOfResidues() const)
TEST_EQUAL(ptr->getNumberOfResidues() >= 20 , true);
END_SECTION
START_SECTION(const Residue* getModifiedResidue(const String& name))
const Residue* mod_res = ptr->getModifiedResidue("Oxidation (M)"); // ox methionine
TEST_STRING_EQUAL(mod_res->getOneLetterCode(), "M")
TEST_STRING_EQUAL(mod_res->getModificationName(), "Oxidation")
END_SECTION
START_SECTION(const Residue* getModifiedResidue(const Residue* residue, const String& name))
const Residue* mod_res = ptr->getModifiedResidue(ptr->getResidue("M"), "Oxidation (M)");
TEST_STRING_EQUAL(mod_res->getOneLetterCode(), "M")
TEST_STRING_EQUAL(mod_res->getModificationName(), "Oxidation")
const Residue* nterm_mod_res = ptr->getModifiedResidue(ptr->getResidue("C"), "Pyro-carbamidomethyl (N-term C)"); // <umod:specificity hidden="0" site="C" position="Any N-term"
TEST_STRING_EQUAL(nterm_mod_res->getOneLetterCode(), "C")
TEST_STRING_EQUAL(nterm_mod_res->getModificationName(), "Pyro-carbamidomethyl")
const Residue* cterm_mod_res = ptr->getModifiedResidue(ptr->getResidue("G"), "Oxidation (C-term G)"); // <umod:specificity hidden="1" site="G" position="Any C-term"
TEST_STRING_EQUAL(cterm_mod_res->getOneLetterCode(), "G")
TEST_STRING_EQUAL(cterm_mod_res->getModificationName(), "Oxidation")
const Residue* prot_cterm_mod_res = ptr->getModifiedResidue(ptr->getResidue("Q"), "Dehydrated (Protein C-term Q)"); // <umod:specificity hidden="1" site="Q" position="Protein C-term"
TEST_STRING_EQUAL(prot_cterm_mod_res->getOneLetterCode(), "Q")
TEST_STRING_EQUAL(prot_cterm_mod_res->getModificationName(), "Dehydrated")
const Residue* prot_nterm_mod_res = ptr->getModifiedResidue(ptr->getResidue("F"), "Deamidated (Protein N-term F)"); // <umod:specificity hidden="1" site="F" position="Protein N-term"
TEST_STRING_EQUAL(prot_nterm_mod_res->getOneLetterCode(), "F")
TEST_STRING_EQUAL(prot_nterm_mod_res->getModificationName(), "Deamidated")
END_SECTION
START_SECTION((const std::set<const Residue*> getResidues(const String& residue_set="All") const))
set<const Residue*> residues = ptr->getResidues("All");
TEST_EQUAL(residues.size() >= 21, true)
residues = ptr->getResidues("Natural20");
TEST_EQUAL(residues.size(), 20)
residues = ptr->getResidues("Natural19WithoutL");
TEST_EQUAL(residues.size(), 19)
END_SECTION
START_SECTION((const std::set<String>& getResidueSets() const))
set<String> res_sets = ResidueDB::getInstance()->getResidueSets();
TEST_EQUAL(res_sets.find("All") != res_sets.end(), true)
TEST_EQUAL(res_sets.find("Natural20") != res_sets.end(), true)
TEST_EQUAL(res_sets.find("Natural19WithoutL") != res_sets.end(), true)
TEST_EQUAL(res_sets.find("Natural19WithoutI") != res_sets.end(), true)
END_SECTION
START_SECTION(void setResidues(const String& filename))
NOT_TESTABLE // this method is hard to test, just provided for convenience
END_SECTION
START_SECTION(Size getNumberOfModifiedResidues() const)
TEST_EQUAL(ptr->getNumberOfModifiedResidues(), 5) // M(Oxidation), C(Pyro-carbamidomethyl), G(Oxidation), Q(Dehydrated), F(Deamidated)
const Residue* mod_res = nullptr;
const Residue* mod_res_nullPointer = nullptr;
mod_res = ptr->getModifiedResidue("Carbamidomethyl (C)");
TEST_NOT_EQUAL(mod_res, mod_res_nullPointer)
TEST_EQUAL(ptr->getNumberOfModifiedResidues(), 6) // + C(Carbamidomethyl)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MzMLSpectrumDecoder_test.cpp | .cpp | 33,038 | 629 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/HANDLERS/MzMLSpectrumDecoder.h>
#define MULTI_LINE_STRING(...) #__VA_ARGS__
using namespace std;
using namespace OpenMS;
///////////////////////////
START_TEST(MzMLSpectrumDecoder, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MzMLSpectrumDecoder* ptr = nullptr;
MzMLSpectrumDecoder* nullPointer = nullptr;
START_SECTION((MzMLSpectrumDecoder() ))
{
ptr = new MzMLSpectrumDecoder();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION((~MzMLSpectrumDecoder()))
{
delete ptr;
}
END_SECTION
// Working example of parsing a spectrum
START_SECTION(( void domParseSpectrum(const std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
ptr->domParseSpectrum(testString, cptr);
TEST_EQUAL(cptr->getMZArray()->data.size(), 15)
TEST_EQUAL(cptr->getIntensityArray()->data.size(), 15)
TEST_REAL_SIMILAR(cptr->getMZArray()->data[7], 7)
TEST_REAL_SIMILAR(cptr->getIntensityArray()->data[7], 8)
delete ptr;
}
END_SECTION
// Working example of parsing a spectrum with some extra CV terms in there (should still work)
START_SECTION(([EXTRA] void domParseSpectrum(const std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
ptr->domParseSpectrum(testString, cptr);
TEST_EQUAL(cptr->getMZArray()->data.size(), 15)
TEST_EQUAL(cptr->getIntensityArray()->data.size(), 15)
TEST_REAL_SIMILAR(cptr->getMZArray()->data[7], 7)
TEST_REAL_SIMILAR(cptr->getIntensityArray()->data[7], 8)
delete ptr;
}
END_SECTION
// missing defaultArrayLength -> should give an exception of ParseError
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2">
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
TEST_EXCEPTION(Exception::ParseError,ptr->domParseSpectrum(testString, cptr))
delete ptr;
}
END_SECTION
// root tag is neither spectrum or chromatogram -> precondition violation
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
// root tag is neither spectrum or chromatogram
//
// this does not generate a runtime error but rather a precondition violation
// -> it should allow a developer to easily spot a problem with the code if
// some other XML tag is used.
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<NotASpectrum index="2" id="index=2">
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
</binaryDataArrayList>
</NotASpectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
TEST_PRECONDITION_VIOLATED(ptr->domParseSpectrum(testString, cptr))
// TEST_PRECONDITION_VIOLATED should already be sufficient to not trigger the "no subtests performed in"
TEST_EQUAL(cptr->getMZArray()->data.size(), 0)
delete ptr;
}
END_SECTION
// no XML at all here ... -> Exception
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
Lorem ipsum
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
TEST_EXCEPTION(Exception::ParseError,ptr->domParseSpectrum(testString, cptr))
delete ptr;
}
END_SECTION
// Working example without intensity -> simply an empty spectrum
START_SECTION(( void domParseSpectrum(const std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
ptr->domParseSpectrum(testString, cptr);
TEST_EQUAL(cptr->getMZArray()->data.size(), 0)
TEST_EQUAL(cptr->getIntensityArray()->data.size(), 0)
delete ptr;
}
END_SECTION
// missing 64 bit float tag -> should throw Exception
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
TEST_EXCEPTION(Exception::ParseError,ptr->domParseSpectrum(testString, cptr))
delete ptr;
}
END_SECTION
// This is a valid XML structure, but simply empty <binary></binary> -> empty spectra output
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="3">
<binaryDataArray encodedLength="0" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary></binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary></binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
ptr->domParseSpectrum(testString, cptr);
TEST_EQUAL(cptr->getMZArray()->data.size(), 0)
TEST_EQUAL(cptr->getIntensityArray()->data.size(), 0)
delete ptr;
}
END_SECTION
// Invalid XML (unclosed brackets) -> should throw Exception
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="3">
<binaryDataArray encodedLength="0" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<bina
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
TEST_EXCEPTION(Exception::ParseError,ptr->domParseSpectrum(testString, cptr))
delete ptr;
}
END_SECTION
// Invalid XML (unclosed brackets) -> should throw Exception
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="3">
<binaryDataArray encodedLength="0" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<cvParam cvRef="MS" accession="MS:100057"
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
TEST_EXCEPTION(Exception::ParseError,ptr->domParseSpectrum(testString, cptr))
delete ptr;
}
END_SECTION
// Invalid mzML (too much content inside <binary>) -> should throw Exception
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="3">
<binaryDataArray encodedLength="0" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>
<whoPutMeHere>
some crazy person, obviously
</whoPutMeHere>
</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
TEST_EXCEPTION(Exception::ParseError,ptr->domParseSpectrum(testString, cptr))
delete ptr;
}
END_SECTION
// Invalid mzML (missing <binary> tag)-> should throw Exception
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="3">
<binaryDataArray encodedLength="0" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
TEST_EXCEPTION(Exception::ParseError,ptr->domParseSpectrum(testString, cptr))
delete ptr;
}
END_SECTION
// Invalid content of <binary> -> empty spectrum
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="3">
<binaryDataArray encodedLength="0" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>
whoPutMeHere: some crazy person, obviously! What if I contain invalid characters like these &-
</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
TEST_EXCEPTION(Exception::ConversionError, ptr->domParseSpectrum(testString, cptr) );
delete ptr;
}
END_SECTION
// encode as int instead of float -> throw Exception
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000519" name="32-bit int" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
TEST_EXCEPTION(Exception::ParseError,ptr->domParseSpectrum(testString, cptr))
delete ptr;
}
END_SECTION
// missing m/z array -> no Exception but simply empty data
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
ptr->domParseSpectrum(testString, cptr);
TEST_EQUAL(cptr->getMZArray()->data.size(), 0) // failed since no m/z array is present
TEST_EQUAL(cptr->getIntensityArray()->data.size(), 0) // failed since no m/z array is present
delete ptr;
}
END_SECTION
START_SECTION(([EXTRA] void domParseSpectrum(std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
// missing: detect semantically invalid XML structures
// for example: multiple occurrences of an array
// (fix in MzMLHandlerHelper::computeDataProperties_)
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="3">
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
OpenMS::Interfaces::SpectrumPtr cptr(new OpenMS::Interfaces::Spectrum);
ptr->domParseSpectrum(testString, cptr);
TEST_EQUAL(cptr->getMZArray()->data.size(), 15)
TEST_EQUAL(cptr->getIntensityArray()->data.size(), 15)
TEST_REAL_SIMILAR(cptr->getMZArray()->data[7], 7)
TEST_REAL_SIMILAR(cptr->getIntensityArray()->data[7], 8)
delete ptr;
}
END_SECTION
// Working example of parsing a chromatogram
START_SECTION(( void domParseChromatogram(const std::string& in, OpenMS::Interfaces::ChromatogramPtr & cptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<chromatogram index="1" id="sic native" defaultArrayLength="10" >
<cvParam cvRef="MS" accession="MS:1000235" name="total ion current chromatogram" value=""/>
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="108" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000595" name="time array" unitAccession="UO:0000010" unitName="second" unitCvRef="UO"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkA=</binary>
</binaryDataArray>
<binaryDataArray encodedLength="108" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary>AAAAAAAAJEAAAAAAAAAiQAAAAAAAACBAAAAAAAAAHEAAAAAAAAAYQAAAAAAAABRAAAAAAAAAEEAAAAAAAAAIQAAAAAAAAABAAAAAAAAA8D8=</binary>
</binaryDataArray>
</binaryDataArrayList>
</chromatogram>);
OpenMS::Interfaces::ChromatogramPtr cptr(new OpenMS::Interfaces::Chromatogram);
ptr->domParseChromatogram(testString, cptr);
TEST_EQUAL(cptr->getTimeArray()->data.size(), 10)
TEST_EQUAL(cptr->getIntensityArray()->data.size(), 10)
TEST_REAL_SIMILAR(cptr->getTimeArray()->data[5], 5)
TEST_REAL_SIMILAR(cptr->getIntensityArray()->data[5], 5)
delete ptr;
}
END_SECTION
START_SECTION(( void domParseSpectrum(const std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<spectrum index="2" id="index=2" defaultArrayLength="15">
<binaryDataArrayList count="3">
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" unitAccession="MS:1000040" unitName="m/z" unitCvRef="MS"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000786" name="non-standard data array" value="Ion Mobility" />
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
);
MSSpectrum s;
ptr->domParseSpectrum(testString, s);
TEST_EQUAL(s.size(), 15)
TEST_EQUAL(s.getFloatDataArrays().size(), 1)
TEST_REAL_SIMILAR(s[7].getMZ(), 7)
TEST_REAL_SIMILAR(s[7].getIntensity(), 8)
TEST_REAL_SIMILAR(s.getFloatDataArrays()[0][7], 8)
TEST_EQUAL(s.getFloatDataArrays()[0].getName(), "Ion Mobility")
delete ptr;
}
END_SECTION
START_SECTION(( void domParseChromatogram(const std::string& in, OpenMS::Interfaces::ChromatogramPtr & cptr) ))
{
ptr = new MzMLSpectrumDecoder();
std::string testString = MULTI_LINE_STRING(
<chromatogram index="1" id="sic native" defaultArrayLength="10" >
<cvParam cvRef="MS" accession="MS:1000235" name="total ion current chromatogram" value=""/>
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="108" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000595" name="time array" unitAccession="UO:0000010" unitName="second" unitCvRef="UO"/>
<binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkA=</binary>
</binaryDataArray>
<binaryDataArray encodedLength="108" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/>
<binary>AAAAAAAAJEAAAAAAAAAiQAAAAAAAACBAAAAAAAAAHEAAAAAAAAAYQAAAAAAAABRAAAAAAAAAEEAAAAAAAAAIQAAAAAAAAABAAAAAAAAA8D8=</binary>
</binaryDataArray>
<binaryDataArray encodedLength="160" >
<cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/>
<cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/>
<cvParam cvRef="MS" accession="MS:1000786" name="non-standard data array" value="Ion Mobility" />
<binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary>
</binaryDataArray>
</binaryDataArrayList>
</chromatogram>);
MSChromatogram s;
ptr->domParseChromatogram(testString, s);
TEST_EQUAL(s.size(), 10)
TEST_EQUAL(s.getFloatDataArrays().size(), 1)
TEST_REAL_SIMILAR(s[5].getRT(), 5)
TEST_REAL_SIMILAR(s[5].getIntensity(), 5)
TEST_REAL_SIMILAR(s.getFloatDataArrays()[0][7], 8)
TEST_EQUAL(s.getFloatDataArrays()[0].getName(), "Ion Mobility")
delete ptr;
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ModelDescription_test.cpp | .cpp | 3,462 | 142 | // 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/ModelDescription.h>
#include <OpenMS/FEATUREFINDER/IsotopeModel.h>
#include <OpenMS/CONCEPT/Exception.h>
///////////////////////////
START_TEST(ModelDescription<2>, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using std::stringstream;
ModelDescription<2>* ptr = nullptr;
ModelDescription<2>* nullPointer = nullptr;
START_SECTION((ModelDescription()))
ptr = new ModelDescription<2>();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~ModelDescription()))
delete ptr;
END_SECTION
START_SECTION( virtual bool operator==(const ModelDescription &rhs) const )
ModelDescription<2> fp1,fp2;
TEST_EQUAL(fp1==fp2,true)
fp1.setName("halligalli2000");
TEST_EQUAL(fp1==fp2,false)
fp2.setName("halligalli2000");
TEST_EQUAL(fp1==fp2,true)
Param param;
param.setValue("bla","bluff");
fp1.setParam(param);
TEST_EQUAL(fp1==fp2,false)
fp2.setParam(param);
TEST_EQUAL(fp1==fp2,true)
END_SECTION
START_SECTION( virtual bool operator!=(const ModelDescription &rhs) const )
ModelDescription<2> fp1, fp2;
TEST_EQUAL(fp1!=fp2,false)
fp1.setName("halligalli2000");
TEST_EQUAL(fp1!=fp2,true)
fp2.setName("halligalli2000");
TEST_EQUAL(fp1!=fp2,false)
END_SECTION
START_SECTION((virtual ModelDescription& operator=(const ModelDescription &source)))
ModelDescription<2> tm1;
tm1.setName("halligalli");
Param param;
param.setValue("test","test");
tm1.setParam(param);
ModelDescription<2> tm2;
tm2 = tm1;
TEST_EQUAL(tm1==tm2,true)
END_SECTION
START_SECTION((ModelDescription(const ModelDescription &source)))
ModelDescription<2> tm1;
tm1.setName("halligalli");
Param param;
param.setValue("test","test");
tm1.setParam(param);
ModelDescription<2> tm2(tm1);
TEST_EQUAL(tm1==tm2,true)
END_SECTION
START_SECTION((const String& getName() const ))
const ModelDescription<2> m;
TEST_EQUAL(m.getName(), "")
END_SECTION
START_SECTION((void setName(const String &name)))
ModelDescription<2> m;
m.setName("halligalli2006");
TEST_EQUAL(m.getName(), "halligalli2006")
END_SECTION
START_SECTION((const Param& getParam() const ))
ModelDescription<2> m;
Param p;
p.setValue("x1",1.0);
p.setValue("x2",2.0);
m.setParam(p);
TEST_EQUAL(m.getParam(), p)
END_SECTION
START_SECTION( String& getName() )
ModelDescription<2> m;
m.setName("halligalli2006");
TEST_EQUAL(m.getName(), "halligalli2006")
END_SECTION
START_SECTION( Param& getParam() )
ModelDescription<2> m;
Param p;
p.setValue("x1",1.0);
p.setValue("x2",2.0);
m.setParam(p);
TEST_EQUAL(m.getParam(), p)
END_SECTION
START_SECTION( void setParam(const Param ¶m) )
ModelDescription<2> m;
Param p;
p.setValue("x1",1.0);
p.setValue("x2",2.0);
m.setParam(p);
TEST_EQUAL(m.getParam(), p)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/EmgGradientDescent_test.cpp | .cpp | 27,299 | 610 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/MATH/MISC/EmgGradientDescent.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
// TODO: remove helper function and its calls
void geogebra_print_execute(const double h, const double mu, const double sigma, const double tau)
{
std::cout << "\nGEOGEBRA: Execute[{\"h = " << h << "\", \"mu = " << mu << "\",\"sigma = " << sigma << "\", \"tau = " << tau << "\"}]\n\n";
}
START_TEST(EmgGradientDescent, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
EmgGradientDescent* ptr = nullptr;
EmgGradientDescent* null_ptr = nullptr;
// Toy chromatogram
// data is taken from raw LC-MS/MS data points acquired for L-Glutamate in RBCs
const vector<double> position = {
2.23095,2.239716667,2.248866667,2.25765,2.266416667,
2.275566667,2.2847,2.293833333,2.304066667,2.315033333,2.325983333,2.336566667,
2.3468,2.357016667,2.367283333,2.377183333,2.387083333,2.39735,2.40725,2.4175,
2.4274,2.4373,2.44755,2.45745,2.4677,2.477966667,2.488216667,2.498516667,2.5084,
2.5183,2.5282,2.538466667,2.548366667,2.558266667,2.568516667,2.578783333,
2.588683333,2.59895,2.6092,2.619466667,2.630066667,2.64065,2.65125,2.662116667,
2.672716667,2.6833,2.6939,2.7045,2.715083333,2.725683333,2.736266667,2.746866667,
2.757833333,2.768416667,2.779016667,2.789616667,2.8002,2.810116667,2.820033333,
2.830316667,2.840216667,2.849766667,2.859316667,2.868866667,2.878783333,2.888683333,
2.898233333,2.907783333,2.916033333,2.924266667,2.93215,2.940383333,2.947933333,
2.955816667,2.964066667,2.97195,2.979833333,2.987716667,2.995616667,3.003516667,
3.011416667,3.01895,3.026833333,3.034366667,3.042266667,3.0498,3.05735,3.065233333,
3.073133333,3.080666667,3.0882,3.095733333,3.103633333,3.111533333,3.119066667,
3.126966667,3.134866667,3.14275,3.15065,3.15855,3.166433333,3.174333333,3.182233333,
3.190133333,3.198016667,3.205916667,3.213166667
};
const vector<double> intensity = {
1447,2139,1699,755,1258,1070,944,1258,1573,1636,
1762,1447,1133,1321,1762,1133,1447,2391,692,1636,2957,1321,1573,1196,1258,881,
1384,2076,1133,1699,1384,692,1636,1133,1573,1825,1510,2391,4342,10382,17618,
51093,153970,368094,632114,869730,962547,966489,845055,558746,417676,270942,
184865,101619,59776,44863,31587,24036,20450,20324,11074,9879,10508,7928,7110,
6733,6481,5726,6921,6670,5537,4971,4719,4782,5097,5789,4279,5411,4530,3524,
2139,3335,3083,4342,4279,3083,3649,4216,4216,3964,2957,2202,2391,2643,3524,
2328,2202,3649,2706,3020,3335,2580,2328,2894,3146,2769,2517
};
const vector<double> saturated_pos_min = {
2.46444988, 2.4746666, 2.4849, 2.49511671, 2.50533342, 2.51556659, 2.52546668, 2.53568339, 2.54563332, 2.55553341, 2.56541657, 2.57566667, 2.58626676, 2.59686661, 2.60778332, 2.61871672, 2.62963343, 2.64056659, 2.6514833, 2.66278338, 2.67406678, 2.68501663, 2.69596672, 2.70693326, 2.71788335, 2.72848344, 2.73943329, 2.75003338, 2.76063323, 2.77121663, 2.78181672, 2.79241657, 2.80299997, 2.8129499, 2.82321668, 2.83313322, 2.84303331, 2.8526001, 2.86213326, 2.87168336, 2.88123322, 2.89078331, 2.9003334, 2.90960002, 2.91886663, 2.92775011, 2.93665004, 2.94589996, 2.95514989, 2.96440005, 2.97364998, 2.9828999, 2.99215007, 3.00139999, 3.01064992, 3.01990008, 3.02915001, 3.03806663, 3.04698324, 3.05591655, 3.0648334, 3.0737834, 3.08270001, 3.09163332, 3.10054994, 3.10946655, 3.1184001, 3.12731671, 3.13623333, 3.14516664, 3.15408325, 3.16300011, 3.17193341, 3.18085003, 3.18976665, 3.19869995, 3.20763326, 3.21623325, 3.22483325, 3.23341656, 3.24201655, 3.25061655, 3.25921679
};
const vector<double> saturated_pos_sec = {
147.8669928, 148.479996, 149.094, 149.7070026, 150.3200052, 150.93399540000001, 151.5280008, 152.1410034, 152.7379992, 153.33200459999998, 153.92499420000001, 154.5400002, 155.1760056, 155.81199660000001, 156.46699919999998, 157.1230032, 157.77800580000002, 158.43399540000001, 159.088998, 159.7670028, 160.4440068, 161.1009978, 161.7580032, 162.4159956, 163.073001, 163.70900640000002, 164.3659974, 165.0020028, 165.6379938, 166.2729978, 166.9090032, 167.5449942, 168.1799982, 168.776994, 169.39300079999998, 169.9879932, 170.5819986, 171.156006, 171.72799559999999, 172.3010016, 172.8739932, 173.4469986, 174.020004, 174.5760012, 175.13199780000002, 175.6650066, 176.19900239999998, 176.75399760000002, 177.3089934, 177.864003, 178.4189988, 178.973994, 179.5290042, 180.08399939999998, 180.6389952, 181.19400480000002, 181.7490006, 182.28399779999998, 182.81899439999998, 183.354993, 183.890004, 184.427004, 184.9620006, 185.4979992, 186.0329964, 186.567993, 187.104006, 187.6390026, 188.1739998, 188.7099984, 189.244995, 189.7800066, 190.31600459999999, 190.8510018, 191.385999, 191.921997, 192.4579956, 192.973995, 193.489995, 194.0049936, 194.520993, 195.036993, 195.5530074
};
const vector<double> saturated_int = {
3667.91333, 3829.03906, 3992.62622, 4164.69531, 4438.9165, 4958.67188, 5914.42041, 7855.03125, 11941.041, 21250.4023, 42803.6133, 94525.1094, 216015.453, 472692.219, 961669, 1718756.12, 2641781.25, 3480271.25, 3979093.25, 4087263, 3988863.5, 3942767, 4051667.25, 4250679.5, 4385092, 4301191.5, 3926528, 3335860.5, 2652440.75, 2002597, 1457891.5, 1041989.56, 746353.938, 555698.812, 426332.062, 344843.938, 291420.156, 256906.516, 232813.5, 215017.938, 200963.688, 188910.703, 177631.375, 166692.906, 155609.891, 144831.812, 133511, 121007.531, 108372.43, 97343.3359, 89953.1406, 85699.6328, 82895.1094, 80079.7188, 76910.4375, 73768.9609, 70963.6641, 68590.4766, 66312.75, 64046.4219, 61798.5039, 59813.6211, 58235.5156, 56946.2266, 55774.4766, 54536.9844, 53272.5625, 52113.4883, 51119.7734, 50214.9961, 49111.543, 47641.0234, 45777.4805, 43666.3633, 41646.0508, 39955.7422, 38698.9688, 37738.0273, 36792.582, 35764.0156, 34750.8164, 33958.5547, 33610.1445
};
const vector<double> saturated_cutoff_pos_min = {
14.3310337, 14.3429499, 14.3551168, 14.3672667, 14.3796835, 14.3923168, 14.4049501, 14.4175835, 14.4299498, 14.4420834, 14.454217, 14.4663496, 14.4782495, 14.4903831, 14.5025167, 14.515317, 14.5275335, 14.5397329, 14.5516834, 14.5636501, 14.5756168, 14.5873337, 14.5993004, 14.6110163, 14.6222496, 14.6334667, 14.6442165, 14.6552162, 14.6661997, 14.6772003, 14.6881838, 14.6987, 14.7094669, 14.7199831, 14.7302504, 14.7405329, 14.7505665, 14.7605829, 14.7703829, 14.7796669, 14.7891998, 14.7985001, 14.810483, 14.8224335, 14.8338833, 14.8455667, 14.8572502, 14.8689499, 14.8806334, 14.8923168, 14.9042501, 14.9164, 14.9287834, 14.9411669, 14.9535503, 14.9659166, 14.9783001, 14.9906836, 15.0025835, 15.0167665, 15.0309162, 15.0450668, 15.0592003, 15.07335, 15.0874996, 15.1016502
};
const vector<double> saturated_cutoff_pos_sec = {
859.862022, 860.576994, 861.307008, 862.036002, 862.78101, 863.539008, 864.297006, 865.0550099999999, 865.7969879999999, 866.525004, 867.25302, 867.9809759999999, 868.69497, 869.422986, 870.151002, 870.9190199999999, 871.65201, 872.3839740000001, 873.101004, 873.8190060000001, 874.537008, 875.2400220000001, 875.958024, 876.660978, 877.334976, 878.008002, 878.65299, 879.312972, 879.971982, 880.632018, 881.291028, 881.922, 882.5680140000001, 883.198986, 883.815024, 884.431974, 885.03399, 885.6349739999999, 886.222974, 886.780014, 887.351988, 887.910006, 888.62898, 889.3460100000001, 890.032998, 890.7340019999999, 891.4350119999999, 892.1369940000001, 892.8380040000001, 893.539008, 894.255006, 894.9839999999999, 895.7270040000001, 896.470014, 897.213018, 897.9549959999999, 898.698006, 899.441016, 900.15501, 901.00599, 901.854972, 902.704008, 903.5520180000001, 904.401, 905.249976, 906.099012
};
const vector<double> saturated_cutoff_int = {
1808499.25, 3368120.75, 3803323.25, 4059358, 4092095, 4058075.25, 4160395, 4395341.5, 4573185, 4565417.5, 4371225, 4065336.75, 3716669.5, 3338531, 2982165.25, 2675112, 2464135, 2307864, 2178321, 2053773.88, 1941723.12, 1851044.12, 1768557.75, 1694074, 1643185, 1621222.5, 1615733.12, 1586897.38, 1506051.75, 1374752.25, 1228128.12, 1104698.5, 1004596.56, 922247.438, 846399.25, 775016.375, 717635, 678566.562, 656717.375, 645997, 640481.062, 637876.188, 632300.688, 619110.375, 599831.625, 578701.5, 559403.312, 543297.625, 528049.25, 509227.594, 485023.156, 462585.688, 448690.75, 438401.25, 425110.969, 409034.406, 394403.406, 381114.688, 369241.094, 356554.969, 345889.281, 336646.844, 325948.938, 316341.688, 310746.156, 309641.875
};
const vector<double> cutoff_pos_min = {
15.34253311, 15.35624981, 15.36995029, 15.38366699, 15.39736652, 15.41156673, 15.42574978, 15.44018364, 15.45436668, 15.46856689, 15.48274994, 15.49695015
};
const vector<double> cutoff_pos_sec = {
920.5519866, 921.3749885999999, 922.1970174, 923.0200194, 923.8419912, 924.6940038, 925.5449868000001, 926.4110184000001, 927.2620008, 928.1140134, 928.9649964, 929.817009
};
const vector<double> cutoff_int = {
3.48297429, 15.54384613, 50.31319046, 151.8971405, 411.25631714, 946.44311523, 1642.56152344, 2118.89526367, 2055.13647461, 1665.13232422, 1275.53015137, 1009.70056152
};
MSChromatogram chromatogram;
MSSpectrum spectrum;
for (Size i = 0; i < position.size(); ++i)
{
chromatogram.push_back(ChromatogramPeak(position[i], intensity[i]));
spectrum.push_back(Peak1D(position[i], intensity[i]));
}
MSChromatogram saturated_chrom_min, saturated_cutoff_chrom_min, cutoff_chrom_min;
MSChromatogram saturated_chrom_sec, saturated_cutoff_chrom_sec, cutoff_chrom_sec;
MSSpectrum saturated_spec_min, saturated_cutoff_spec_min, cutoff_spec_min;
MSSpectrum saturated_spec_sec, saturated_cutoff_spec_sec, cutoff_spec_sec;
for (Size i = 0; i < saturated_pos_min.size(); ++i)
{
saturated_chrom_min.push_back(ChromatogramPeak(saturated_pos_min[i], saturated_int[i]));
saturated_chrom_sec.push_back(ChromatogramPeak(saturated_pos_sec[i], saturated_int[i]));
saturated_spec_min.push_back(Peak1D(saturated_pos_min[i], saturated_int[i]));
saturated_spec_sec.push_back(Peak1D(saturated_pos_sec[i], saturated_int[i]));
}
for (Size i = 0; i < saturated_cutoff_pos_min.size(); ++i)
{
saturated_cutoff_chrom_min.push_back(ChromatogramPeak(saturated_cutoff_pos_min[i], saturated_cutoff_int[i]));
saturated_cutoff_chrom_sec.push_back(ChromatogramPeak(saturated_cutoff_pos_sec[i], saturated_cutoff_int[i]));
saturated_cutoff_spec_min.push_back(Peak1D(saturated_cutoff_pos_min[i], saturated_cutoff_int[i]));
saturated_cutoff_spec_sec.push_back(Peak1D(saturated_cutoff_pos_sec[i], saturated_cutoff_int[i]));
}
for (Size i = 0; i < cutoff_pos_min.size(); ++i)
{
cutoff_chrom_min.push_back(ChromatogramPeak(cutoff_pos_min[i], cutoff_int[i]));
cutoff_chrom_sec.push_back(ChromatogramPeak(cutoff_pos_sec[i], cutoff_int[i]));
cutoff_spec_min.push_back(Peak1D(cutoff_pos_min[i], cutoff_int[i]));
cutoff_spec_sec.push_back(Peak1D(cutoff_pos_sec[i], cutoff_int[i]));
}
START_SECTION(EmgGradientDescent())
{
ptr = new EmgGradientDescent();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~EmgGradientDescent())
{
delete ptr;
}
END_SECTION
START_SECTION(getParameters())
{
EmgGradientDescent emg;
const Param& params = emg.getParameters();
TEST_EQUAL(params.getValue("print_debug"), 0)
TEST_EQUAL(params.getValue("max_gd_iter"), 100000)
TEST_EQUAL(params.getValue("compute_additional_points"), "true")
}
END_SECTION
START_SECTION(void fitEMGPeakModel(
const MSChromatogram& input_peak,
MSChromatogram& output_peak
) const)
{
MSChromatogram out_min, out_sec;
const MSChromatogram::FloatDataArray * fda_emg;
EmgGradientDescent emg;
emg.fitEMGPeakModel(chromatogram, out_min);
TEST_EQUAL(out_min.size(), 107)
fda_emg = &out_min.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 1317410)
TEST_REAL_SIMILAR((*fda_emg)[1], 2.68121)
TEST_REAL_SIMILAR((*fda_emg)[2], 0.0212625)
TEST_REAL_SIMILAR((*fda_emg)[3], 0.0235329)
// geogebra_print_execute((*fda_emg)[0], (*fda_emg)[1], (*fda_emg)[2], (*fda_emg)[3]);
emg.fitEMGPeakModel(saturated_chrom_min, out_min);
emg.fitEMGPeakModel(saturated_chrom_sec, out_sec);
TEST_EQUAL(out_min.size(), 87)
TEST_EQUAL(out_min.size(), out_sec.size())
TOLERANCE_RELATIVE(1.0 + 1e-2)
for (Size i = 0; i < out_min.size(); i += 9)
{
TEST_REAL_SIMILAR(out_min[i].getIntensity(), out_sec[i].getIntensity())
}
TOLERANCE_RELATIVE(1.0 + 1e-5)
fda_emg = &out_min.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 7735860)
TEST_REAL_SIMILAR((*fda_emg)[1], 2.66296)
TEST_REAL_SIMILAR((*fda_emg)[2], 0.0394313)
TEST_REAL_SIMILAR((*fda_emg)[3], 0.0394313)
// geogebra_print_execute((*fda_emg)[0], (*fda_emg)[1], (*fda_emg)[2], (*fda_emg)[3]);
fda_emg = &out_sec.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 7736020)
TEST_REAL_SIMILAR((*fda_emg)[1], 159.778)
TEST_REAL_SIMILAR((*fda_emg)[2], 2.36584)
TEST_REAL_SIMILAR((*fda_emg)[3], 2.36584)
emg.fitEMGPeakModel(saturated_cutoff_chrom_min, out_min);
emg.fitEMGPeakModel(saturated_cutoff_chrom_sec, out_sec);
TEST_EQUAL(out_min.size(), 71)
TEST_EQUAL(out_min.size(), out_sec.size())
TOLERANCE_RELATIVE(1.0 + 1e-2)
for (Size i = 0; i < out_min.size(); i += 9)
{
TEST_REAL_SIMILAR(out_min[i].getIntensity(), out_sec[i].getIntensity())
}
TOLERANCE_RELATIVE(1.0 + 1e-5)
fda_emg = &out_min.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 15515900)
TEST_REAL_SIMILAR((*fda_emg)[1], 14.3453)
TEST_REAL_SIMILAR((*fda_emg)[2], 0.0344277)
TEST_REAL_SIMILAR((*fda_emg)[3], 0.188507)
// geogebra_print_execute((*fda_emg)[0], (*fda_emg)[1], (*fda_emg)[2], (*fda_emg)[3]);
fda_emg = &out_sec.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 15515900)
TEST_REAL_SIMILAR((*fda_emg)[1], 860.719)
TEST_REAL_SIMILAR((*fda_emg)[2], 2.06566)
TEST_REAL_SIMILAR((*fda_emg)[3], 11.3104)
emg.fitEMGPeakModel(cutoff_chrom_min, out_min);
emg.fitEMGPeakModel(cutoff_chrom_sec, out_sec);
TEST_EQUAL(out_min.size(), 28)
TEST_EQUAL(out_min.size(), out_sec.size())
TOLERANCE_RELATIVE(1.0 + 1e-2)
for (Size i = 0; i < out_min.size(); i += 9)
{
TEST_REAL_SIMILAR(out_min[i].getIntensity(), out_sec[i].getIntensity())
}
TOLERANCE_RELATIVE(1.0 + 1e-5)
fda_emg = &out_min.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 3791.07)
TEST_REAL_SIMILAR((*fda_emg)[1], 15.4227)
TEST_REAL_SIMILAR((*fda_emg)[2], 0.0210588)
TEST_REAL_SIMILAR((*fda_emg)[3], 0.0476741)
// geogebra_print_execute((*fda_emg)[0], (*fda_emg)[1], (*fda_emg)[2], (*fda_emg)[3]);
fda_emg = &out_sec.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 3791.13)
TEST_REAL_SIMILAR((*fda_emg)[1], 925.363)
TEST_REAL_SIMILAR((*fda_emg)[2], 1.26351)
TEST_REAL_SIMILAR((*fda_emg)[3], 2.8605)
}
END_SECTION
START_SECTION(void fitEMGPeakModel(
const MSSpectrum& input_peak,
MSSpectrum& output_peak
) const)
{
MSSpectrum out_min, out_sec;
const MSSpectrum::FloatDataArray * fda_emg;
EmgGradientDescent emg;
emg.fitEMGPeakModel(spectrum, out_min);
TEST_EQUAL(out_min.size(), 107)
fda_emg = &out_min.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 1317410)
TEST_REAL_SIMILAR((*fda_emg)[1], 2.68121)
TEST_REAL_SIMILAR((*fda_emg)[2], 0.0212625)
TEST_REAL_SIMILAR((*fda_emg)[3], 0.0235329)
emg.fitEMGPeakModel(saturated_spec_min, out_min);
emg.fitEMGPeakModel(saturated_spec_sec, out_sec);
TEST_EQUAL(out_min.size(), 87)
TEST_EQUAL(out_min.size(), out_sec.size())
TOLERANCE_RELATIVE(1.0 + 1e-2)
for (Size i = 0; i < out_min.size(); i += 9)
{
TEST_REAL_SIMILAR(out_min[i].getIntensity(), out_sec[i].getIntensity())
}
TOLERANCE_RELATIVE(1.0 + 1e-5)
fda_emg = &out_min.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 7735860)
TEST_REAL_SIMILAR((*fda_emg)[1], 2.66296)
TEST_REAL_SIMILAR((*fda_emg)[2], 0.0394313)
TEST_REAL_SIMILAR((*fda_emg)[3], 0.0394313)
fda_emg = &out_sec.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 7736020)
TEST_REAL_SIMILAR((*fda_emg)[1], 159.778)
TEST_REAL_SIMILAR((*fda_emg)[2], 2.36584)
TEST_REAL_SIMILAR((*fda_emg)[3], 2.36584)
emg.fitEMGPeakModel(saturated_cutoff_spec_min, out_min);
emg.fitEMGPeakModel(saturated_cutoff_spec_sec, out_sec);
TEST_EQUAL(out_min.size(), 71)
TEST_EQUAL(out_min.size(), out_sec.size())
TOLERANCE_RELATIVE(1.0 + 1e-2)
for (Size i = 0; i < out_min.size(); i += 9)
{
TEST_REAL_SIMILAR(out_min[i].getIntensity(), out_sec[i].getIntensity())
}
TOLERANCE_RELATIVE(1.0 + 1e-5)
fda_emg = &out_min.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 15515900)
TEST_REAL_SIMILAR((*fda_emg)[1], 14.3453)
TEST_REAL_SIMILAR((*fda_emg)[2], 0.0344277)
TEST_REAL_SIMILAR((*fda_emg)[3], 0.188507)
fda_emg = &out_sec.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 15515900)
TEST_REAL_SIMILAR((*fda_emg)[1], 860.719)
TEST_REAL_SIMILAR((*fda_emg)[2], 2.06566)
TEST_REAL_SIMILAR((*fda_emg)[3], 11.3104)
emg.fitEMGPeakModel(cutoff_spec_min, out_min);
emg.fitEMGPeakModel(cutoff_spec_sec, out_sec);
TEST_EQUAL(out_min.size(), 28)
TEST_EQUAL(out_min.size(), out_sec.size())
TOLERANCE_RELATIVE(1.0 + 1e-2)
for (Size i = 0; i < out_min.size(); i += 9)
{
TEST_REAL_SIMILAR(out_min[i].getIntensity(), out_sec[i].getIntensity())
}
TOLERANCE_RELATIVE(1.0 + 1e-5)
fda_emg = &out_min.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 3791.07)
TEST_REAL_SIMILAR((*fda_emg)[1], 15.4227)
TEST_REAL_SIMILAR((*fda_emg)[2], 0.0210588)
TEST_REAL_SIMILAR((*fda_emg)[3], 0.0476741)
fda_emg = &out_sec.getFloatDataArrays()[0];
TEST_EQUAL(fda_emg->getName(), "emg_parameters")
TEST_REAL_SIMILAR((*fda_emg)[0], 3791.13)
TEST_REAL_SIMILAR((*fda_emg)[1], 925.363)
TEST_REAL_SIMILAR((*fda_emg)[2], 1.26351)
TEST_REAL_SIMILAR((*fda_emg)[3], 2.8605)
}
END_SECTION
START_SECTION(double Loss_function(
const std::vector<double>& xs,
const std::vector<double>& ys,
const double h,
const double mu,
const double sigma,
const double tau
) const)
{
MSChromatogram out_min;
EmgGradientDescent emg;
Param params = emg.getParameters();
params.setValue("compute_additional_points", "false");
emg.setParameters(params);
emg.fitEMGPeakModel(chromatogram, out_min);
EmgGradientDescent_friend emg_f;
const MSChromatogram::FloatDataArray& fda_emg = out_min.getFloatDataArrays()[0];
TEST_REAL_SIMILAR(emg_f.Loss_function(position, intensity, fda_emg[0], fda_emg[1], fda_emg[2], fda_emg[3]), 60778399.8312241)
// geogebra_print_execute(fda_emg[0], fda_emg[1], fda_emg[2], fda_emg[3]);
emg.fitEMGPeakModel(saturated_chrom_min, out_min);
const MSChromatogram::FloatDataArray& fda_emg_sat = out_min.getFloatDataArrays()[0];
TEST_REAL_SIMILAR(emg_f.Loss_function(saturated_pos_min, saturated_int, fda_emg_sat[0], fda_emg_sat[1], fda_emg_sat[2], fda_emg_sat[3]), 187412764882.422)
// geogebra_print_execute(fda_emg_sat[0], fda_emg_sat[1], fda_emg_sat[2], fda_emg_sat[3]);
emg.fitEMGPeakModel(saturated_cutoff_chrom_min, out_min);
const MSChromatogram::FloatDataArray& fda_emg_sat_cut = out_min.getFloatDataArrays()[0];
TEST_REAL_SIMILAR(emg_f.Loss_function(saturated_cutoff_pos_min, saturated_cutoff_int, fda_emg_sat_cut[0], fda_emg_sat_cut[1], fda_emg_sat_cut[2], fda_emg_sat_cut[3]), 56213636966.189)
// geogebra_print_execute(fda_emg_sat_cut[0], fda_emg_sat_cut[1], fda_emg_sat_cut[2], fda_emg_sat_cut[3]);
emg.fitEMGPeakModel(cutoff_chrom_min, out_min);
const MSChromatogram::FloatDataArray& fda_emg_cut = out_min.getFloatDataArrays()[0];
TEST_REAL_SIMILAR(emg_f.Loss_function(cutoff_pos_min, cutoff_int, fda_emg_cut[0], fda_emg_cut[1], fda_emg_cut[2], fda_emg_cut[3]), 651.824632922326)
// geogebra_print_execute(fda_emg_cut[0], fda_emg_cut[1], fda_emg_cut[2], fda_emg_cut[3]);
}
END_SECTION
START_SECTION(void extractTrainingSet(
const std::vector<double>& xs,
const std::vector<double>& ys,
std::vector<double>& TrX,
std::vector<double>& TrY
) const)
{
EmgGradientDescent_friend emg_f;
vector<double> TrX, TrY;
emg_f.extractTrainingSet(position, intensity, TrX, TrY);
// non-saturated, non-cutoff peak: no point is filtered, all are valid
TEST_EQUAL(TrX.size(), position.size())
emg_f.extractTrainingSet(saturated_pos_min, saturated_int, TrX, TrY);
TEST_NOT_EQUAL(TrX.size(), saturated_pos_min.size())
TEST_EQUAL(TrX.size(), 77)
emg_f.extractTrainingSet(saturated_cutoff_pos_min, saturated_cutoff_int, TrX, TrY);
TEST_NOT_EQUAL(TrX.size(), saturated_cutoff_pos_min.size())
TEST_EQUAL(TrX.size(), 61)
emg_f.extractTrainingSet(cutoff_pos_min, cutoff_int, TrX, TrY);
// cutoff but non-saturated peak: no point is filtered, all are valid
TEST_EQUAL(TrX.size(), cutoff_pos_min.size())
}
END_SECTION
START_SECTION(double computeMuMaxDistance(const std::vector<double>& xs) const)
{
EmgGradientDescent_friend emg_f;
vector<double> xs { 3, 2, 4, 2, 4, 5, 7, 9, 3 };
TEST_REAL_SIMILAR(emg_f.computeMuMaxDistance(xs), 2.45)
xs.clear();
TEST_REAL_SIMILAR(emg_f.computeMuMaxDistance(xs), 0.0) // empty vector case
}
END_SECTION
START_SECTION(double computeInitialMean(
const std::vector<double>& xs,
const std::vector<double>& ys
) const)
{
EmgGradientDescent_friend emg_f;
double mu;
mu = emg_f.computeInitialMean(position, intensity);
TEST_REAL_SIMILAR(mu, 2.69743333333333)
mu = emg_f.computeInitialMean(saturated_pos_min, saturated_int);
TEST_REAL_SIMILAR(mu, 2.69516110583333)
mu = emg_f.computeInitialMean(saturated_cutoff_pos_sec, saturated_cutoff_int);
TEST_REAL_SIMILAR(mu, 865.1314205)
mu = emg_f.computeInitialMean(cutoff_pos_sec, cutoff_int);
TEST_REAL_SIMILAR(mu, 926.90050115)
const vector<double> empty;
TEST_EXCEPTION(Exception::SizeUnderflow, emg_f.computeInitialMean(empty, empty))
}
END_SECTION
START_SECTION(void iRpropPlus(
const double prev_diff_E_param,
double& diff_E_param,
double& param_lr,
double& param_update,
double& param,
const double current_E,
const double previous_E
) const)
{
EmgGradientDescent_friend emg_f;
const double prev_diff_E_param { 10.0 };
double diff_E_param { 20.0 };
double param_lr { 4.0 };
double param_update { 0.5 };
double param { 860.0 };
const double current_E { 13.0 };
const double previous_E { 14.0 };
emg_f.iRpropPlus(
prev_diff_E_param, diff_E_param, param_lr,
param_update, param, current_E, previous_E
);
TEST_REAL_SIMILAR(diff_E_param, 20.0)
TEST_REAL_SIMILAR(param_lr, 4.8)
TEST_REAL_SIMILAR(param_update, -4.8)
TEST_REAL_SIMILAR(param, 855.2)
diff_E_param = -20.0;
param_lr = 4.0;
param_update = 0.5;
param = 860.0;
emg_f.iRpropPlus(
prev_diff_E_param, diff_E_param, param_lr,
param_update, param, current_E, previous_E
);
TEST_REAL_SIMILAR(diff_E_param, 0.0)
TEST_REAL_SIMILAR(param_lr, 2.0)
TEST_REAL_SIMILAR(param_update, 0.5)
TEST_REAL_SIMILAR(param, 860.0)
diff_E_param = 0.0;
param_lr = 4.0;
param_update = 0.5;
param = 860.0;
emg_f.iRpropPlus(
prev_diff_E_param, diff_E_param, param_lr,
param_update, param, current_E, previous_E
);
TEST_REAL_SIMILAR(diff_E_param, 0.0)
TEST_REAL_SIMILAR(param_lr, 4.0)
TEST_REAL_SIMILAR(param_update, -4.0)
TEST_REAL_SIMILAR(param, 856.0)
}
END_SECTION
START_SECTION(double compute_z(
const double x,
const double mu,
const double sigma,
const double tau
) const)
{
EmgGradientDescent_friend emg_f;
double x;
const double mu { 14.3453 };
const double sigma { 0.0344277 };
const double tau { 0.188507 };
x = mu - 1.0 / 60.0;
TEST_REAL_SIMILAR(emg_f.compute_z(x, mu, sigma, tau), 0.471456263584609)
x = mu + 1.0 / 60.0;
TEST_REAL_SIMILAR(emg_f.compute_z(x, mu, sigma, tau), -0.213173439809831)
x = -3333333;
TEST_REAL_SIMILAR(emg_f.compute_z(x, mu, sigma, tau), 68463258.2588395)
}
END_SECTION
START_SECTION(double emg_point(
const double x,
const double h,
const double mu,
const double sigma,
const double tau
) const)
{
EmgGradientDescent_friend emg_f;
double x;
double h { 15515900 };
double mu { 14.3453 };
double sigma { 0.0344277 };
double tau { 0.188507 };
x = mu - 1.0 / 60.0;
TEST_REAL_SIMILAR(emg_f.emg_point(x, h, mu, sigma, tau), 1992032.65711041)
x = mu + 1.0 / 60.0;
TEST_REAL_SIMILAR(emg_f.emg_point(x, h, mu, sigma, tau), 4088964.97520213)
x = -3333333;
TEST_REAL_SIMILAR(emg_f.emg_point(x, h, mu, sigma, tau), 0.0)
mu = 860.719;
sigma = 2.06566;
tau = 11.3104;
x = mu - 1;
TEST_REAL_SIMILAR(emg_f.emg_point(x, h, mu, sigma, tau), 1992033.06584247)
x = mu + 1;
TEST_REAL_SIMILAR(emg_f.emg_point(x, h, mu, sigma, tau), 4088968.52957875)
x = -200000000;
TEST_REAL_SIMILAR(emg_f.emg_point(x, h, mu, sigma, tau), 0.0)
}
END_SECTION
START_SECTION(void applyEstimatedParameters(
const std::vector<double>& xs,
const double h,
const double mu,
const double sigma,
const double tau,
std::vector<double>& out_xs,
std::vector<double>& out_ys
) const)
{
EmgGradientDescent_friend emg_f;
const double h { 15515900 };
const double mu { 14.3453 };
const double sigma { 0.0344277 };
const double tau { 0.188507 };
vector<double> out_xs;
vector<double> out_ys;
Param params = emg_f.emg_gd_.getParameters();
params.setValue("compute_additional_points", "false");
emg_f.emg_gd_.setParameters(params);
emg_f.applyEstimatedParameters(saturated_cutoff_pos_min, h, mu, sigma, tau, out_xs, out_ys);
TEST_EQUAL(out_xs.size(), saturated_cutoff_pos_min.size())
TEST_REAL_SIMILAR(out_xs.front(), 14.3310337)
TEST_REAL_SIMILAR(out_ys.front(), 2144281.1472228)
params.setValue("compute_additional_points", "true");
emg_f.emg_gd_.setParameters(params);
emg_f.applyEstimatedParameters(saturated_cutoff_pos_min, h, mu, sigma, tau, out_xs, out_ys);
TEST_EQUAL(out_xs.size(), 71) // more points than before
TEST_REAL_SIMILAR(out_xs.front(), 14.2717555076923) // peak was cutoff on the left side
TEST_REAL_SIMILAR(out_ys.front(), 108845.941990663)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.