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/EuclideanSimilarity_test.cpp | .cpp | 2,599 | 92 | // 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/EuclideanSimilarity.h>
#include <cmath>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(EuclideanSimilarity, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
EuclideanSimilarity* ptr = nullptr;
EuclideanSimilarity* nullPointer = nullptr;
START_SECTION(EuclideanSimilarity())
{
ptr = new EuclideanSimilarity();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~EuclideanSimilarity())
{
delete ptr;
}
END_SECTION
START_SECTION((EuclideanSimilarity(const EuclideanSimilarity &source)))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((EuclideanSimilarity& operator=(const EuclideanSimilarity &source)))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((float operator()(const std::pair< float, float > &a, const std::pair< float, float > &b) const ))
{
EuclideanSimilarity es;
TOLERANCE_ABSOLUTE(0.0001);
TEST_REAL_SIMILAR(es(make_pair(2.0f,2.0f),make_pair(4.f,4.f)), 1-sqrt(8.0));
TEST_REAL_SIMILAR(es(make_pair(9.f,0.1f),make_pair(2.8f,2.f)), 1-sqrt(42.05));
TEST_REAL_SIMILAR(es(make_pair(12.f,0.0f),make_pair(2.f,0.0f)), 1-sqrt(100.0));
es.setScale(sqrt(233.28f));
}
END_SECTION
START_SECTION((float operator()(const std::pair< float, float > &c) const ))
{
EuclideanSimilarity es;
TOLERANCE_ABSOLUTE(0.0001);
TEST_REAL_SIMILAR(es(make_pair(9.0f,0.1f)), 1-0);
TEST_REAL_SIMILAR(es(make_pair(2.8f,2.0f)), 1-0);
}
END_SECTION
START_SECTION((void setScale(float x)))
{
EuclideanSimilarity es;
es.setScale(10);
TOLERANCE_ABSOLUTE(0.0001);
TEST_REAL_SIMILAR(es(make_pair(2.0f,2.0f),make_pair(4.f,4.f)), 1-(sqrt(8.0)/10));
TEST_REAL_SIMILAR(es(make_pair(9.0f,0.1f),make_pair(2.8f,2.f)), 1-(sqrt(42.05)/10));
TEST_REAL_SIMILAR(es(make_pair(12.0f,0.0f),make_pair(2.f,0.0f)), 1-(sqrt(100.0)/10));
es.setScale(sqrt(233.28f));
TEST_REAL_SIMILAR(es(make_pair(0.1f,0.1f),make_pair(10.9f,10.9f)), 1-1);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/DBSuitability_test.cpp | .cpp | 15,347 | 419 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Tom Waschischeck $
// $Authors: Tom Waschischeck $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/METADATA/PeptideHit.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/QC/DBSuitability.h>
#include <vector>
///////////////////////////
using namespace OpenMS;
using namespace std;
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/DATASTRUCTURES/FASTAContainer.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <boost/regex.hpp>
int countAS(const vector<FASTAFile::FASTAEntry>& fasta)
{
int counter = 0;
for (const auto& entry : fasta)
{
counter += entry.sequence.size();
}
return counter;
}
START_TEST(Suitability, "$Id$")
/////////////////////////////////////////////////////////////
////////////////////// CREATE DATA //////////////////////////
/////////////////////////////////////////////////////////////
PeptideEvidence decoy_protein("DECOY_PROT", 0, 0, 'A', 'A');
PeptideEvidence target_protein("DB_PROT", 0, 0, 'A', 'A');
PeptideEvidence novo_protein(Constants::UserParam::CONCAT_PEPTIDE, 0, 0, 'A', 'A');
// target-db hits with different q-values
PeptideHit target_db_hit1;
target_db_hit1.setSequence(AASequence::fromString("PEP"));
target_db_hit1.setPeptideEvidences({ target_protein });
target_db_hit1.setMetaValue("target_decoy", "target+decoy");
target_db_hit1.setMetaValue("MS:1002252", 0.8);
target_db_hit1.setScore(0.002);
PeptideHit target_db_hit2;
target_db_hit2.setSequence(AASequence::fromString("PEP"));
target_db_hit2.setPeptideEvidences({ target_protein });
target_db_hit2.setMetaValue("target_decoy", "target");
target_db_hit2.setMetaValue("MS:1002252", 0.8);
target_db_hit2.setScore(0.011);
// target-novo hits with different xcorr scores
PeptideHit target_novo_hit1;
target_novo_hit1.setSequence(AASequence::fromString("PEP"));
target_novo_hit1.setPeptideEvidences({ novo_protein });
target_novo_hit1.setMetaValue("target_decoy", "target");
target_novo_hit1.setMetaValue("MS:1002252", 0.85); // diff to db 0.05
target_novo_hit1.setScore(0.001);
PeptideHit target_novo_hit2;
target_novo_hit2.setSequence(AASequence::fromString("PEP"));
target_novo_hit2.setPeptideEvidences({ novo_protein });
target_novo_hit2.setMetaValue("target_decoy", "target");
target_novo_hit2.setMetaValue("MS:1002252", 0.93); // diff to db 0.13
target_novo_hit2.setScore(0.001);
// decoy hits with different xcorr scores -> resulting cut-offs: 0.15, 0.1, 0.05 (devided by 377.3 - weight of "PEP")
PeptideHit decoy1;
decoy1.setSequence(AASequence::fromString("PEP"));
decoy1.setPeptideEvidences({ decoy_protein });
decoy1.setMetaValue("target_decoy", "decoy");
decoy1.setMetaValue("MS:1002252", 0.7);
decoy1.setScore(1);
PeptideHit decoy2;
decoy2.setSequence(AASequence::fromString("PEP"));
decoy2.setPeptideEvidences({ decoy_protein });
decoy2.setMetaValue("target_decoy", "decoy");
decoy2.setMetaValue("MS:1002252", 0.6);
decoy2.setScore(1);
PeptideHit decoy3;
decoy3.setSequence(AASequence::fromString("PEP"));
decoy3.setMetaValue("target_decoy", "decoy");
decoy3.setMetaValue("MS:1002252", 0.55);
decoy3.setScore(1);
PeptideHit high_decoy;
high_decoy.setSequence(AASequence::fromString("PEP"));
high_decoy.setMetaValue("target_decoy", "decoy");
high_decoy.setMetaValue("MS:1002252", 0.55);
high_decoy.setScore(0);
// some error throwing hits
PeptideHit no_xcorr_hit;
no_xcorr_hit.setSequence(AASequence::fromString("PEP"));
no_xcorr_hit.setPeptideEvidences({ decoy_protein });
no_xcorr_hit.setMetaValue("target_decoy", "decoy");
no_xcorr_hit.setScore(1);
// build identifications
PeptideIdentificationList pep_ids;
PeptideIdentificationList top_decoy;
PeptideIdentificationList few_decoys;
PeptideIdentificationList no_xcorr_ids;
PeptideIdentification pep_id;
pep_id.setScoreType("some_score");
pep_id.setHigherScoreBetter(false);
pep_id.setHits({ target_novo_hit1, decoy1, decoy2 });
pep_ids.push_back(pep_id);
top_decoy.push_back(pep_id);
pep_id.setHits({ target_db_hit1, decoy1, decoy3 });
pep_ids.push_back(pep_id);
top_decoy.push_back(pep_id);
pep_id.setHits({ target_db_hit2 });
pep_ids.push_back(pep_id);
few_decoys.push_back(pep_id);
pep_id.setHits({ high_decoy, target_db_hit2 });
top_decoy.push_back(pep_id);
pep_id.setHits({ target_novo_hit1, target_db_hit1, decoy2, decoy3});
pep_ids.push_back(pep_id);
top_decoy.push_back(pep_id);
no_xcorr_ids.push_back(pep_id);
pep_id.setHits({ target_novo_hit2, target_db_hit1 });
pep_ids.push_back(pep_id);
top_decoy.push_back(pep_id);
pep_id.setHits({ no_xcorr_hit });
no_xcorr_ids.push_back(pep_id);
PeptideIdentificationList pep_ids_2(pep_ids);
PeptideIdentificationList pep_ids_3(pep_ids);
PeptideIdentificationList FDR_id;
pep_id.setScoreType("q-value");
pep_id.setHits({ decoy1 });
FDR_id.push_back(pep_id);
vector<FASTAFile::FASTAEntry> empty_fasta;
MSExperiment empty_exp;
ProteinIdentification::SearchParameters empty_params;
/////////////////////////////////////////////////////////////
///////////////////// START TESTING /////////////////////////
/////////////////////////////////////////////////////////////
DBSuitability* ptr = nullptr;
DBSuitability* nulpt = nullptr;
START_SECTION(DBSuitability())
{
ptr = new DBSuitability();
TEST_NOT_EQUAL(ptr, nulpt)
}
END_SECTION
START_SECTION(~DBSuitability())
{
delete ptr;
}
END_SECTION
START_SECTION(void compute(PeptideIdentificationList&& pep_ids, const MSExperiment& exp, const std::vector<FASTAFile::FASTAEntry>& original_fasta, const std::vector<FASTAFile::FASTAEntry>& novo_fasta, const ProteinIdentification::SearchParameters& search_params))
{
// Test normal suitability (without correction)
DBSuitability s;
Param p;
p.setValue("disable_correction", "true");
p.setValue("reranking_cutoff_percentile", 1.);
s.setParameters(p);
s.compute(move(pep_ids), empty_exp, empty_fasta, empty_fasta, empty_params);
p.setValue("reranking_cutoff_percentile", 1./3);
p.setValue("FDR", 0.);
s.setParameters(p);
s.compute(move(pep_ids_2), empty_exp, empty_fasta, empty_fasta, empty_params);
s.compute(move(top_decoy), empty_exp, empty_fasta, empty_fasta, empty_params);
p.setValue("reranking_cutoff_percentile", 0.);
s.setParameters(p);
s.compute(move(pep_ids_3), empty_exp, empty_fasta, empty_fasta, empty_params);
vector<DBSuitability::SuitabilityData> d = s.getResults();
DBSuitability::SuitabilityData data_fract_1 = d[0];
DBSuitability::SuitabilityData data_fract_05 = d[1];
DBSuitability::SuitabilityData data_decoy_top = d[2];
DBSuitability::SuitabilityData data_small_percentile = d[3];
TEST_REAL_SIMILAR(data_fract_1.cut_off, 0.00044);
TEST_REAL_SIMILAR(data_fract_05.cut_off, 0.00029);
TEST_REAL_SIMILAR(data_decoy_top.cut_off, 0.00029);
TEST_REAL_SIMILAR(data_small_percentile.cut_off, 0.00014);
TEST_EQUAL(data_fract_1.num_interest, 2);
TEST_EQUAL(data_fract_05.num_interest, 2);
TEST_EQUAL(data_decoy_top.num_interest, 0);
TEST_EQUAL(data_small_percentile.num_interest, 2);
TEST_EQUAL(data_fract_1.num_re_ranked, 2);
TEST_EQUAL(data_fract_05.num_re_ranked, 1);
TEST_EQUAL(data_decoy_top.num_re_ranked, 0);
TEST_EQUAL(data_small_percentile.num_re_ranked, 0);
TEST_EQUAL(data_fract_1.num_top_db, 4);
TEST_EQUAL(data_fract_05.num_top_db, 3);
TEST_EQUAL(data_decoy_top.num_top_db, 0);
TEST_EQUAL(data_small_percentile.num_top_db, 2);
TEST_EQUAL(data_fract_1.num_top_novo, 1);
TEST_EQUAL(data_fract_05.num_top_novo, 2);
TEST_EQUAL(data_decoy_top.num_top_novo, 0);
TEST_EQUAL(data_small_percentile.num_top_novo, 3);
TEST_REAL_SIMILAR(data_fract_1.suitability, 4./5);
TEST_REAL_SIMILAR(data_fract_05.suitability, 3./5);
TEST_REAL_SIMILAR(data_small_percentile.suitability, 2./5);
TEST_EQUAL(data_decoy_top.suitability, DBL_MAX);
TEST_EXCEPTION_WITH_MESSAGE(Exception::Precondition, s.compute(move(FDR_id), empty_exp, empty_fasta, empty_fasta, empty_params), "q-value found at PeptideIdentifications. That is not allowed! Please make sure FDR did not run previously.");
TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, s.compute(move(few_decoys), empty_exp, empty_fasta, empty_fasta, empty_params), "Under 20 % of peptide identifications have two decoy hits. This is not enough for re-ranking. Use the 'no_rerank' flag to still compute a suitability score.");
TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, s.compute(move(no_xcorr_ids), empty_exp, empty_fasta, empty_fasta, empty_params), "No cross correlation score found at peptide hit. Only Comet search engine is supported for re-ranking. Set 'force' flag to use the default score for this. This may result in undefined behaviour and is not advised.");
// Corrected Suitability is to complicated to be tested here.
// The tests for the DatabaseSuitability TOPP tool have to suffice.
}
END_SECTION
START_SECTION(getResults())
{
NOT_TESTABLE;
}
END_SECTION
DBSuitability_friend private_suit;
START_SECTION(std::vector<FASTAFile::FASTAEntry> getSubsampledFasta_(const std::vector<FASTAFile::FASTAEntry>& fasta_data, double subsampling_rate) const)
{
vector<FASTAFile::FASTAEntry> fasta;
FASTAFile::FASTAEntry entry;
entry.sequence = "AAAAAAA";// 7
fasta.push_back(entry);
entry.sequence = "PP";// 2
fasta.push_back(entry);
entry.sequence = "EEE";// 3
fasta.push_back(entry);
entry.sequence = "I";// 1
fasta.push_back(entry);
entry.sequence = "KKKKKK";// 6
fasta.push_back(entry);
entry.sequence = "LLLLL";// 5
fasta.push_back(entry);
entry.sequence = "QQQQ";//4
fasta.push_back(entry);
entry.sequence = "YYY";// 3
fasta.push_back(entry);
entry.sequence = "GGGG";// 4
fasta.push_back(entry);
// 35 AS in fasta
vector<FASTAFile::FASTAEntry> subsampled_fasta = private_suit.getSubsampledFasta(fasta, 0.3); // 35 * 0.3 = 10.5 --> at least 11 AS should be written (& at max. 17)
TEST_EQUAL((countAS(subsampled_fasta) >= 11 && countAS(subsampled_fasta) < 17), 1);
TEST_EXCEPTION(Exception::IllegalArgument, private_suit.getSubsampledFasta(fasta, 2));
TEST_EXCEPTION(Exception::IllegalArgument, private_suit.getSubsampledFasta(fasta, -1));
}
END_SECTION
START_SECTION(void appendDecoys_(std::vector<FASTAFile::FASTAEntry>& fasta) const)
{
vector<FASTAFile::FASTAEntry> fasta;
FASTAFile::FASTAEntry entry;
entry.sequence = "LIEQKPABIM";
entry.identifier = "PROTEIN";
fasta.push_back(entry);
private_suit.appendDecoys(fasta);
TEST_STRING_EQUAL(fasta[1].sequence, "LIBAPKQEIM");
TEST_STRING_EQUAL(fasta[1].identifier, "DECOY_PROTEIN");
}
END_SECTION
START_SECTION(double calculateCorrectionFactor_(const DBSuitability::SuitabilityData& data, const DBSuitability::SuitabilityData& data_sampled, double sampling_rate) const)
{
DBSuitability::SuitabilityData full_data;
DBSuitability::SuitabilityData subsampled_data;
full_data.num_top_db = 100;
subsampled_data.num_top_db = 50;
// delta 50
full_data.num_top_novo = 10;
subsampled_data.num_top_novo = 30;
// delta 20
double factor = private_suit.calculateCorrectionFactor(full_data, subsampled_data, 0.6);
// rate 0.6 --> db_slope = -50 / -0.4 = 125, novo_slope = 20 / -0.4 = -50
// factor = - (125) / (-50) = 2.5
TEST_EQUAL(factor, 2.5);
TEST_EXCEPTION(Exception::Precondition, private_suit.calculateCorrectionFactor(full_data, subsampled_data, 2));
TEST_EXCEPTION(Exception::Precondition, private_suit.calculateCorrectionFactor(full_data, subsampled_data, -1));
}
END_SECTION
START_SECTION(UInt numberOfUniqueProteins_(const PeptideIdentificationList& peps, UInt number_of_hits = 1) const)
{
PeptideEvidence ev1("PROTEIN_1", 0, 0, '[', ']');
PeptideEvidence ev2("PROTEIN_2", 0, 0, '[', ']');
PeptideEvidence ev3("PROTEIN_3", 0, 0, '[', ']');
PeptideEvidence ev4("PROTEIN_4", 0, 0, '[', ']');
PeptideEvidence ev5("DECOY_PROTEIN", 0, 0, '[', ']');
PeptideHit hit1;
hit1.setPeptideEvidences({ev1, ev1, ev2});
hit1.setMetaValue("target_decoy", "target");
PeptideHit hit2;
hit2.setPeptideEvidences({ev4, ev3, ev5});
hit2.setMetaValue("target_decoy", "target+decoy");
PeptideHit hit3;
hit3.setPeptideEvidences({ev3, ev2, ev3});
hit3.setMetaValue("target_decoy", "target");
PeptideHit hit4;
hit4.setPeptideEvidences({ev5});
hit4.setMetaValue("target_decoy", "decoy");
PeptideHit empty_hit;
PeptideIdentification id1;
id1.setHits({hit1, hit2});
PeptideIdentification id2;
id2.setHits({hit3});
PeptideIdentification id3;
id3.setHits({hit4});
PeptideIdentification empty_id;
PeptideIdentification id_hit_without_info;
id_hit_without_info.setHits({empty_hit});
PeptideIdentificationList ids({id1, id2, empty_id, id3});
TEST_EQUAL(private_suit.numberOfUniqueProteins(ids), 3);
TEST_EQUAL(private_suit.numberOfUniqueProteins(ids, 5), 4);
TEST_EXCEPTION(Exception::MissingInformation, private_suit.numberOfUniqueProteins({id_hit_without_info}));
}
END_SECTION
START_SECTION(Size getIndexWithMedianNovoHits_(const std::vector<SuitabilityData>& data) const)
{
DBSuitability::SuitabilityData d1;
d1.num_top_novo = 10;
DBSuitability::SuitabilityData d2;
d2.num_top_novo = 20;
DBSuitability::SuitabilityData d3;
d3.num_top_novo = 15;
DBSuitability::SuitabilityData d4;
d4.num_top_novo = 40;
TEST_EQUAL(private_suit.getIndexWithMedianNovoHits({d1, d2, d3}), 2);
TEST_EQUAL(private_suit.getIndexWithMedianNovoHits({d1, d2, d3, d4}), 1);
TEST_EXCEPTION(Exception::IllegalArgument, private_suit.getIndexWithMedianNovoHits({}));
}
END_SECTION
START_SECTION(double getScoreMatchingFDR_(const PeptideIdentificationList& pep_ids, double FDR, String score_name, bool higher_score_better) const)
{
PeptideHit hit1;
hit1.setScore(0.01);
hit1.setMetaValue("some_score", 120);
PeptideHit hit2;
hit2.setScore(0.04);
hit2.setMetaValue("some_score", 80);
PeptideHit hit3;
hit3.setScore(0.5);
hit3.setMetaValue("some_score", 5);
PeptideHit hit4;
hit4.setScore(0.05);
hit4.setMetaValue("some_score", 75);
PeptideIdentification id1;
id1.setScoreType("q-value");
id1.setHits({hit1});
PeptideIdentification id2;
id2.setScoreType("q-value");
id2.setHits({hit2});
PeptideIdentification id3;
id3.setScoreType("q-value");
id3.setHits({hit3});
PeptideIdentification id4;
id4.setScoreType("q-value");
id4.setHits({hit4});
TEST_EQUAL(private_suit.getScoreMatchingFDR({id1, id2, id3, id4}, 0.05, "some_score", true), 75);
TEST_EQUAL(private_suit.getScoreMatchingFDR({id1, id2, id3, id4}, 0.05, "some", false), 120);
TEST_EXCEPTION(Exception::IllegalArgument, private_suit.getScoreMatchingFDR({id1}, 0.05, "e-value", false));
id1.setScoreType("e-value");
TEST_EXCEPTION(Exception::Precondition, private_suit.getScoreMatchingFDR({id1}, 0.05, "some_score", false));
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST | C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IDRipper_test.cpp | .cpp | 1,958 | 69 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Immanuel Luhn$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/ID/IDRipper.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <vector>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(IDRipper, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
///load input data
std::vector< ProteinIdentification > protein_identifications;
PeptideIdentificationList identifications;
String document_id;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("IDFilter_test.idXML"), protein_identifications, identifications, document_id);
PeptideIdentification identification = identifications[0];
ProteinIdentification protein_identification = protein_identifications[0];
IDRipper* ptr = nullptr;
IDRipper* null_ptr = nullptr;
START_SECTION(IDRipper())
{
ptr = new IDRipper();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IDRipper())
{
delete ptr;
}
END_SECTION
START_SECTION((virtual ~IDRipper()))
{
// TODO
}
END_SECTION
START_SECTION((void rip(std::map< String, std::pair< std::vector< ProteinIdentification >, std::vector< PeptideIdentification > > > &ripped, std::vector< ProteinIdentification > &proteins, std::vector< PeptideIdentification > &peptides)))
{
// TODO
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/BSpline2d_test.cpp | .cpp | 5,061 | 185 | // 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/test_config.h>
///////////////////////////
#include <OpenMS/MATH/MISC/BSpline2d.h>
#include <OpenMS/FORMAT/CsvFile.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(BSpline2d, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
BSpline2d* ptr = nullptr;
BSpline2d* null_ptr = nullptr;
/* load data generated by R code:
# add noise on x and y=sin(x)
s <- seq(-5,5,0.1)
x <- s + rnorm(length(s))
y <- 10 * sin(x) + rnorm(length(s))
# duplicate x entries by subsampling length(x) rows with replacement
df <- cbind(x,y)
sub <- df[sample(length(x), replace=TRUE),]
# add (again) noise to y values
sub[,2] = sub[,2] + rnorm(length(sub[,2]))
# append and order by x
df <- rbind(df, sub)
df <- df[order(df[,1]),]
*/
CsvFile sinus_file(OPENMS_GET_TEST_DATA_PATH("BSpline2d_test_sinus.txt"), '\t');
std::vector<double> x;
std::vector<double> y;
for (Size i = 0; i != sinus_file.rowCount(); ++i)
{
StringList sl;
if (sinus_file.getRow(i, sl))
{
x.push_back(sl[0].toDouble());
y.push_back(sl[1].toDouble());
}
}
START_SECTION((BSpline2d(const std::vector< double > &x, const std::vector< double > &y, double wave_length=0, BoundaryCondition boundary_condition=BC_ZERO_ENDPOINTS, Size num_nodes=0)))
{
ptr = new BSpline2d(x, y);
TEST_NOT_EQUAL(ptr, null_ptr)
BSpline2d(x, y, 10, BSpline2d::BC_ZERO_ENDPOINTS);
BSpline2d(x, y, 1, BSpline2d::BC_ZERO_FIRST);
BSpline2d(x, y, 100, BSpline2d::BC_ZERO_SECOND);
}
END_SECTION
START_SECTION((virtual ~BSpline2d()))
{
delete ptr;
}
END_SECTION
START_SECTION((bool solve(const std::vector< double > &y)))
{
BSpline2d b(x, y);
b.solve(y);
}
END_SECTION
START_SECTION((double eval(const double x) const))
{
// calculate error of noisy points
double mean_squared_error_noisy(0.0);
for (Size i = 0; i != x.size(); ++i)
{
double error = y[i] - 10.0 * sin(x[i]);
//cout << "Original Error: " << error << endl;
mean_squared_error_noisy += error * error;
}
mean_squared_error_noisy /= (double)x.size();
{
// calculate error after smoothing
BSpline2d b(x, y);
double mean_squared_error_smoothed(0.0);
for (Size i = 0; i != x.size(); ++i)
{
double error = b.eval(x[i]) - 10.0 * sin(x[i]);
//cout << "Smoothed Error: " << error << endl;
mean_squared_error_smoothed += error * error;
}
mean_squared_error_smoothed /= (double)x.size();
// error of smoothed signal must be much lower (for this data it should be at least half of the unsmoothed one)
TEST_EQUAL(mean_squared_error_smoothed < 0.5 * mean_squared_error_noisy, true)
}
{
// calculate error after regularized smoothing
BSpline2d b(x, y, 2.0);
double mean_squared_error_smoothed(0.0);
for (Size i = 0; i != x.size(); ++i)
{
double error = b.eval(x[i]) - 10.0 * sin(x[i]);
mean_squared_error_smoothed += error * error;
}
mean_squared_error_smoothed /= (double)x.size();
// error of smoothed signal must be lower (for this data it should be at least half of the unsmoothed one)
TEST_EQUAL(mean_squared_error_smoothed < 0.5 * mean_squared_error_noisy, true)
}
}
END_SECTION
START_SECTION((double derivative(const double x) const))
{
{
// calculate error on first derivative of smoothed points.
// preserve curvature - otherwise we get large errors on derivative
BSpline2d b(x, y, 0, BSpline2d::BC_ZERO_SECOND);
double mean_absolute_derivative_error(0.0);
for (Size i = 0; i != x.size(); ++i)
{
double error = fabs(b.derivative(x[i]) - 10.0 * cos(x[i]));
mean_absolute_derivative_error += error;
}
mean_absolute_derivative_error /= (double)x.size();
//cout << mean_absolute_derivative_error << endl;
TEST_EQUAL(mean_absolute_derivative_error < 10.0 * 0.2, true)
}
}
END_SECTION
START_SECTION((bool ok() const))
{
vector<double> x;
vector<double> y;
for (Size i = 0; i != 10; ++i)
{
x.push_back(i);
y.push_back(i);
}
BSpline2d b1(x, y, 0, BSpline2d::BC_ZERO_SECOND, 100);
double y1 = b1.eval(5.5);
TEST_EQUAL(b1.ok(), true);
x.clear();
y.clear();
for (Size i = 10; i != 0; --i)
{
x.push_back(i);
y.push_back(i);
}
BSpline2d b2(x, y, 0, BSpline2d::BC_ZERO_SECOND, 100);
double y2 = b2.eval(5.5);
TEST_EQUAL(b2.ok(), true);
TEST_REAL_SIMILAR(y1,y2);
}
END_SECTION
START_SECTION((void debug(bool enable)))
{
NOT_TESTABLE
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IsobaricNormalizer_test.cpp | .cpp | 2,475 | 94 | // 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/IsobaricNormalizer.h>
///////////////////////////
#include <OpenMS/ANALYSIS/QUANTITATION/ItraqFourPlexQuantitationMethod.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
using namespace OpenMS;
using namespace std;
START_TEST(IsobaricNormalizer, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IsobaricNormalizer* ptr = nullptr;
IsobaricNormalizer* null_ptr = nullptr;
//
ItraqFourPlexQuantitationMethod quant_meth;
START_SECTION((IsobaricNormalizer(const IsobaricQuantitationMethod *const quant_method)))
{
ptr = new IsobaricNormalizer(&quant_meth);
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IsobaricNormalizer())
{
delete ptr;
}
END_SECTION
START_SECTION((IsobaricNormalizer(const IsobaricNormalizer &other)))
{
IsobaricNormalizer normalizer(&quant_meth);
IsobaricNormalizer * normalizer2 = new IsobaricNormalizer(normalizer);
TEST_NOT_EQUAL(normalizer2, null_ptr)
delete normalizer2;
// equality cannot be checked
NOT_TESTABLE
}
END_SECTION
START_SECTION((IsobaricNormalizer& operator=(const IsobaricNormalizer &rhs)))
{
IsobaricNormalizer normalizer(&quant_meth);
IsobaricNormalizer normalizer2(&quant_meth);
normalizer2 = normalizer;
// equality cannot be checked
NOT_TESTABLE
}
END_SECTION
START_SECTION((void normalize(ConsensusMap &consensus_map)))
{
IsobaricNormalizer normalizer(&quant_meth);
ConsensusXMLFile cm_file;
ConsensusMap cm_in;
cm_file.load(OPENMS_GET_TEST_DATA_PATH("IsobaricNormalizer.consensusXML"),cm_in);
normalizer.normalize(cm_in);
String cm_file_out;
NEW_TMP_FILE(cm_file_out);
cm_file.store(cm_file_out,cm_in);
WHITELIST("<?xml-stylesheet");
TEST_FILE_SIMILAR(cm_file_out,OPENMS_GET_TEST_DATA_PATH("IsobaricNormalizer_out.consensusXML"));
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/DBoundingBox_test.cpp | .cpp | 11,089 | 387 | // 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/DATASTRUCTURES/DBoundingBox.h>
/////////////////////////////////////////////////////////////
#include <unordered_set>
#include <unordered_map>
#include <sstream>
using namespace OpenMS;
using namespace std;
START_TEST(DBoundingBox, "$Id$")
/////////////////////////////////////////////////////////////
typedef DBoundingBox<1> BB1;
typedef DBoundingBox<2> BB2;
BB1* ptr1 = nullptr;
BB1* nullPointer1 = nullptr;
START_SECTION(DBoundingBox())
ptr1 = new BB1;
TEST_NOT_EQUAL(ptr1, nullPointer1)
END_SECTION
START_SECTION(~DBoundingBox())
delete ptr1;
END_SECTION
BB2* ptr2 = nullptr;
BB2* nullPointer2 = nullptr;
START_SECTION([EXTRA] DBoundingBox())
ptr2 = new BB2;
TEST_NOT_EQUAL(ptr2, nullPointer2)
END_SECTION
START_SECTION([EXTRA] ~DBoundingBox())
delete ptr2;
END_SECTION
START_SECTION(DBoundingBox(const PositionType& minimum, const PositionType& maximum))
{
DPosition<1> min(2), max(5);
BB1 bb(min,max);
TEST_REAL_SIMILAR(bb.minPosition()[0], 2);
TEST_REAL_SIMILAR(bb.maxPosition()[0], 5);
}
END_SECTION
START_SECTION(DBoundingBox(const DBoundingBox &rhs))
BB2 bb(DPosition<2>(1,2),DPosition<2>(3,4));
BB2 bb_copy(bb);
TEST_REAL_SIMILAR(bb.minPosition()[0],bb_copy.minPosition()[0]);
TEST_REAL_SIMILAR(bb.minPosition()[1],bb_copy.minPosition()[1]);
TEST_REAL_SIMILAR(bb.maxPosition()[0],bb_copy.maxPosition()[0]);
TEST_REAL_SIMILAR(bb.maxPosition()[1],bb_copy.maxPosition()[1]);
END_SECTION
START_SECTION(DBoundingBox& operator=(const DBoundingBox &rhs))
BB2 bb(DPosition<2>(1,2),DPosition<2>(3,4));
BB2 bb_copy;
bb_copy = bb;
TEST_REAL_SIMILAR(bb.minPosition()[0],bb_copy.minPosition()[0]);
TEST_REAL_SIMILAR(bb.minPosition()[1],bb_copy.minPosition()[1]);
TEST_REAL_SIMILAR(bb.maxPosition()[0],bb_copy.maxPosition()[0]);
TEST_REAL_SIMILAR(bb.maxPosition()[1],bb_copy.maxPosition()[1]);
END_SECTION
START_SECTION(DBoundingBox& operator=(const Base &rhs))
BB2::Base bb(DPosition<2>(1,2),DPosition<2>(3,4));
BB2 bb_copy;
bb_copy = bb;
TEST_REAL_SIMILAR(bb.minPosition()[0],bb_copy.minPosition()[0]);
TEST_REAL_SIMILAR(bb.minPosition()[1],bb_copy.minPosition()[1]);
TEST_REAL_SIMILAR(bb.maxPosition()[0],bb_copy.maxPosition()[0]);
TEST_REAL_SIMILAR(bb.maxPosition()[1],bb_copy.maxPosition()[1]);
END_SECTION
START_SECTION(bool isEmpty() const)
BB2 bb;
bb = BB2::empty;
TEST_EQUAL(bb.isEmpty(),true);
bb = BB2::zero;
TEST_EQUAL(bb.isEmpty(),true);
bb = BB2(DPosition<2>(1,2),DPosition<2>(3,4));
TEST_EQUAL(bb.isEmpty(),false);
END_SECTION
START_SECTION(void enlarge(const PositionType& p))
BB2 bb2h;
TEST_EQUAL(bb2h.encloses(11,13),false);
TEST_EQUAL(bb2h.encloses(10,1),false);
bb2h.enlarge(BB2::PositionType(11,13));
TEST_EQUAL(bb2h.encloses(11,13),true);
TEST_EQUAL(bb2h.encloses(10,1),false);
bb2h.enlarge(BB2::PositionType(9,0));
TEST_EQUAL(bb2h.encloses(11,13),true);
TEST_EQUAL(bb2h.encloses(10,1),true);
END_SECTION
START_SECTION((void enlarge(CoordinateType x, CoordinateType y)))
BB2 bb2h;
TEST_EQUAL(bb2h.encloses(11,13),false);
TEST_EQUAL(bb2h.encloses(10,1),false);
bb2h.enlarge(11,13);
TEST_EQUAL(bb2h.encloses(11,13),true);
TEST_EQUAL(bb2h.encloses(10,1),false);
bb2h.enlarge(9,0);
TEST_EQUAL(bb2h.encloses(11,13),true);
TEST_EQUAL(bb2h.encloses(10,1),true);
END_SECTION
START_SECTION(bool operator == (const DBoundingBox& rhs) const)
BB2 bb2;
bb2.enlarge(9,0);
BB2 bb2_copy(bb2);
TEST_EQUAL(bb2==bb2_copy,true);
END_SECTION
START_SECTION(bool operator == (const Base& rhs) const)
BB2 bb2;
bb2.enlarge(9,0);
BB2::Base bb2_copy_base(bb2);
TEST_EQUAL(bb2==bb2_copy_base,true);
END_SECTION
START_SECTION((bool encloses(CoordinateType x, CoordinateType y) const))
BB2 tmp;
tmp.setMinX( 100 );
tmp.setMinY( 200 );
tmp.setMaxX( 300 );
tmp.setMaxY( 400 );
TEST_EQUAL(tmp.encloses(10,200),false);
TEST_EQUAL(tmp.encloses(100,200),true);
TEST_EQUAL(tmp.encloses(200,200),true);
TEST_EQUAL(tmp.encloses(300,200),true);
TEST_EQUAL(tmp.encloses(310,200),false);
TEST_EQUAL(tmp.encloses(10,400),false);
TEST_EQUAL(tmp.encloses(100,400),true);
TEST_EQUAL(tmp.encloses(200,400),true);
TEST_EQUAL(tmp.encloses(300,400),true);
TEST_EQUAL(tmp.encloses(310,400),false);
TEST_EQUAL(tmp.encloses(200,190),false);
TEST_EQUAL(tmp.encloses(200,200),true);
TEST_EQUAL(tmp.encloses(200,300),true);
TEST_EQUAL(tmp.encloses(200,400),true);
TEST_EQUAL(tmp.encloses(200,410),false);
TEST_EQUAL(tmp.encloses(0,0),false);
TEST_EQUAL(tmp.encloses(100,200),true);
TEST_EQUAL(tmp.encloses(300,200),true);
TEST_EQUAL(tmp.encloses(100,400),true);
TEST_EQUAL(tmp.encloses(300,400),true);
END_SECTION
START_SECTION(bool encloses(const PositionType& position) const)
BB2 tmp;
tmp.setMinX( 100 );
tmp.setMinY( 200 );
tmp.setMaxX( 300 );
tmp.setMaxY( 400 );
TEST_EQUAL(tmp.encloses(BB2::PositionType(10,200)),false);
TEST_EQUAL(tmp.encloses(BB2::PositionType(100,200)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(200,200)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(300,200)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(310,200)),false);
TEST_EQUAL(tmp.encloses(BB2::PositionType(10,400)),false);
TEST_EQUAL(tmp.encloses(BB2::PositionType(100,400)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(200,400)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(300,400)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(310,400)),false);
TEST_EQUAL(tmp.encloses(BB2::PositionType(200,190)),false);
TEST_EQUAL(tmp.encloses(BB2::PositionType(200,200)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(200,300)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(200,400)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(200,410)),false);
TEST_EQUAL(tmp.encloses(BB2::PositionType(0,0)),false);
TEST_EQUAL(tmp.encloses(BB2::PositionType(100,200)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(300,200)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(100,400)),true);
TEST_EQUAL(tmp.encloses(BB2::PositionType(300,400)),true);
END_SECTION
START_SECTION(bool intersects(const DBoundingBox& bounding_box) const)
DPosition<2> p1,p2,p3,one,two;
p1[0]=-1.0f;
p1[1]=-2.0f;
p2[0]=3.0f;
p2[1]=4.0f;
p3[0]=-10.0f;
p3[1]=20.0f;
one[0]=1;
one[1]=1;
two[0]=2;
two[1]=2;
BB2 r2;
r2.setMin(p1);
r2.setMax(p2);
BB2 r3(r2);
TEST_EQUAL(r2.intersects(r3),true)
r3.setMaxX(10.0f);
TEST_EQUAL(r2.intersects(r3),true)
r3.setMax(r2.maxPosition()+one);
TEST_EQUAL(r2.intersects(r3),true)
r3.setMin(r2.maxPosition()+one);
r3.setMax(r2.maxPosition()+two);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMin(r2.minPosition());
r3.setMinX(10.0f);
r3.setMax(r3.minPosition()+one);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(-10.0f);
r3.setMinY(-10.0f);
r3.setMax(r3.minPosition()+one);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(-10.0f);
r3.setMinY(-10.0f);
r3.setMaxX(0.0f);
r3.setMaxY(-9.0f);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(-10.0f);
r3.setMinY(-10.0f);
r3.setMaxX(10.0f);
r3.setMaxY(-9.0f);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(-10.0f);
r3.setMinY(0.0f);
r3.setMaxX(-9.0f);
r3.setMaxY(1.0f);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(-10.0f);
r3.setMinY(10.0f);
r3.setMax(r3.minPosition()+one);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(-10.0f);
r3.setMinY(0.0f);
r3.setMaxX(-9.0f);
r3.setMaxY(10.0f);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(9.0f);
r3.setMinY(0.0f);
r3.setMaxX(10.0f);
r3.setMaxY(10.0f);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(9.0f);
r3.setMinY(0.0f);
r3.setMaxX(10.0f);
r3.setMaxY(10.0f);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(9.0f);
r3.setMinY(-5.0f);
r3.setMaxX(10.0f);
r3.setMaxY(0.0f);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(9.0f);
r3.setMinY(-5.0f);
r3.setMaxX(10.0f);
r3.setMaxY(5.0f);
TEST_EQUAL(r2.intersects(r3),false)
r3.setMinX(-5.0f);
r3.setMinY(-5.0f);
r3.setMaxX(0.0f);
r3.setMaxY(0.0f);
TEST_EQUAL(r2.intersects(r3),true)
r3.setMinX(-5.0f);
r3.setMinY(-5.0f);
r3.setMaxX(5.0f);
r3.setMaxY(0.0f);
TEST_EQUAL(r2.intersects(r3),true)
r3.setMinX(-5.0f);
r3.setMinY(-5.0f);
r3.setMaxX(5.0f);
r3.setMaxY(5.0f);
TEST_EQUAL(r2.intersects(r3),true)
r3.setMinX(0.0f);
r3.setMinY(-5.0f);
r3.setMaxX(0.0f);
r3.setMaxY(0.0f);
TEST_EQUAL(r2.intersects(r3),true)
r3.setMinX(0.0f);
r3.setMinY(-5.0f);
r3.setMaxX(5.0f);
r3.setMaxY(0.0f);
TEST_EQUAL(r2.intersects(r3),true)
r3.setMinX(0.0f);
r3.setMinY(-5.0f);
r3.setMaxX(5.0f);
r3.setMaxY(5.0f);
TEST_EQUAL(r2.intersects(r3),true)
END_SECTION
START_SECTION((template <UInt D> std::ostream & operator<<(std::ostream &os, const DBoundingBox< D > &bounding_box)))
{
std::ostringstream os;
DPosition<1> min(2), max(5);
BB1 bb(min,max);
os << bb;
TEST_STRING_EQUAL( os.str(),
"--DBOUNDINGBOX BEGIN--\n"
"MIN --> 2.0\n"
"MAX --> 5.0\n"
"--DBOUNDINGBOX END--\n");
}
END_SECTION
START_SECTION(([EXTRA] std::hash<DBoundingBox<D>>))
{
// Test that equal bounding boxes have equal hashes
BB2 bb1(DPosition<2>(1.0, 2.0), DPosition<2>(3.0, 4.0));
BB2 bb2(DPosition<2>(1.0, 2.0), DPosition<2>(3.0, 4.0));
BB2 bb3(DPosition<2>(5.0, 6.0), DPosition<2>(7.0, 8.0));
std::hash<BB2> hasher;
// Equal objects must have equal hashes
TEST_EQUAL(bb1 == bb2, true)
TEST_EQUAL(hasher(bb1), hasher(bb2))
// Different objects should (likely) have different hashes
TEST_EQUAL(bb1 == bb3, false)
TEST_NOT_EQUAL(hasher(bb1), hasher(bb3))
// Test 1D bounding box hash
BB1 bb1d_a(DPosition<1>(1.0), DPosition<1>(5.0));
BB1 bb1d_b(DPosition<1>(1.0), DPosition<1>(5.0));
BB1 bb1d_c(DPosition<1>(2.0), DPosition<1>(6.0));
std::hash<BB1> hasher1d;
TEST_EQUAL(bb1d_a == bb1d_b, true)
TEST_EQUAL(hasher1d(bb1d_a), hasher1d(bb1d_b))
TEST_NOT_EQUAL(hasher1d(bb1d_a), hasher1d(bb1d_c))
// Test use in unordered_set
std::unordered_set<BB2> bb_set;
bb_set.insert(bb1);
bb_set.insert(bb2); // Should not be inserted (equal to bb1)
bb_set.insert(bb3);
TEST_EQUAL(bb_set.size(), 2)
TEST_EQUAL(bb_set.count(bb1), 1)
TEST_EQUAL(bb_set.count(bb3), 1)
// Test use in unordered_map
std::unordered_map<BB2, std::string> bb_map;
bb_map[bb1] = "first";
bb_map[bb2] = "second"; // Should overwrite bb1's value
bb_map[bb3] = "third";
TEST_EQUAL(bb_map.size(), 2)
TEST_EQUAL(bb_map[bb1], "second")
TEST_EQUAL(bb_map[bb3], "third")
// Test hash consistency with default-constructed (empty) bounding boxes
BB2 default1;
BB2 default2;
TEST_EQUAL(default1 == default2, true)
TEST_EQUAL(hasher(default1), hasher(default2))
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SpectraMerger_test.cpp | .cpp | 7,460 | 203 | // 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, Andreas Bertsch, Lars Nilse $
// --------------------------------------------------------------------------
//
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/PROCESSING/SPECTRAMERGING/SpectraMerger.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/KERNEL/MSExperiment.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(SpectraMerger, "$Id$")
/////////////////////////////////////////////////////////////
SpectraMerger* e_ptr = nullptr;
SpectraMerger* e_nullPointer = nullptr;
START_SECTION((SpectraMerger()))
e_ptr = new SpectraMerger;
TEST_NOT_EQUAL(e_ptr, e_nullPointer)
END_SECTION
START_SECTION((~SpectraMerger()))
delete e_ptr;
END_SECTION
e_ptr = new SpectraMerger();
START_SECTION((SpectraMerger(const SpectraMerger& source)))
SpectraMerger copy(*e_ptr);
TEST_EQUAL(copy.getParameters(), e_ptr->getParameters())
END_SECTION
START_SECTION((SpectraMerger& operator=(const SpectraMerger& source)))
SpectraMerger copy;
copy = *e_ptr;
TEST_EQUAL(copy.getParameters(), e_ptr->getParameters())
END_SECTION
START_SECTION((template < typename MapType > void mergeSpectraBlockWise(MapType &exp)))
PeakMap exp, exp2;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("SpectraMerger_input_2.mzML"), exp);
TEST_EQUAL(exp.size(), 144)
exp2 = exp;
SpectraMerger merger;
Param p;
p.setValue("mz_binning_width", 0.0001, "Max m/z distance of two peaks to be merged.", {"advanced"});
p.setValue("mz_binning_width_unit", "Da", "Unit in which the distance between two peaks is given.", {"advanced"});
p.setValue("block_method:rt_block_size", 5);
p.setValue("block_method:ms_levels", ListUtils::create<Int>("1"));
merger.setParameters(p);
merger.mergeSpectraBlockWise(exp);
TEST_EQUAL(exp.size(), 130);
exp=exp2;
p.setValue("block_method:rt_block_size", 4);
p.setValue("block_method:ms_levels", ListUtils::create<Int>("2"));
merger.setParameters(p);
merger.mergeSpectraBlockWise(exp);
TEST_EQUAL(exp.size(), 50);
TEST_REAL_SIMILAR(exp[0].getRT(),201.0275)
TEST_REAL_SIMILAR(exp[1].getRT(),204.34075)
TEST_EQUAL(exp[1].getMSLevel(), 2);
TEST_EQUAL(exp[2].getMSLevel(), 1);
exp=exp2;
p.setValue("block_method:rt_block_size", 4);
p.setValue("block_method:ms_levels", ListUtils::create<Int>("1,2"));
merger.setParameters(p);
merger.mergeSpectraBlockWise(exp);
TEST_EQUAL(exp.size(), 37);
END_SECTION
START_SECTION((template < typename MapType > void mergeSpectraPrecursors(MapType &exp)))
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("SpectraMerger_input_precursor.mzML"), exp);
SpectraMerger merger;
TEST_EQUAL(exp.size(), 17)
Param p;
p.setValue("mz_binning_width", 0.3, "Max m/z distance of two peaks to be merged.", {"advanced"});
p.setValue("mz_binning_width_unit", "Da", "Unit in which the distance between two peaks is given.", {"advanced"});
// same precursor MS/MS merging
p.setValue("precursor_method:mz_tolerance", 10e-5, "Max m/z distance of the precursor entries of two spectra to be merged in [Da].");
p.setValue("precursor_method:rt_tolerance", 5.0, "Max RT distance of the precursor entries of two spectra to be merged in [s].");
merger.setParameters(p);
merger.mergeSpectraPrecursors(exp);
PeakMap exp2;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("SpectraMerger_output_precursor.mzML"), exp2);
TEST_EQUAL(exp.size(), exp2.size());
ABORT_IF(exp.size() != exp2.size());
for (Size i=0;i<exp.size();++i)
{
TEST_EQUAL(exp[i].size(), exp2[i].size())
TEST_EQUAL(exp[i].getMSLevel (), exp2[i].getMSLevel ())
}
END_SECTION
START_SECTION((bool areMassesMatched(double mz1, double mz2, double tol_ppm, int max_c)))
SpectraMerger merger;
bool non_matched = merger.areMassesMatched(100, 1000, 10, 5);
bool matched = merger.areMassesMatched(1000, 1000.001, 10, 5);
TEST_EQUAL(non_matched, false);
TEST_EQUAL(matched, true);
END_SECTION
START_SECTION((template < typename MapType > void averageGaussian(MapType &exp)))
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("SpectraMerger_input_3.mzML"), exp); // profile mode
SpectraMerger merger;
TEST_EQUAL(exp.size(), 28)
Param p;
p.setValue("mz_binning_width", 0.0001, "Max m/z distance of two peaks to be merged.", {"advanced"});
p.setValue("mz_binning_width_unit", "Da", "Unit in which the distance between two peaks is given.", {"advanced"});
// same precursor MS/MS merging
p.setValue("average_gaussian:spectrum_type", "automatic", "Spectrum type of the MS level to be averaged");
p.setValue("average_gaussian:ms_level", 1, "Average spectra of this level. All other spectra remain unchanged.");
p.setValue("average_gaussian:rt_FWHM", 5.0, "FWHM of Gauss curve in seconds to be averaged over.");
p.setValue("average_gaussian:cutoff", 0.01, "Intensity cutoff for Gaussian. The Gaussian RT profile decreases from 1 at its apex to 0 at infinity. Spectra for which the intensity of the Gaussian drops below the cutoff do not contribute to the average.", {"advanced"});
merger.setParameters(p);
merger.average(exp,"gaussian");
PeakMap exp2;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("SpectraMerger_output_3.mzML"), exp2);
TEST_EQUAL(exp.size(), exp2.size());
ABORT_IF(exp.size() != exp2.size());
for (Size i=0;i<exp.size();++i)
{
TEST_EQUAL(exp[i].size(), exp2[i].size())
TEST_EQUAL(exp[i].getMSLevel (), exp2[i].getMSLevel ())
}
END_SECTION
START_SECTION((template < typename MapType > void averageGaussian(MapType &exp)))
PeakMap exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("SpectraMerger_input_4.mzML"), exp); // centroid mode
SpectraMerger merger;
TEST_EQUAL(exp.size(), 28)
Param p;
p.setValue("mz_binning_width", 0.0001, "Max m/z distance of two peaks to be merged.", {"advanced"});
p.setValue("mz_binning_width_unit", "Da", "Unit in which the distance between two peaks is given.", {"advanced"});
// same precursor MS/MS merging
p.setValue("average_gaussian:spectrum_type", "automatic", "Spectrum type of the MS level to be averaged");
p.setValue("average_gaussian:ms_level", 1, "Average spectra of this level. All other spectra remain unchanged.");
p.setValue("average_gaussian:rt_FWHM", 5.0, "FWHM of Gauss curve in seconds to be averaged over.");
p.setValue("average_gaussian:cutoff", 0.01, "Intensity cutoff for Gaussian. The Gaussian RT profile decreases from 1 at its apex to 0 at infinity. Spectra for which the intensity of the Gaussian drops below the cutoff do not contribute to the average.", {"advanced"});
merger.setParameters(p);
merger.average(exp,"gaussian");
PeakMap exp2;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("SpectraMerger_output_4.mzML"), exp2);
TEST_EQUAL(exp.size(), exp2.size());
ABORT_IF(exp.size() != exp2.size());
for (Size i=0;i<exp.size();++i)
{
TEST_EQUAL(exp[i].size(), exp2[i].size())
TEST_EQUAL(exp[i].getMSLevel (), exp2[i].getMSLevel ())
}
END_SECTION
delete e_ptr;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SingleLinkage_test.cpp | .cpp | 3,343 | 124 | // 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/SingleLinkage.h>
#include <OpenMS/ML/CLUSTERING/ClusterAnalyzer.h>
#include <OpenMS/DATASTRUCTURES/DistanceMatrix.h>
#include <vector>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(SingleLinkage, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
SingleLinkage* ptr = nullptr;
SingleLinkage* nullPointer = nullptr;
START_SECTION(SingleLinkage())
{
ptr = new SingleLinkage();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~SingleLinkage())
{
delete ptr;
}
END_SECTION
ptr = new SingleLinkage();
START_SECTION((SingleLinkage(const SingleLinkage &source)))
{
SingleLinkage copy(*ptr);
}
END_SECTION
START_SECTION((SingleLinkage& operator=(const SingleLinkage &source)))
{
SingleLinkage copy;
copy = *ptr;
}
END_SECTION
START_SECTION((void operator()(DistanceMatrix< float > &original_distance, std::vector<BinaryTreeNode>& cluster_tree, const float threshold=1) const))
{
DistanceMatrix<float> matrix(6,666);
matrix.setValue(1,0,0.5f);
matrix.setValue(2,0,0.8f);
matrix.setValue(2,1,0.3f);
matrix.setValue(3,0,0.6f);
matrix.setValue(3,1,0.8f);
matrix.setValue(3,2,0.8f);
matrix.setValue(4,0,0.8f);
matrix.setValue(4,1,0.8f);
matrix.setValue(4,2,0.8f);
matrix.setValue(4,3,0.4f);
matrix.setValue(5,0,0.7f);
matrix.setValue(5,1,0.8f);
matrix.setValue(5,2,0.8f);
matrix.setValue(5,3,0.8f);
matrix.setValue(5,4,0.8f);
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.5f));
//~ tree.push_back(BinaryTreeNode(0,1,0.6f));
//~ tree.push_back(BinaryTreeNode(0,1,0.7f));
tree.push_back(BinaryTreeNode(1,2,0.3f));
tree.push_back(BinaryTreeNode(3,4,0.4f));
tree.push_back(BinaryTreeNode(0,1,0.5f));
tree.push_back(BinaryTreeNode(0,3,0.6f));
tree.push_back(BinaryTreeNode(0,5,0.7f));
(*ptr)(matrix,result);
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);
}
//~ float th(0.6f);
//~ tree.pop_back();
//~ tree.pop_back();
//~ result.clear();
//~ (*ptr)(matrix,result,th);
//~ 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
delete ptr;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SpectralDeconvolution_test.cpp | .cpp | 4,766 | 140 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Jihyung Kim$
// $Authors: Jihyung Kim$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/TOPDOWN/SpectralDeconvolution.h>
#include <OpenMS/FORMAT/MzMLFile.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(SpectralDeconvolution, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
SpectralDeconvolution* ptr = 0;
SpectralDeconvolution* null_ptr = 0;
START_SECTION(SpectralDeconvolution())
{
ptr = new SpectralDeconvolution();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~SpectralDeconvolution())
{
delete ptr;
}
END_SECTION
/// < public methods without tests >
/// - default constructors and operators are not used (copy, move, assignment)
/// - setTargetMasses : only private member (which can not be accessed) is affected
/// - getDecoyDeconvolvedSpectrum, isDecoy, addPreviouslyDeconvolvedMonoMass, clearPreviouslyDeconvolvedMonoMasses: under development
/// - getAvgPPMError
SpectralDeconvolution fd_algo = SpectralDeconvolution();
Param fd_param;
fd_param.setValue("min_charge", 5);
fd_param.setValue("max_charge", 20);
START_SECTION((static int getNominalMass(const double mass)))
{
double tmp_mass1 = 10000;
double tmp_mass2 = 25000;
TEST_EQUAL(fd_algo.getNominalMass(tmp_mass1), 9995);
TEST_EQUAL(fd_algo.getNominalMass(tmp_mass2), 24987);
}
END_SECTION
START_SECTION((void calculateAveragine(const bool use_RNA_averagine)))
{
fd_param.setValue("max_mass", 2000.);
fd_algo.setParameters(fd_param);
SpectralDeconvolution tmp_algo = SpectralDeconvolution();
fd_param.setValue("max_mass", 100.);
tmp_algo.setParameters(fd_param);
fd_algo.calculateAveragine(false);
tmp_algo.calculateAveragine(true);
const auto &precalculated_avg = fd_algo.getAveragine();
const auto &precalculated_avg_tmp = tmp_algo.getAveragine();
TEST_EQUAL(precalculated_avg.getMaxIsotopeIndex(), 199);
TEST_EQUAL(precalculated_avg.getApexIndex(50), 0);
TOLERANCE_ABSOLUTE(0.1)
TEST_REAL_SIMILAR(precalculated_avg.getAverageMassDelta(50), 0.0296591659229435);
TEST_EQUAL(precalculated_avg_tmp.getMaxIsotopeIndex(), 199);
TEST_EQUAL(precalculated_avg_tmp.getApexIndex(50), 0);
TEST_REAL_SIMILAR(precalculated_avg_tmp.getAverageMassDelta(50), 0.025145817950033234);
}
END_SECTION
START_SECTION((PrecalculatedAveragine& getAveragine()))
{
const auto &precalculated_avg = fd_algo.getAveragine();
TEST_EQUAL(precalculated_avg.getMaxIsotopeIndex(), 199);
TEST_EQUAL(precalculated_avg.getApexIndex(50), 0);
TEST_REAL_SIMILAR(precalculated_avg.getAverageMassDelta(50), 0.0296591659229435);
}
END_SECTION
// load test data
PeakMap input;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("FLASHDeconv_sample_input1.mzML"), input);
// resetting fd_algo based on the test data
fd_param.setValue("max_mass", 50000.);
fd_algo.setParameters(fd_param);
fd_algo.calculateAveragine(false);
START_SECTION(DeconvolvedSpectrum& getDeconvolvedSpectrum())
{
fd_algo.performSpectrumDeconvolution(input[3], 4, PeakGroup());
DeconvolvedSpectrum d_ms1_spec = fd_algo.getDeconvolvedSpectrum();
for (auto pg : d_ms1_spec) {
std::cout << pg.getMonoMass() << std::endl;
}
// TEST_EQUAL(d_ms1_spec.size(), 6);
}
END_SECTION
START_SECTION((DeconvolvedSpectrum& performSpectrumDeconvolution(const MSSpectrum &spec, const std::vector< DeconvolvedSpectrum > &survey_scans, const int scan_number, const bool write_detail, const std::map< int, std::vector< std::vector< double >>> &precursor_map_for_FLASHIda)))
{
fd_algo.performSpectrumDeconvolution(input[3], 4, PeakGroup());
DeconvolvedSpectrum d_ms1_spec = fd_algo.getDeconvolvedSpectrum();
fd_algo.performSpectrumDeconvolution(input[5], 6, PeakGroup());
DeconvolvedSpectrum d_ms2_spec = fd_algo.getDeconvolvedSpectrum();
TEST_EQUAL(d_ms1_spec.getScanNumber(), 4);
// TEST_EQUAL(d_ms1_spec.size(), 6);
Precursor precursor = d_ms2_spec.getPrecursor();
TOLERANCE_ABSOLUTE(1);
TEST_EQUAL(d_ms1_spec.getPrecursorPeakGroup().size(), 0);
TEST_EQUAL(d_ms2_spec.getPrecursorPeakGroup().size(), 0);
TEST_EQUAL(precursor.getCharge(), 9);
TOLERANCE_ABSOLUTE(100);
TEST_REAL_SIMILAR(precursor.getIntensity(), 12293.4);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ItraqConstants_test.cpp | .cpp | 8,415 | 223 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/QUANTITATION/ItraqConstants.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/DATASTRUCTURES/ListUtilsIO.h>
using namespace OpenMS;
using namespace std;
START_TEST(ItraqConstants, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
ItraqConstants* ptr = nullptr;
ItraqConstants* nullPointer = nullptr;
START_SECTION(ItraqConstants())
{
ptr = new ItraqConstants();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~ItraqConstants())
{
delete ptr;
}
END_SECTION
START_SECTION((static StringList getIsotopeMatrixAsStringList(const int itraq_type, const IsotopeMatrices &isotope_corrections)))
{
ItraqConstants::IsotopeMatrices ic;
ic.resize(3);
ic[0].setMatrix<double,4,4>(ItraqConstants::ISOTOPECORRECTIONS_FOURPLEX);
ic[1].setMatrix<double,8,4>(ItraqConstants::ISOTOPECORRECTIONS_EIGHTPLEX);
ic[2].setMatrix<double,6,4>(ItraqConstants::ISOTOPECORRECTIONS_TMT_SIXPLEX);
{
StringList ics = ItraqConstants::getIsotopeMatrixAsStringList(ItraqConstants::FOURPLEX, ic);
StringList t_ics = ListUtils::create<String>("114:0.0/1.0/5.9/0.2,115:0.0/2.0/5.6/0.1,116:0.0/3.0/4.5/0.1,117:0.1/4.0/3.5/0.1");
TEST_EQUAL(ics, t_ics);
}
{
StringList ics = ItraqConstants::getIsotopeMatrixAsStringList(ItraqConstants::EIGHTPLEX, ic);
StringList t_ics = ListUtils::create<String>("113:0.0/0.0/6.89/0.22,114:0.0/0.94/5.9/0.16,115:0.0/1.88/4.9/0.1,116:0.0/2.82/3.9/0.07,117:0.06/3.77/2.99/0.0,118:0.09/4.71/1.88/0.0,119:0.14/5.66/0.87/0.0,121:0.27/7.44/0.18/0.0");
TEST_EQUAL(ics, t_ics);
}
{
StringList ics = ItraqConstants::getIsotopeMatrixAsStringList(ItraqConstants::TMT_SIXPLEX, ic);
StringList t_ics = ListUtils::create<String>("126:0.0/0.0/0.0/0.0,127:0.0/0.0/0.0/0.0,128:0.0/0.0/0.0/0.0,129:0.0/0.0/0.0/0.0,130:0.0/0.0/0.0/0.0,131:0.0/0.0/0.0/0.0");
TEST_EQUAL(ics, t_ics);
}
}
END_SECTION
START_SECTION((static void updateIsotopeMatrixFromStringList(const int itraq_type, const StringList &channels, IsotopeMatrices &isotope_corrections)))
{
ItraqConstants::IsotopeMatrices ic;
ic.resize(3);
ic[0].setMatrix<double,4,4>(ItraqConstants::ISOTOPECORRECTIONS_FOURPLEX);
ic[1].setMatrix<double,8,4>(ItraqConstants::ISOTOPECORRECTIONS_EIGHTPLEX);
ic[2].setMatrix<double,6,4>(ItraqConstants::ISOTOPECORRECTIONS_TMT_SIXPLEX);
//StringList t_ics = ListUtils::create<String>("114:0/1/5.9/0.2,115:0/2/5.6/0.1,116:0/3/4.5/0.1,117:0.1/4/3.5/0.1"); // the default
StringList t_ics = ListUtils::create<String>("114:0/1/5.9/4.2,115:3/2/5.6/0.1,116:0/3/4.5/0.1,117:0.1/4/3.5/2");
ic[0](0,3) = 4.2;
ic[0](1,0) = 3;
ic[0](3,3) = 2;
ItraqConstants::IsotopeMatrices ic_new;
ItraqConstants::updateIsotopeMatrixFromStringList(ItraqConstants::FOURPLEX, t_ics, ic_new);
TEST_EQUAL(ic_new.size(), ic.size())
for(ItraqConstants::IsotopeMatrices::size_type i = 0; i < ic_new.size() && i < ic.size(); ++i)
{
TEST_EQUAL(ic_new[i], ic[i])
}
// reset previously updated and update TMT isotope corrections
ic[0].setMatrix<double,4,4>(ItraqConstants::ISOTOPECORRECTIONS_FOURPLEX);
ic[2](0,2) = 3.4;
ic[2](1,0) = 2.1;
ic[2](4,3) = 5.1;
// StringList tmt_ics = ListUtils::create<String>("126:0/0/0/0,127:0/0/0/0,128:0/0/0/0,129:0/0/0/0,130:0/0/0/0,131:0/0/0/0"); // the original one
StringList tmt_ics = ListUtils::create<String>("126:0/0/3.4/0,127:2.1/0/0/0,128:0/0/0/0,129:0/0/0/0,130:0/0/0/5.1,131:0/0/0/0");
ItraqConstants::IsotopeMatrices ic_tmt;
ItraqConstants::updateIsotopeMatrixFromStringList(ItraqConstants::TMT_SIXPLEX, tmt_ics, ic_tmt);
TEST_EQUAL(ic_new.size(), ic.size())
for(ItraqConstants::IsotopeMatrices::size_type i = 0; i < ic_tmt.size() && i < ic.size(); ++i)
{
TEST_EQUAL(ic_tmt[i], ic[i])
}
}
END_SECTION
START_SECTION((static void initChannelMap(const int itraq_type, ChannelMapType &map)))
{
ItraqConstants::ChannelMapType map;
ItraqConstants::initChannelMap(ItraqConstants::EIGHTPLEX, map);
TEST_EQUAL(8, map.size());
TEST_EQUAL(map[119].id, 6);
TEST_EQUAL(map[119].active, false);
ItraqConstants::ChannelMapType map4;
ItraqConstants::initChannelMap(ItraqConstants::FOURPLEX, map4);
TEST_EQUAL(4, map4.size());
TEST_EQUAL(map4[114].id, 0);
TEST_EQUAL(map4[114].active, false);
ItraqConstants::ChannelMapType mapTMT;
ItraqConstants::initChannelMap(ItraqConstants::TMT_SIXPLEX, mapTMT);
TEST_EQUAL(6, mapTMT.size());
TEST_EQUAL(mapTMT[126].id, 0);
TEST_EQUAL(mapTMT[126].active, false);
TEST_EQUAL(mapTMT[129].id, 3);
TEST_EQUAL(mapTMT[129].active, false);
}
END_SECTION
START_SECTION((static void updateChannelMap(const StringList& active_channels, ChannelMapType& map)))
{
StringList active_channels = ListUtils::create<String>("114:myReference");
ItraqConstants::ChannelMapType map;
ItraqConstants::initChannelMap(ItraqConstants::FOURPLEX, map);
ItraqConstants::updateChannelMap(active_channels, map);
TEST_EQUAL(map[114].description, String("myReference"))
TEST_EQUAL(map[114].active, true);
// TMT
StringList activeTmtChannels = ListUtils::create<String>("126:myReference,129:treated,131:control");
ItraqConstants::ChannelMapType tmtMap;
ItraqConstants::initChannelMap(ItraqConstants::TMT_SIXPLEX, tmtMap);
ItraqConstants::updateChannelMap(activeTmtChannels, tmtMap);
TEST_EQUAL(tmtMap[126].description, String("myReference"))
TEST_EQUAL(tmtMap[126].active, true);
TEST_EQUAL(tmtMap[127].description, String(""))
TEST_EQUAL(tmtMap[127].active, false);
TEST_EQUAL(tmtMap[128].description, String(""))
TEST_EQUAL(tmtMap[128].active, false);
TEST_EQUAL(tmtMap[129].description, String("treated"))
TEST_EQUAL(tmtMap[129].active, true);
TEST_EQUAL(tmtMap[130].description, String(""))
TEST_EQUAL(tmtMap[130].active, false);
TEST_EQUAL(tmtMap[131].description, String("control"))
TEST_EQUAL(tmtMap[131].active, true);
}
END_SECTION
START_SECTION((static Matrix<double> translateIsotopeMatrix(const int &itraq_type, const IsotopeMatrices &isotope_corrections)))
{
ItraqConstants::IsotopeMatrices ic;
ic.resize(3);
ic[0].setMatrix<double,4,4>(ItraqConstants::ISOTOPECORRECTIONS_FOURPLEX);
ic[1].setMatrix<double,8,4>(ItraqConstants::ISOTOPECORRECTIONS_EIGHTPLEX);
ic[2].setMatrix<double,6,4>(ItraqConstants::ISOTOPECORRECTIONS_TMT_SIXPLEX);
Matrix<double> channel_frequency = ItraqConstants::translateIsotopeMatrix(ItraqConstants::FOURPLEX, ic);
std::cout << "CF: \n" << channel_frequency << "\n";
TEST_REAL_SIMILAR(channel_frequency(0,0), 0.929)
TEST_REAL_SIMILAR(channel_frequency(3,0), 0)
channel_frequency = ItraqConstants::translateIsotopeMatrix(ItraqConstants::EIGHTPLEX, ic);
std::cout << "CF: \n" << channel_frequency << "\n";
/*
0.9289 0.0094 0 0 0 0 0 0
0.0689 0.93 0.0188 0 0 0 0 0
0.0022 0.059 0.9312 0.0282 0.0006 0 0 0
0 0.0016 0.049 0.9321 0.0377 0.0009 0 0
0 0 0.001 0.039 0.9329 0.0471 0.0014 0
0 0 0 0.0007 0.0288 0.9332 0.0566 0
0 0 0 0 0 0.0188 0.9333 0.0027
0 0 0 0 0 0 0 0.9211
*/
// test lower right triangle
TEST_REAL_SIMILAR(channel_frequency(6,7), 0.0027)
TEST_REAL_SIMILAR(channel_frequency(7,7), 0.9211)
TEST_REAL_SIMILAR(channel_frequency(7,6), 0.0000)
channel_frequency = ItraqConstants::translateIsotopeMatrix(ItraqConstants::TMT_SIXPLEX, ic);
std::cout << "CF: \n" << channel_frequency << "\n";
TEST_REAL_SIMILAR(channel_frequency(0,0), 1.0)
TEST_REAL_SIMILAR(channel_frequency(1,0), 0.0)
TEST_REAL_SIMILAR(channel_frequency(0,1), 0.0)
TEST_REAL_SIMILAR(channel_frequency(3,3), 1.0)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IMSIsotopeDistribution_test.cpp | .cpp | 3,246 | 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/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSIsotopeDistribution.h>
///////////////////////////
using namespace OpenMS;
using namespace ims;
using namespace std;
START_TEST(IMSIsotopeDistribution, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IMSIsotopeDistribution* ptr = nullptr;
IMSIsotopeDistribution* null_ptr = nullptr;
START_SECTION(IMSIsotopeDistribution())
{
ptr = new IMSIsotopeDistribution();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IMSIsotopeDistribution())
{
delete ptr;
}
END_SECTION
START_SECTION((IMSIsotopeDistribution(nominal_mass_type nominalMass=0)))
{
// TODO
}
END_SECTION
START_SECTION((IMSIsotopeDistribution(mass_type mass)))
{
// TODO
}
END_SECTION
START_SECTION((IMSIsotopeDistribution(const peaks_container &peaks, nominal_mass_type nominalMass=0)))
{
// TODO
}
END_SECTION
START_SECTION((IMSIsotopeDistribution(const IMSIsotopeDistribution &distribution)))
{
// TODO
}
END_SECTION
START_SECTION((size_type size() const ))
{
// TODO
}
END_SECTION
START_SECTION((IMSIsotopeDistribution& operator=(const IMSIsotopeDistribution &distribution)))
{
// TODO
}
END_SECTION
START_SECTION((bool operator==(const IMSIsotopeDistribution &distribution) const ))
{
// TODO
}
END_SECTION
START_SECTION((bool operator!=(const IMSIsotopeDistribution &distribution) const ))
{
// TODO
}
END_SECTION
START_SECTION((IMSIsotopeDistribution& operator*=(const IMSIsotopeDistribution &distribution)))
{
// TODO
}
END_SECTION
START_SECTION((IMSIsotopeDistribution& operator*=(unsigned int pow)))
{
// TODO
}
END_SECTION
START_SECTION((mass_type getMass(size_type i) const ))
{
// TODO
}
END_SECTION
START_SECTION((abundance_type getAbundance(size_type i) const ))
{
// TODO
}
END_SECTION
START_SECTION((mass_type getAverageMass() const ))
{
// TODO
}
END_SECTION
START_SECTION((nominal_mass_type getNominalMass() const ))
{
// TODO
}
END_SECTION
START_SECTION((void setNominalMass(nominal_mass_type nominalMass)))
{
// TODO
}
END_SECTION
START_SECTION((masses_container getMasses() const ))
{
// TODO
}
END_SECTION
START_SECTION((abundances_container getAbundances() const ))
{
// TODO
}
END_SECTION
START_SECTION((void normalize()))
{
// TODO
}
END_SECTION
START_SECTION((bool empty() const ))
{
// TODO
}
END_SECTION
START_SECTION(([ims::IMSIsotopeDistribution::Peak] Peak(mass_type mass=0.0, abundance_type abundance=0.0)))
{
// TODO
}
END_SECTION
START_SECTION(([ims::IMSIsotopeDistribution::Peak] bool operator==(const Peak &peak) const ))
{
// TODO
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/RNaseDigestion_test.cpp | .cpp | 6,591 | 203 | // 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/CHEMISTRY/RNaseDigestion.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(RNaseDigestion, "$Id$")
/////////////////////////////////////////////////////////////
RNaseDigestion* rd_ptr = 0;
RNaseDigestion* rd_null = 0;
START_SECTION(([EXTRA] RNaseDigestion()))
{
rd_ptr = new RNaseDigestion;
TEST_NOT_EQUAL(rd_ptr, rd_null);
}
END_SECTION
START_SECTION([EXTRA] ~RNaseDigestion())
{
delete rd_ptr;
}
END_SECTION
START_SECTION((void setEnzyme(const String& enzyme_name)))
{
RNaseDigestion rd;
rd.setEnzyme("RNase_T1");
TEST_EQUAL(rd.getEnzymeName(), "RNase_T1");
rd.setEnzyme("cusativin");
TEST_EQUAL(rd.getEnzymeName(), "cusativin");
rd.setEnzyme("mazF");
TEST_EQUAL(rd.getEnzymeName(), "mazF");
rd.setEnzyme("colicin_E5");
TEST_EQUAL(rd.getEnzymeName(), "colicin_E5");
TEST_EXCEPTION(Exception::ElementNotFound, rd.setEnzyme("NoSuchEnzyme"));
}
END_SECTION
START_SECTION((void digest(const NASequence& rna, vector<NASequence>& output, Size min_length, Size max_length) const))
{
RNaseDigestion rd;
rd.setEnzyme("RNase_T1"); // cuts after G and leaves a 3'-phosphate
vector<NASequence> out;
rd.digest(NASequence::fromString("AUC"), out);
TEST_EQUAL(out.size(), 1);
TEST_STRING_EQUAL(out[0].toString(), "AUC");
out.clear();
rd.digest(NASequence::fromString("AGUC"), out);
TEST_EQUAL(out.size(), 2);
TEST_STRING_EQUAL(out[0].toString(), "AGp");
TEST_STRING_EQUAL(out[1].toString(), "UC");
out.clear();
rd.digest(NASequence::fromString("pAUGUCGCAG"), out);
TEST_EQUAL(out.size(), 3);
TEST_STRING_EQUAL(out[0].toString(), "pAUGp");
TEST_STRING_EQUAL(out[1].toString(), "UCGp");
TEST_STRING_EQUAL(out[2].toString(), "CAG");
out.clear();
// RNase T1 should cut after G and m1G, but not after Gm:
rd.digest(NASequence::fromString("G[m1G][Gm]A"), out);
TEST_EQUAL(out.size(), 3);
TEST_STRING_EQUAL(out[0].toString(), "Gp");
TEST_STRING_EQUAL(out[1].toString(), "[m1G]p");
TEST_STRING_EQUAL(out[2].toString(), "[Gm]A");
out.clear();
rd.setMissedCleavages(2);
rd.digest(NASequence::fromString("pAUGUCGCAG"), out);
TEST_EQUAL(out.size(), 6);
TEST_STRING_EQUAL(out[0].toString(), "pAUGp");
TEST_STRING_EQUAL(out[1].toString(), "pAUGUCGp");
TEST_STRING_EQUAL(out[2].toString(), "pAUGUCGCAG");
TEST_STRING_EQUAL(out[3].toString(), "UCGp");
TEST_STRING_EQUAL(out[4].toString(), "UCGCAG");
TEST_STRING_EQUAL(out[5].toString(), "CAG");
out.clear();
rd.setEnzyme("cusativin");
rd.setMissedCleavages(0);
rd.digest(NASequence::fromString("CCCAUCCG"), out);
TEST_EQUAL(out.size(), 3);
TEST_STRING_EQUAL(out[0].toString(), "CCCp");
TEST_STRING_EQUAL(out[1].toString(), "AUCCp");
TEST_STRING_EQUAL(out[2].toString(), "G");
out.clear();
rd.setEnzyme("cusativin");
rd.setMissedCleavages(0);
rd.digest(NASequence::fromString("CCCAUCCG"), out);
TEST_EQUAL(out.size(), 3);
TEST_STRING_EQUAL(out[0].toString(), "CCCp");
TEST_STRING_EQUAL(out[1].toString(), "AUCCp");
TEST_STRING_EQUAL(out[2].toString(), "G");
out.clear();
rd.setEnzyme("mazF");
rd.setMissedCleavages(0);
rd.digest(NASequence::fromString("A[m6A]CA[m5C]AGGACGACAAAG"), out);
TEST_EQUAL(out.size(), 2);
TEST_STRING_EQUAL(out[0].toString(), "A[m6A]CA[m5C]AGGACGp");
TEST_STRING_EQUAL(out[1].toString(), "ACAAAG");
out.clear();
rd.setEnzyme("colicin_E5");
rd.setMissedCleavages(0);
rd.digest(NASequence::fromString("GGAUGUAAA"), out);
TEST_EQUAL(out.size(), 2);
TEST_STRING_EQUAL(out[0].toString(), "GGAUGp");
TEST_STRING_EQUAL(out[1].toString(), "UAAA");
out.clear();
rd.setEnzyme("no cleavage");
rd.setMissedCleavages(3);
rd.digest(NASequence::fromString("CCCAUCCG"), out);
TEST_EQUAL(out.size(), 1);
TEST_STRING_EQUAL(out[0].toString(), "CCCAUCCG");
rd.setEnzyme("RNase_4c");
rd.setMissedCleavages(0);
rd.digest(NASequence::fromString("UCCGUACGG"), out);
TEST_EQUAL(out.size(), 2);
TEST_STRING_EQUAL(out[0].toString(), "UCCGUc");
TEST_STRING_EQUAL(out[1].toString(), "ACGG");
rd.setEnzyme("unspecific cleavage");
rd.setMissedCleavages(0); // shouldn't matter for the result
rd.digest(NASequence::fromString("ACGU"), out);
TEST_EQUAL(out.size(), 10);
TEST_STRING_EQUAL(out[0].toString(), "Ap");
TEST_STRING_EQUAL(out[1].toString(), "ACp");
TEST_STRING_EQUAL(out[2].toString(), "ACGp");
TEST_STRING_EQUAL(out[3].toString(), "ACGU");
TEST_STRING_EQUAL(out[4].toString(), "Cp");
TEST_STRING_EQUAL(out[5].toString(), "CGp");
TEST_STRING_EQUAL(out[6].toString(), "CGU");
TEST_STRING_EQUAL(out[7].toString(), "Gp");
TEST_STRING_EQUAL(out[8].toString(), "GU");
TEST_STRING_EQUAL(out[9].toString(), "U");
}
END_SECTION
START_SECTION((void digest(IdentificationData& id_data, Size min_length = 0,
Size max_length = 0) const))
{
IdentificationData id_data;
IdentificationData::ParentSequence rna("test", IdentificationData::MoleculeType::RNA, "pAUGUCGCAG");
id_data.registerParentSequence(rna);
RNaseDigestion rd;
rd.setEnzyme("RNase_T1"); // cuts after G and leaves a 3'-phosphate
rd.digest(id_data);
TEST_EQUAL(id_data.getIdentifiedOligos().size(), 3);
/// multiple occurrences of the same oligo:
IdentificationData id_data2;
rna.sequence = "ACUGACUGG";
id_data2.registerParentSequence(rna);
rd.digest(id_data2, 2);
TEST_EQUAL(id_data2.getIdentifiedOligos().size(), 1);
ABORT_IF(id_data2.getIdentifiedOligos().empty());
IdentificationData::IdentifiedOligoRef ref = id_data2.getIdentifiedOligos().begin();
TEST_EQUAL(ref->parent_matches.size(), 1);
ABORT_IF(ref->parent_matches.empty());
// oligo sequence matches in two locations:
const set<IdentificationData::ParentMatch>& matches =
ref->parent_matches.begin()->second;
TEST_EQUAL(matches.size(), 2);
ABORT_IF(matches.size() < 2);
auto match_it = matches.begin();
TEST_EQUAL(match_it->start_pos, 0);
++match_it;
TEST_EQUAL(match_it->start_pos, 4);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IMSAlphabet_test.cpp | .cpp | 9,092 | 330 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Stephan Aiche $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabet.h>
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabetTextParser.h>
///////////////////////////
using namespace OpenMS;
using namespace ims;
using namespace std;
class IMSAlphabetParserImpl
: public IMSAlphabetParser<>
{
private:
ContainerType elements_;
public:
ContainerType& getElements() override
{
return elements_;
}
void parse(std::istream& ) override
{
// ignore istream, just enter something into the map
elements_.insert(std::make_pair("hydrogen", 1.0));
elements_.insert(std::make_pair("oxygen", 16.0));
}
};
START_TEST(IMSAlphabet, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IMSElement hydrogen("hydrogen", 1.0);
IMSElement oxygen("oxygen", 16.0);
IMSElement nitrogen("nitrogen", 14.0);
vector<IMSElement> elements;
elements.push_back(hydrogen);
elements.push_back(oxygen);
elements.push_back(nitrogen);
double carbon_mass = 12.0;
IMSElement carbon("carbon", carbon_mass);
IMSAlphabet* ptr = nullptr;
IMSAlphabet* null_ptr = nullptr;
START_SECTION(IMSAlphabet())
{
ptr = new IMSAlphabet();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IMSAlphabet())
{
delete ptr;
}
END_SECTION
START_SECTION((IMSAlphabet(const container &elements)))
{
ptr = new IMSAlphabet(elements);
TEST_NOT_EQUAL(ptr, null_ptr)
TEST_EQUAL(ptr->size(), 3)
TEST_EQUAL(ptr->getName(0), "hydrogen")
delete ptr;
}
END_SECTION
// test instance for the following tests
IMSAlphabet alphabet(elements);
START_SECTION((IMSAlphabet(const IMSAlphabet &alphabet)))
{
IMSAlphabet alphabet_copy(alphabet);
TEST_EQUAL(alphabet_copy.size(), 3)
TEST_EQUAL(alphabet_copy.getName(0), "hydrogen")
}
END_SECTION
START_SECTION((const element_type& getElement(const name_type &name) const ))
{
TEST_EQUAL(alphabet.getElement("hydrogen"), hydrogen)
TEST_EQUAL(alphabet.getElement("oxygen"), oxygen)
TEST_EQUAL(alphabet.getElement("nitrogen"), nitrogen)
}
END_SECTION
START_SECTION((const element_type& getElement(size_type index) const ))
{
TEST_EQUAL(alphabet.getElement(0), hydrogen)
TEST_EQUAL(alphabet.getElement(1), oxygen)
TEST_EQUAL(alphabet.getElement(2), nitrogen)
TEST_EXCEPTION(Exception::InvalidValue, alphabet.getElement("nitrogen2"))
}
END_SECTION
START_SECTION((void setElement(const name_type &name, mass_type mass, bool forced=false)))
{
IMSAlphabet alphabet_copy(alphabet);
alphabet_copy.setElement("hydrogen", 2.0, false);
TEST_EQUAL(alphabet_copy.size(), 3)
TEST_EQUAL(alphabet_copy.getMass("hydrogen"), 2.0)
// this should not change the alphabet, since there is no
// element named carbon
alphabet_copy.setElement("carbon", carbon_mass, false);
TEST_EQUAL(alphabet_copy.size(), 3)
alphabet_copy.setElement("carbon", carbon_mass, true);
TEST_EQUAL(alphabet_copy.size(), 4)
TEST_EQUAL(alphabet_copy.getMass("carbon"), 12)
}
END_SECTION
START_SECTION((const name_type& getName(size_type index) const ))
{
TEST_STRING_EQUAL(alphabet.getName(0),"hydrogen")
TEST_STRING_EQUAL(alphabet.getName(1),"oxygen")
TEST_STRING_EQUAL(alphabet.getName(2),"nitrogen")
}
END_SECTION
START_SECTION((mass_type getMass(const name_type &name) const ))
{
TEST_EQUAL(alphabet.getMass("hydrogen"), hydrogen.getMass())
TEST_EQUAL(alphabet.getMass("oxygen"), oxygen.getMass())
TEST_EQUAL(alphabet.getMass("nitrogen"), nitrogen.getMass())
TEST_EXCEPTION(Exception::InvalidValue, alphabet.getMass("nitrogen2"))
}
END_SECTION
START_SECTION((mass_type getMass(size_type index) const ))
{
TEST_EQUAL(alphabet.getMass(0), hydrogen.getMass())
TEST_EQUAL(alphabet.getMass(1), oxygen.getMass())
TEST_EQUAL(alphabet.getMass(2), nitrogen.getMass())
}
END_SECTION
START_SECTION((masses_type getMasses(size_type isotope_index=0) const ))
{
IMSAlphabet::masses_type masses = alphabet.getMasses();
TEST_EQUAL(masses.size(), 3)
ABORT_IF(masses.size() != 3)
TEST_EQUAL(masses[0], hydrogen.getMass())
TEST_EQUAL(masses[1], oxygen.getMass())
TEST_EQUAL(masses[2], nitrogen.getMass())
}
END_SECTION
START_SECTION((masses_type getAverageMasses() const ))
{
IMSAlphabet::masses_type average_masses = alphabet.getAverageMasses();
TEST_EQUAL(average_masses.size(), 3)
ABORT_IF(average_masses.size() != 3)
TEST_EQUAL(average_masses[0], hydrogen.getAverageMass())
TEST_EQUAL(average_masses[1], oxygen.getAverageMass())
TEST_EQUAL(average_masses[2], nitrogen.getAverageMass())
}
END_SECTION
START_SECTION((bool hasName(const name_type &name) const ))
{
TEST_EQUAL(alphabet.hasName("nitrogen"), true)
TEST_EQUAL(alphabet.hasName("oxygen"), true)
TEST_EQUAL(alphabet.hasName("oxygen2"), false)
}
END_SECTION
START_SECTION((void push_back(const name_type &name, mass_type value)))
{
IMSAlphabet alphabet_copy(alphabet);
alphabet_copy.push_back("carbon", carbon_mass);
TEST_EQUAL(alphabet_copy.size(), 4)
ABORT_IF(alphabet_copy.size() != 4)
TEST_EQUAL(alphabet_copy.getElement(3).getName(), "carbon")
TEST_EQUAL(alphabet_copy.hasName("carbon"),true)
TEST_EQUAL(alphabet_copy.getMass(3), carbon_mass)
}
END_SECTION
START_SECTION((void push_back(const element_type &element)))
{
IMSAlphabet alphabet_copy(alphabet);
alphabet_copy.push_back(carbon);
TEST_EQUAL(alphabet_copy.size(), 4)
ABORT_IF(alphabet_copy.size() != 4)
TEST_EQUAL(alphabet_copy.getElement(3).getName(), "carbon")
TEST_EQUAL(alphabet_copy.hasName("carbon"),true)
TEST_EQUAL(alphabet_copy.getMass(3), carbon.getMass())
}
END_SECTION
START_SECTION((void clear()))
{
IMSAlphabet alphabet_copy(alphabet);
alphabet_copy.clear();
TEST_EQUAL(alphabet_copy.size(), 0)
TEST_EQUAL(alphabet_copy.hasName("oxygen"), false)
}
END_SECTION
START_SECTION((virtual void sortByNames()))
{
IMSAlphabet alphabet_copy(alphabet);
alphabet_copy.sortByNames();
TEST_EQUAL(alphabet_copy.size(), 3)
TEST_EQUAL(alphabet_copy.getElement(0), hydrogen)
TEST_EQUAL(alphabet_copy.getElement(1), nitrogen)
TEST_EQUAL(alphabet_copy.getElement(2), oxygen)
}
END_SECTION
START_SECTION((virtual void sortByValues()))
{
IMSAlphabet alphabet_copy(alphabet);
alphabet_copy.push_back(carbon);
alphabet_copy.sortByValues();
TEST_EQUAL(alphabet_copy.size(), 4)
TEST_EQUAL(alphabet_copy.getElement(0), hydrogen)
TEST_EQUAL(alphabet_copy.getElement(1), carbon)
TEST_EQUAL(alphabet_copy.getElement(2), nitrogen)
TEST_EQUAL(alphabet_copy.getElement(3), oxygen)
}
END_SECTION
START_SECTION((virtual void load(const std::string &fname)))
{
NOT_TESTABLE // will be tested in virtual void load(const std::string &fname, IMSAlphabetParser<> *parser)
}
END_SECTION
START_SECTION((virtual void load(const std::string &fname, IMSAlphabetParser<> *parser)))
{
IMSAlphabet load_copy(alphabet);
TEST_EQUAL(load_copy.size(), 3)
TEST_EXCEPTION(Exception::IOException, load_copy.load(""))
// this should not clear the alphabet
TEST_EQUAL(load_copy.size(), 3)
// create file with minimal content
String filename;
NEW_TMP_FILE(filename)
// just create the file
ofstream of;
of.open(filename.c_str());
of << "# a comment which should be ignored" << std::endl;
of << "hydrogen\t1.0" << std::endl;
of << "oxygen\t16.0" << std::endl;
of << "nitrogen\t14.0" << std::endl;
of.close();
IMSAlphabetTextParser parser;
load_copy.load(filename, parser);
TEST_EQUAL(load_copy.size(), 3)
TEST_EQUAL(load_copy.hasName("hydrogen"), true)
TEST_REAL_SIMILAR(load_copy.getMass("hydrogen"), 1.0)
TEST_EQUAL(load_copy.hasName("nitrogen"), true)
TEST_REAL_SIMILAR(load_copy.getMass("nitrogen"), 14.0)
TEST_EQUAL(load_copy.hasName("oxygen"), true)
TEST_REAL_SIMILAR(load_copy.getMass("oxygen"), 16.0)
}
END_SECTION
START_SECTION((size_type size() const ))
{
TEST_EQUAL(alphabet.size(),3)
IMSAlphabet alphabet_copy(alphabet);
TEST_EQUAL(alphabet_copy.size(),3)
alphabet_copy.push_back(carbon);
TEST_EQUAL(alphabet_copy.size(), 4)
}
END_SECTION
START_SECTION((bool erase(const name_type &name)))
{
IMSAlphabet alphabet_copy(alphabet);
TEST_EQUAL(alphabet_copy.size(),3)
TEST_EQUAL(alphabet_copy.erase("hydrogen"), true)
TEST_EQUAL(alphabet_copy.size(),2)
TEST_EQUAL(alphabet_copy.erase("hydrogen"), false)
TEST_EQUAL(alphabet_copy.erase("oxygen"), true)
TEST_EQUAL(alphabet_copy.size(),1)
TEST_EQUAL(alphabet_copy.erase("nitrogen"), true)
TEST_EQUAL(alphabet_copy.size(),0)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/StatsHelpers_test.cpp | .cpp | 1,961 | 56 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Witold Wolski $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include "OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h"
using namespace std;
using namespace OpenMS;
using namespace OpenSwath;
START_TEST(DiaPrescore2, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION ( testscorefunction)
{
static const double arr1[] = {
10, 20, 50, 100, 50, 20, 10, // peak at 600
3, 7, 15, 30, 15, 7, 3, // peak at 601
1, 3, 9, 15, 9, 3, 1, // peak at 602
3, 9, 3 // peak at 603
};
std::vector<double> intensity (arr1, arr1 + sizeof(arr1) / sizeof(double) );
static const double arr2[] = {
599.97, 599.98, 599.99, 600.0, 600.01, 600.02, 600.03,
600.97, 600.98, 600.99, 601.0, 601.01, 601.02, 601.03,
601.97, 601.98, 601.99, 602.0, 602.01, 602.02, 602.03,
602.99, 603.0, 603.01
};
std::vector<double> mz (arr2, arr2 + sizeof(arr2) / sizeof(double) );
double norm = OpenSwath::norm(mz.cbegin(),mz.cend());
std::vector<double> normalized;
OpenSwath::normalize(mz,norm,normalized);
TEST_REAL_SIMILAR(OpenSwath::norm(normalized.cbegin(),normalized.cend()), 1.);
double x = dotProd(normalized.cbegin(),normalized.cend(),normalized.cbegin());
TEST_REAL_SIMILAR(x, 1.);
double man = manhattanDist(normalized.cbegin(),normalized.cend(),normalized.cbegin());
TEST_REAL_SIMILAR(man, 0.);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SwathWindowLoader_test.cpp | .cpp | 7,529 | 181 | // 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/SwathWindowLoader.h>
///////////////////////////
#include <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h>
using namespace OpenMS;
START_TEST(SwathWindowLoader, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
SwathWindowLoader* ptr = nullptr;
SwathWindowLoader* nullPointer = nullptr;
START_SECTION(SwathWindowLoader())
ptr = new SwathWindowLoader;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(virtual ~SwathWindowLoader())
delete ptr;
END_SECTION
START_SECTION( static void readSwathWindows(const std::string& filename, std::vector<double>& swath_prec_lower, std::vector<double>& swath_prec_upper) )
{
std::vector<double> swath_prec_lower;
std::vector<double> swath_prec_upper;
SwathWindowLoader::readSwathWindows(OPENMS_GET_TEST_DATA_PATH("SwathWindowFile.txt"), swath_prec_lower, swath_prec_upper);
TEST_EQUAL(swath_prec_lower.size(), swath_prec_upper.size())
TEST_REAL_SIMILAR(swath_prec_lower[0], 400)
TEST_REAL_SIMILAR(swath_prec_lower[1], 425)
TEST_REAL_SIMILAR(swath_prec_lower[2], 450)
TEST_REAL_SIMILAR(swath_prec_lower[3], 475)
TEST_REAL_SIMILAR(swath_prec_upper[0], 425)
TEST_REAL_SIMILAR(swath_prec_upper[1], 450)
TEST_REAL_SIMILAR(swath_prec_upper[2], 475)
TEST_REAL_SIMILAR(swath_prec_upper[3], 500)
// test without header
std::vector<double> swath_prec_lower_no_head;
std::vector<double> swath_prec_upper_no_head;
SwathWindowLoader::readSwathWindows(OPENMS_GET_TEST_DATA_PATH("SwathWindowFileNoHeader.txt"), swath_prec_lower_no_head, swath_prec_upper_no_head);
TEST_EQUAL(swath_prec_lower_no_head.size(), swath_prec_upper.size())
TEST_REAL_SIMILAR(swath_prec_lower_no_head[0], 400)
TEST_REAL_SIMILAR(swath_prec_lower_no_head[1], 425)
TEST_REAL_SIMILAR(swath_prec_lower_no_head[2], 450)
TEST_REAL_SIMILAR(swath_prec_lower_no_head[3], 475)
TEST_REAL_SIMILAR(swath_prec_upper_no_head[0], 425)
TEST_REAL_SIMILAR(swath_prec_upper_no_head[1], 450)
TEST_REAL_SIMILAR(swath_prec_upper_no_head[2], 475)
TEST_REAL_SIMILAR(swath_prec_upper_no_head[3], 500)
}
END_SECTION
START_SECTION ( static void annotateSwathMapsFromFile(const std::string& filename, std::vector<OpenSwath::SwathMap>& swath_maps, bool do_sort, bool force) )
{
// pretend this is given in the raw data:
const std::vector< OpenSwath::SwathMap > swath_maps = {
{399, 426, 1, false},
{424, 451, 2, false},
{450, 475, 3, false}, // matches exacly (no overlap), but will be ok
{474, 501, 4, false}
};
// copy to feed into function
std::vector< OpenSwath::SwathMap > swath_maps_test = swath_maps;
SwathWindowLoader::annotateSwathMapsFromFile(OPENMS_GET_TEST_DATA_PATH("SwathWindowFile.txt"), swath_maps_test, false, false);
TEST_REAL_SIMILAR(swath_maps_test[0].lower, 400)
TEST_REAL_SIMILAR(swath_maps_test[1].lower, 425)
TEST_REAL_SIMILAR(swath_maps_test[2].lower, 450)
TEST_REAL_SIMILAR(swath_maps_test[3].lower, 475)
TEST_REAL_SIMILAR(swath_maps_test[0].upper, 425)
TEST_REAL_SIMILAR(swath_maps_test[1].upper, 450)
TEST_REAL_SIMILAR(swath_maps_test[2].upper, 475)
TEST_REAL_SIMILAR(swath_maps_test[3].upper, 500)
///////////////
// test sorting (start inverted)
std::vector< OpenSwath::SwathMap > swath_maps_inv = swath_maps;
// invert
std::sort(swath_maps_inv.rbegin(), swath_maps_inv.rend(), [](const OpenSwath::SwathMap& a, const OpenSwath::SwathMap& b) { return a.lower < b.lower; });
swath_maps_test = swath_maps_inv;
// test before
TEST_EQUAL(swath_maps_test[0].lower, 474)
TEST_EQUAL(swath_maps_test[0].center, 4)
TEST_EQUAL(swath_maps_test[3].lower, 399)
TEST_EQUAL(swath_maps_test[3].center, 1)
SwathWindowLoader::annotateSwathMapsFromFile(OPENMS_GET_TEST_DATA_PATH("SwathWindowFile.txt"),
swath_maps_test, true, false);
TEST_REAL_SIMILAR(swath_maps_test[0].lower, 400)
TEST_REAL_SIMILAR(swath_maps_test[1].lower, 425)
TEST_REAL_SIMILAR(swath_maps_test[2].lower, 450)
TEST_REAL_SIMILAR(swath_maps_test[3].lower, 475)
TEST_REAL_SIMILAR(swath_maps_test[0].upper, 425)
TEST_REAL_SIMILAR(swath_maps_test[1].upper, 450)
TEST_REAL_SIMILAR(swath_maps_test[2].upper, 475)
TEST_REAL_SIMILAR(swath_maps_test[3].upper, 500)
// should now be in original order
TEST_REAL_SIMILAR(swath_maps_test[0].center, 1)
TEST_REAL_SIMILAR(swath_maps_test[1].center, 2)
TEST_REAL_SIMILAR(swath_maps_test[2].center, 3)
TEST_REAL_SIMILAR(swath_maps_test[3].center, 4)
///////////////////////////////////
// Test exceptions
std::vector< OpenSwath::SwathMap > swath_maps_too_large(5);
TEST_EXCEPTION(OpenMS::Exception::IllegalArgument,
SwathWindowLoader::annotateSwathMapsFromFile(
OPENMS_GET_TEST_DATA_PATH("SwathWindowFile.txt"), swath_maps_too_large, true, false));
std::vector< OpenSwath::SwathMap > swath_maps_too_small(3);
TEST_EXCEPTION(OpenMS::Exception::IllegalArgument,
SwathWindowLoader::annotateSwathMapsFromFile(
OPENMS_GET_TEST_DATA_PATH("SwathWindowFile.txt"), swath_maps_too_small, true, false));
// wrong order && no sorting --> fail
swath_maps_test = swath_maps_inv;
// test before
TEST_EQUAL(swath_maps_test[0].lower, 474)
TEST_EQUAL(swath_maps_test[0].center, 4)
TEST_EQUAL(swath_maps_test[3].lower, 399)
TEST_EQUAL(swath_maps_test[3].center, 1)
TEST_EXCEPTION(OpenMS::Exception::IllegalArgument,
SwathWindowLoader::annotateSwathMapsFromFile(OPENMS_GET_TEST_DATA_PATH("SwathWindowFile.txt"),
swath_maps_test, false, false));
// wrong order && no sorting && force --> ok
swath_maps_test = swath_maps_inv;
SwathWindowLoader::annotateSwathMapsFromFile(OPENMS_GET_TEST_DATA_PATH("SwathWindowFile.txt"),
swath_maps_test, false, true);
// overwritten windows (not narrowing the range since in wrong order )... but ok, due to -force
TEST_REAL_SIMILAR(swath_maps_test[0].lower, 400)
TEST_REAL_SIMILAR(swath_maps_test[1].lower, 425)
TEST_REAL_SIMILAR(swath_maps_test[2].lower, 450)
TEST_REAL_SIMILAR(swath_maps_test[3].lower, 475)
TEST_REAL_SIMILAR(swath_maps_test[0].upper, 425)
TEST_REAL_SIMILAR(swath_maps_test[1].upper, 450)
TEST_REAL_SIMILAR(swath_maps_test[2].upper, 475)
TEST_REAL_SIMILAR(swath_maps_test[3].upper, 500)
// should still be in reverse order
TEST_REAL_SIMILAR(swath_maps_test[0].center, 4)
TEST_REAL_SIMILAR(swath_maps_test[1].center, 3)
TEST_REAL_SIMILAR(swath_maps_test[2].center, 2)
TEST_REAL_SIMILAR(swath_maps_test[3].center, 1)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/RangeManager_test.cpp | .cpp | 16,923 | 593 | // 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/Peak2D.h>
#include <OpenMS/KERNEL/RangeManager.h>
///////////////////////////
#include <sstream>
using namespace OpenMS;
using namespace std;
// test with additional Mobility (should always be empty)
using RangeMType = RangeManagerContainer<RangeRT, RangeMZ, RangeIntensity, RangeMobility>;
using RangeMTypeInt = RangeManager<RangeIntensity>;
using RangeMTypeMzInt = RangeManager<RangeMZ, RangeIntensity>;
using RangeMTypeRT = RangeManager<RangeRT>;
class RM : public RangeMType
{
public:
// avoid compiler warning, but in production code virtual should not be done on a RM to save
// space and time
virtual ~RM() = default;
bool operator == (const RM& rhs) const
{
return RangeMType::operator==(rhs);
}
bool operator != (const RM& rhs) const
{
return !(operator==(rhs));
}
void updateRanges() override
{
std::vector<Peak2D > vec;
Peak2D tmp;
tmp.getPosition()[0] = 2.0;
tmp.getPosition()[1] = 500.0;
tmp.setIntensity(1.0f);
vec.push_back(tmp);
tmp.getPosition()[0] = 100.0;
tmp.getPosition()[1] = 1300.0;
tmp.setIntensity(47110.0);
vec.push_back(tmp);
tmp.getPosition()[0] = 2.0;
tmp.getPosition()[1] = 500.0;
tmp.setIntensity(1.0f);
vec.push_back(tmp);
clearRanges();
for (const auto& peak : vec)
{
extendRT(peak.getRT());
extendMZ(peak.getMZ());
extendIntensity(peak.getIntensity());
}
}
virtual void updateRanges2()
{
std::vector<Peak2D > vec;
Peak2D tmp;
tmp.getPosition()[0] = 2.0;
tmp.getPosition()[1] = 500.0;
tmp.setIntensity(1.0f);
vec.push_back(tmp);
clearRanges();
for (const auto& peak : vec)
{
extendRT(peak.getRT());
extendMZ(peak.getMZ());
extendIntensity(peak.getIntensity());
}
}
}; // class RM
START_TEST(RangeManager, "RangeManager")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
// tests for RangeBase
START_SECTION(RangeBase())
RangeBase b;
TEST_EQUAL(b.isEmpty(), true)
END_SECTION
START_SECTION(RangeBase(const double min, const double max))
RangeBase b(4, 6);
TEST_EQUAL(b.isEmpty(), false)
TEST_EQUAL(b.getMin(), 4)
TEST_EQUAL(b.getMax(), 6)
TEST_EXCEPTION(Exception::InvalidRange, RangeBase(6, 3))
END_SECTION
START_SECTION(const RangeBase& rhs)
RangeBase b_(4, 6);
auto b(b_);
TEST_EQUAL(b.isEmpty(), false)
TEST_EQUAL(b.getMin(), 4)
TEST_EQUAL(b.getMax(), 6)
END_SECTION
START_SECTION(RangeBase& operator=(const RangeBase& rhs))
RangeBase b_(4, 6);
RangeBase b;
b = b_;
TEST_EQUAL(b.isEmpty(), false)
TEST_EQUAL(b.getMin(), 4)
TEST_EQUAL(b.getMax(), 6)
END_SECTION
START_SECTION(void clear())
RangeBase b(4, 6);
TEST_EQUAL(b.isEmpty(), false)
b.clear();
TEST_EQUAL(b.isEmpty(), true)
END_SECTION
START_SECTION(bool isEmpty() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(bool contains(const double value) const)
RangeBase b(4, 6);
TEST_EQUAL(b.contains(5), true)
TEST_EQUAL(b.contains(3), false)
TEST_EQUAL(b.contains(7), false)
RangeBase empty;
TEST_EQUAL(empty.contains(5), false)
END_SECTION
START_SECTION(bool contains(const RangeBase& inner_range) const)
RangeBase b(2, 6), inner1(2,4), inner2(3,4), inner3(4,6), over1(1,4), over2(3,7), outer(1,7);
TEST_EQUAL(b.contains(inner1), true)
TEST_EQUAL(b.contains(inner2), true)
TEST_EQUAL(b.contains(inner3), true)
TEST_EQUAL(b.contains(over1), false)
TEST_EQUAL(b.contains(over2), false)
TEST_EQUAL(b.contains(outer), false)
TEST_EQUAL(outer.contains(b), true)
END_SECTION
START_SECTION(void setMin(const double min))
RangeBase b(4, 6);
b.setMin(5);
TEST_EQUAL(b.getMin(), 5)
b.setMin(7);// also increases max
TEST_EQUAL(b.getMin(), 7)
TEST_EQUAL(b.getMax(), 7);
END_SECTION
START_SECTION(void setMax(const double max))
RangeBase b(4, 6);
b.setMax(5);
TEST_EQUAL(b.getMax(), 5)
b.setMax(2);// also decreases min
TEST_EQUAL(b.getMin(), 2)
TEST_EQUAL(b.getMax(), 2);
END_SECTION
START_SECTION(double getMin() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(double getMax() const)
NOT_TESTABLE // tested above
END_SECTION
START_SECTION(void extend(const RangeBase& other))
RangeBase b(4, 6);
RangeBase other(1, 8);
b.extend(other);
TEST_EQUAL(b.getMin(), 1)
TEST_EQUAL(b.getMax(), 8)
END_SECTION
/// extend the range such that it includes the given @p value
START_SECTION(void extend(const double value))
RangeBase b(4, 6);
b.extend(1);
TEST_EQUAL(b.getMin(), 1)
TEST_EQUAL(b.getMax(), 6)
RangeBase b2(4, 6);
b2.extend(8);
TEST_EQUAL(b2.getMin(), 4)
TEST_EQUAL(b2.getMax(), 8)
RangeBase b3(4, 6);
b3.extend(5);
TEST_EQUAL(b3.getMin(), 4)
TEST_EQUAL(b3.getMax(), 6)
END_SECTION
START_SECTION(void extendLeftRight(const double by))
RangeBase b(4, 6);
b.extendLeftRight(1);
TEST_EQUAL(b.getMin(), 3)
TEST_EQUAL(b.getMax(), 7)
RangeBase b2(2, 8);
b2.extendLeftRight(-2);
TEST_EQUAL(b2.getMin(), 4)
TEST_EQUAL(b2.getMax(), 6)
b2.extendLeftRight(-19);
TEST_TRUE(b2.isEmpty())
RangeBase empty;
empty.extendLeftRight(100);
TEST_TRUE(empty.isEmpty())
END_SECTION
START_SECTION(void clampTo(const RangeBase& other))
RangeBase b(-4, 6);
b.clampTo({-2, 7});
TEST_EQUAL(b.getMin(), -2)
TEST_EQUAL(b.getMax(), 6)
RangeBase b2(4, 6);
b2.clampTo({1, 5});
TEST_EQUAL(b2.getMin(), 4)
TEST_EQUAL(b2.getMax(), 5)
b2.clampTo({4.5, 4.5});
TEST_EQUAL(b2.getMin(), 4.5)
TEST_EQUAL(b2.getMax(), 4.5)
RangeBase b3(4, 6);
b3.clampTo({10, 11});
TEST_TRUE(b3.isEmpty())
RangeBase b4(4, 6);
TEST_EXCEPTION(Exception::InvalidRange, b4.clampTo(RangeBase()))
END_SECTION
START_SECTION(void pushInto(const RangeBase& sandbox))
RangeBase b(-4, 6);
b.pushInto({-2, 7}); // moves and clips
TEST_EQUAL(b.getMin(), -2)
TEST_EQUAL(b.getMax(), 7)
RangeBase b2(4, 6);
b2.pushInto({1, 15}); // does nothing
TEST_EQUAL(b2.getMin(), 4)
TEST_EQUAL(b2.getMax(), 6)
b2.pushInto({4.5, 4.5}); // hard clip inside old range
TEST_EQUAL(b2.getMin(), 4.5)
TEST_EQUAL(b2.getMax(), 4.5)
RangeBase b3(4, 6); // move left, no clip
b3.pushInto({-10, 5});
TEST_EQUAL(b3.getMin(), 3)
TEST_EQUAL(b3.getMax(), 5)
b3.pushInto({4, 10}); // move right, no clip
TEST_EQUAL(b3.getMin(), 4)
TEST_EQUAL(b3.getMax(), 6)
RangeBase b4(4, 6); // hard clip outside old range
b4.pushInto({-10, -10});
TEST_EQUAL(b4.getMin(), -10)
TEST_EQUAL(b4.getMax(), -10)
RangeBase b5(4, 6);
TEST_EXCEPTION(Exception::InvalidRange, b5.pushInto(RangeBase()))
END_SECTION
START_SECTION(void scaleBy(const double factor))
RangeBase b(4, 6);
b.scaleBy(10); // diff is 2, so extend distance to 20, by increase of 9 on each side
TEST_EQUAL(b.getMin(), 4-9)
TEST_EQUAL(b.getMax(), 6+9)
// scaling empty ranges does nothing
RangeBase empty1, empty2;
empty1.scaleBy(10);
TEST_EQUAL(empty1, empty2)
END_SECTION
START_SECTION(void shift(const double distance))
RangeBase b(4, 6);
b.shift(10);
TEST_EQUAL(b.getMin(), 14)
TEST_EQUAL(b.getMax(), 16)
// shifting empty ranges does nothing
RangeBase empty1, empty2;
empty1.shift(10);
TEST_EQUAL(empty1, empty2)
END_SECTION
START_SECTION(double center() const)
RangeBase b(4, 6);
TEST_EQUAL(b.center(), 5)
RangeBase empty;
TEST_TRUE(std::isnan(empty.center()));
END_SECTION
START_SECTION(double getSpan() const)
RangeBase b(4, 6);
TEST_EQUAL(b.getSpan(), 2)
RangeBase empty;
TEST_TRUE(std::isnan(empty.getSpan()));
END_SECTION
START_SECTION(bool operator==(const RangeBase& rhs) const)
RangeBase b(4, 6), b2(4, 6), empty1, empty2;
TEST_NOT_EQUAL(b, empty1)
TEST_EQUAL(b, b2)
TEST_EQUAL(empty1, empty2)
END_SECTION
RM* ptr;
RM* nullPointer = nullptr;
START_SECTION((RangeMType()))
ptr = new RM();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~RangeMType()))
delete ptr;
END_SECTION
START_SECTION((RangeManager(const RangeManager& rhs)))
RM rm0;
rm0.updateRanges();
RM rm(rm0);
TEST_REAL_SIMILAR(rm.getMinRT(), 2.0)
TEST_REAL_SIMILAR(rm.getMinMZ(), 500.0)
TEST_REAL_SIMILAR(rm.getMaxRT(), 100.0)
TEST_REAL_SIMILAR(rm.getMaxMZ(), 1300.0)
TEST_REAL_SIMILAR(rm.getMinIntensity(), 1.0)
TEST_REAL_SIMILAR(rm.getMaxIntensity(), 47110.0)
END_SECTION
START_SECTION((RangeManager& operator=(const RangeManager& rhs)))
RM rm0;
rm0.updateRanges();
RM rm;
rm = rm0;
TEST_REAL_SIMILAR(rm.getMinRT(), 2.0)
TEST_REAL_SIMILAR(rm.getMinMZ(), 500.0)
TEST_REAL_SIMILAR(rm.getMaxRT(), 100.0)
TEST_REAL_SIMILAR(rm.getMaxMZ(), 1300.0)
TEST_REAL_SIMILAR(rm.getMinIntensity(), 1.0)
TEST_REAL_SIMILAR(rm.getMaxIntensity(), 47110.0)
END_SECTION
START_SECTION((bool operator==(const RangeManager& rhs) const))
RM rm0 , rm;
TEST_TRUE(rm == rm0);
rm0.updateRanges();
TEST_EQUAL(rm==rm0, false);
END_SECTION
START_SECTION((bool operator!=(const RangeManager& rhs) const))
RM rm0 , rm;
TEST_EQUAL(rm!=rm0, false);
rm0.updateRanges();
TEST_FALSE(rm == rm0);
END_SECTION
START_SECTION((virtual void updateRanges()=0))
RM rm;
rm.updateRanges();
rm.updateRanges(); //second time to check the initialization
TEST_REAL_SIMILAR(rm.getMinRT(), 2.0)
TEST_REAL_SIMILAR(rm.getMinMZ(), 500.0)
TEST_EQUAL(rm.RangeRT::isEmpty(), false)
TEST_REAL_SIMILAR(rm.getMaxRT(), 100.0)
TEST_REAL_SIMILAR(rm.getMaxMZ(), 1300.0)
TEST_EQUAL(rm.RangeMZ::isEmpty(), false)
TEST_REAL_SIMILAR(rm.getMinIntensity(), 1.0)
TEST_REAL_SIMILAR(rm.getMaxIntensity(), 47110.0)
TEST_EQUAL(rm.RangeIntensity::isEmpty(), false)
TEST_TRUE(rm.RangeMobility::isEmpty())
//test with only one point
rm.updateRanges2(); //second time to check the initialization
TEST_REAL_SIMILAR(rm.getMinRT(), 2.0)
TEST_REAL_SIMILAR(rm.getMinMZ(), 500.0)
TEST_REAL_SIMILAR(rm.getMaxRT(), 2.0)
TEST_REAL_SIMILAR(rm.getMaxMZ(), 500.0)
TEST_REAL_SIMILAR(rm.getMinIntensity(), 1.0)
TEST_REAL_SIMILAR(rm.getMaxIntensity(), 1.0)
END_SECTION
START_SECTION(HasRangeType hasRange() const)
RM rm;
TEST_EQUAL(rm.hasRange() == HasRangeType::NONE, true);
rm.updateRanges();
TEST_EQUAL(rm.hasRange() == HasRangeType::SOME, true);
rm.extendMobility(56.4);
TEST_EQUAL(rm.hasRange() == HasRangeType::ALL, true);
END_SECTION
START_SECTION(template<typename... RangeBasesOther>
bool containsAll(const RangeManager<RangeBasesOther...>& rhs) const)
RM rm;
rm.updateRanges();
RM outer = rm;
TEST_EQUAL(rm.containsAll(outer), true);
TEST_EQUAL(outer.containsAll(rm), true);
outer.scaleBy(1.1);
TEST_EQUAL(rm.containsAll(outer), false);
TEST_EQUAL(outer.containsAll(rm), true);
outer.scaleBy(0.5);
TEST_EQUAL(rm.containsAll(outer), true);
TEST_EQUAL(outer.containsAll(rm), false);
outer = rm;
// empty dimensions in the rhs are considered contained
outer.extendMobility(56.4); // rm.mobility is empty
TEST_EQUAL(rm.containsAll(outer), false);
TEST_EQUAL(outer.containsAll(rm), true);
// empty dimensions do not count
outer.RangeMZ::scaleBy(0.5); // mz range is smaller
rm.RangeMZ::clear(); // but now does not count anymore
TEST_EQUAL(rm.containsAll(outer), false); // due to mobility from above
TEST_EQUAL(outer.containsAll(rm), true);
// no ranges overlap...
RangeManager<RangeRT, RangeMZ> rmz;
RangeManager<RangeIntensity, RangeMobility> im;
TEST_EXCEPTION(Exception::InvalidRange, rmz.containsAll(im))
END_SECTION
START_SECTION(template<typename... RangeBasesOther>
void extend(const RangeManager<RangeBasesOther...>& rhs))
RM rm;
rm.updateRanges();
RangeMTypeMzInt mid;
mid.assign(rm); // assigns only overlapping dimensions
TEST_REAL_SIMILAR(mid.getMinMZ(), 500.0)
TEST_REAL_SIMILAR(mid.getMaxMZ(), 1300.0)
TEST_REAL_SIMILAR(mid.getMinIntensity(), 1.0)
TEST_REAL_SIMILAR(mid.getMaxIntensity(), 47110.0)
RangeMTypeInt small;
small.extendIntensity(123456.7);
mid.extend(small);
TEST_REAL_SIMILAR(mid.getMinMZ(), 500.0)
TEST_REAL_SIMILAR(mid.getMaxMZ(), 1300.0)
TEST_REAL_SIMILAR(mid.getMinIntensity(), 1.0)
TEST_REAL_SIMILAR(mid.getMaxIntensity(), 123456.7)
END_SECTION
START_SECTION(void scaleBy(const double factor))
RM rm;
rm.updateRanges();
rm.scaleBy(2);
TEST_REAL_SIMILAR(rm.getMinRT(), 2.0-49)
TEST_REAL_SIMILAR(rm.getMaxRT(), 100.0+49)
TEST_REAL_SIMILAR(rm.getMinMZ(), 500.0-400)
TEST_REAL_SIMILAR(rm.getMaxMZ(), 1300.0+400)
TEST_REAL_SIMILAR(rm.getMinIntensity(), 1.0 - (47109.0/2))
TEST_REAL_SIMILAR(rm.getMaxIntensity(), 47110.0 + (47109.0/2))
TEST_TRUE(rm.RangeMobility::isEmpty())
// scaling a dimension where min == max does nothing
RangeManager<RangeRT, RangeMZ> rtmz;
rtmz.extendMZ(100);
rtmz.extendRT(50);
auto copy = rtmz;
rtmz.scaleBy(2.0);
TEST_EQUAL(rtmz, copy)
// scaling empty dimensions does nothing
RM rm_empty, rm_empty2;
rm_empty.scaleBy(4);
TEST_EQUAL(rm_empty, rm_empty2)
END_SECTION
START_SECTION(template<typename... RangeBasesOther> void pushInto(const RangeManager<RangeBasesOther...>& sandbox))
RM rm;
rm.updateRanges();
RangeMTypeMzInt rmi;
rmi.extendMZ(700); // shift
rmi.extendMZ(2000);
rmi.extendIntensity(500); // shift and clamp
rmi.extendIntensity(600);
rm.pushInto(rmi);
TEST_REAL_SIMILAR(rm.getMinRT(), 2.0)
TEST_REAL_SIMILAR(rm.getMaxRT(), 100.0)
TEST_REAL_SIMILAR(rm.getMinMZ(), 500.0 + 200)
TEST_REAL_SIMILAR(rm.getMaxMZ(), 1300.0 + 200)
TEST_REAL_SIMILAR(rm.getMinIntensity(), 1.0 + 499)
TEST_REAL_SIMILAR(rm.getMaxIntensity(), 600) // was 47110.0
TEST_TRUE(rm.RangeMobility::isEmpty())
// if no dimensions overlap...
RangeMTypeRT rt;
TEST_EXCEPTION(Exception::InvalidRange, rmi.pushInto(rt))
END_SECTION
START_SECTION(template<typename... RangeBasesOther> void clampTo(const RangeManager<RangeBasesOther...>& rhs))
RM rm;
rm.updateRanges();
RangeMTypeMzInt rmi;
rmi.extendMZ(700); // clamp left
rmi.extendMZ(2000);
rmi.extendIntensity(-10); // clamp to empty
rmi.extendIntensity(-9);
rm.clampTo(rmi);
TEST_REAL_SIMILAR(rm.getMinRT(), 2.0) // should be untouched (since rmi.RT is empty)
TEST_REAL_SIMILAR(rm.getMaxRT(), 100.0)
TEST_REAL_SIMILAR(rm.getMinMZ(), 500.0 + 200)
TEST_REAL_SIMILAR(rm.getMaxMZ(), 1300.0 + 0)
TEST_TRUE(rm.getRangeForDim(MSDim::INT).isEmpty())
TEST_TRUE(rm.RangeMobility::isEmpty())
// if no dimensions overlap...
RangeMTypeRT rt;
TEST_EXCEPTION(Exception::InvalidRange, rmi.clampTo(rt))
END_SECTION
START_SECTION(RangeBase& getRangeForDim(MSDim dim))
RM rm;
rm.updateRanges();
auto rt = rm.getRangeForDim(MSDim::RT);
auto mz = rm.getRangeForDim(MSDim::MZ);
auto in = rm.getRangeForDim(MSDim::INT);
auto im = rm.getRangeForDim(MSDim::IM);
TEST_REAL_SIMILAR(rt.getMin(), 2.0)
TEST_REAL_SIMILAR(mz.getMin(), 500.0)
TEST_REAL_SIMILAR(rt.getMax(), 100.0)
TEST_REAL_SIMILAR(mz.getMax(), 1300.0)
TEST_REAL_SIMILAR(in.getMin(), 1.0)
TEST_REAL_SIMILAR(in.getMax(), 47110.0)
TEST_FALSE(rt.isEmpty())
TEST_TRUE(im.isEmpty())
END_SECTION
START_SECTION((void clearRanges()))
RM rm;
rm.updateRanges();
TEST_REAL_SIMILAR(rm.getMinRT(), 2.0)
TEST_REAL_SIMILAR(rm.getMinMZ(), 500.0)
TEST_REAL_SIMILAR(rm.getMaxRT(), 100.0)
TEST_REAL_SIMILAR(rm.getMaxMZ(), 1300.0)
TEST_REAL_SIMILAR(rm.getMinIntensity(), 1.0)
TEST_REAL_SIMILAR(rm.getMaxIntensity(), 47110.0)
TEST_EQUAL(rm.RangeRT::isEmpty(), false)
TEST_EQUAL(rm.RangeMZ::isEmpty(), false)
TEST_EQUAL(rm.RangeIntensity::isEmpty(), false)
TEST_EQUAL(rm.RangeMobility::isEmpty(), true)
rm.clearRanges();
TEST_TRUE(rm.RangeRT::isEmpty())
TEST_TRUE(rm.RangeMZ::isEmpty())
TEST_TRUE(rm.RangeIntensity::isEmpty())
TEST_TRUE(rm.RangeMobility::isEmpty())
END_SECTION
START_SECTION(void printRange(std::ostream& out) const)
RM rm;
rm.extendRT(1.0);
rm.extendMZ(2.0);
rm.extendIntensity(3.0);
rm.extendMobility(4.0);
stringstream ss;
rm.printRange(ss);
TEST_EQUAL(ss.str(), "rt: [1, 1]\n"
"mz: [2, 2]\n"
"intensity: [3, 3]\n"
"mobility: [4, 4]\n");
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MRMIonSeries_test.cpp | .cpp | 11,968 | 280 | // 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/MRMIonSeries.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MRMIonSeries, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MRMIonSeries * ptr = nullptr;
MRMIonSeries* nullPointer = nullptr;
START_SECTION(MRMIonSeries())
{
ptr = new MRMIonSeries();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~MRMIonSeries())
{
delete ptr;
}
END_SECTION
START_SECTION((boost::unordered_map<String, double> MRMIonSeries::getIonSeries(AASequence sequence, size_t precursor_charge, std::vector<String> fragment_types, std::vector<size_t> fragment_charges, bool enable_specific_losses, bool enable_unspecific_losses)))
{
MRMIonSeries mrmis;
std::vector<String> fragment_types;
fragment_types.push_back(String("b"));
fragment_types.push_back(String("y"));
std::vector<size_t> fragment_charges;
fragment_charges.push_back(3);
fragment_charges.push_back(2);
fragment_charges.push_back(1);
// Standard peptide
MRMIonSeries::IonSeries ionseries1 = mrmis.getIonSeries(AASequence::fromString(String("PEPTIDEK")), 3, fragment_types, fragment_charges, false, false);
TEST_EQUAL(ionseries1.size(), 42)
TEST_REAL_SIMILAR(ionseries1["b2^1"], 227.10263491)
TEST_REAL_SIMILAR(ionseries1["b2^2"], 114.05495569)
TEST_REAL_SIMILAR(ionseries1["b2^3"], 76.37239595)
TEST_REAL_SIMILAR(ionseries1["b5^1"], 538.28714271)
TEST_REAL_SIMILAR(ionseries1["b5^2"], 269.64720959)
TEST_REAL_SIMILAR(ionseries1["b5^3"], 180.10056521)
TEST_REAL_SIMILAR(ionseries1["b7^1"], 782.35668109)
TEST_REAL_SIMILAR(ionseries1["b7^2"], 391.68197878)
TEST_REAL_SIMILAR(ionseries1["b7^3"], 261.45707801)
TEST_REAL_SIMILAR(ionseries1["y1^1"], 147.11280491)
TEST_REAL_SIMILAR(ionseries1["y1^2"], 74.06004069)
TEST_REAL_SIMILAR(ionseries1["y1^3"], 49.70911928)
TEST_REAL_SIMILAR(ionseries1["y5^1"], 605.31408687)
TEST_REAL_SIMILAR(ionseries1["y5^2"], 303.16068167)
TEST_REAL_SIMILAR(ionseries1["y5^3"], 202.44287993)
TEST_REAL_SIMILAR(ionseries1["y7^1"], 831.40944532)
TEST_REAL_SIMILAR(ionseries1["y7^2"], 416.20836089)
TEST_REAL_SIMILAR(ionseries1["y7^3"], 277.80799942)
// Enable neutral losses
MRMIonSeries::IonSeries ionseries2 = mrmis.getIonSeries(AASequence::fromString(String("PEPTIDEK")), 3, fragment_types, fragment_charges, true, true);
TEST_EQUAL(ionseries2.size(), 99)
TEST_REAL_SIMILAR(ionseries2["b5^2"], 269.64720959)
TEST_REAL_SIMILAR(ionseries2["b5-H2O1^2"], 260.64192709)
TEST_REAL_SIMILAR(ionseries2["b5-C1H4O1S1^2"], 0) // no oxidized methionine in peptide
TEST_REAL_SIMILAR(ionseries2["b5-H1O3P1^2"], 0) // no phosphorylation in peptide
TEST_REAL_SIMILAR(ionseries2["b5-H3O4P1^2"], 0) // no phosphorylation in peptide
TEST_REAL_SIMILAR(ionseries2["b5-C1O2^2"], 0)
MRMIonSeries::IonSeries ionseries3 = mrmis.getIonSeries(AASequence::fromString(String("ES(Phospho)")), 3, fragment_types, fragment_charges, true, true);
TEST_EQUAL(ionseries3.size(), 12)
TEST_REAL_SIMILAR(ionseries3["y1^1"], 186.0162)
TEST_REAL_SIMILAR(ionseries3["y1-H3O4P1^2"], 44.5233)
TEST_REAL_SIMILAR(ionseries3["y1^2"], 93.5117)
TEST_REAL_SIMILAR(ionseries3["y1^3"], 62.6769)
TEST_REAL_SIMILAR(ionseries3["b1-H2O1^1"], 112.0393)
TEST_REAL_SIMILAR(ionseries3["b1-H2O1^2"], 56.5233)
TEST_REAL_SIMILAR(ionseries3["y1-H3O4P1^1"], 88.0393)
TEST_REAL_SIMILAR(ionseries3["y1-H3O4P1^3"], 30.018)
TEST_REAL_SIMILAR(ionseries3["b1^2"], 65.5285)
TEST_REAL_SIMILAR(ionseries3["b1-H2O1^3"], 38.018)
TEST_REAL_SIMILAR(ionseries3["b1^1"], 130.0498)
TEST_REAL_SIMILAR(ionseries3["b1^3"], 44.0214)
MRMIonSeries::IonSeries ionseries4 = mrmis.getIonSeries(AASequence::fromString(String("ES")), 3, fragment_types, fragment_charges, true, true);
TEST_REAL_SIMILAR(ionseries4["y1-H2O1^1"], 88.0393)
TEST_REAL_SIMILAR(ionseries4["y1^1"], 106.0499)
TEST_REAL_SIMILAR(ionseries4["y1-H2O1^2"], 44.5233)
TEST_REAL_SIMILAR(ionseries4["y1^2"], 53.5286)
TEST_REAL_SIMILAR(ionseries4["y1-H2O1^3"], 30.0180)
TEST_REAL_SIMILAR(ionseries4["y1^3"], 36.0215)
TEST_REAL_SIMILAR(ionseries4["b1-H2O1^1"], 112.0393)
TEST_REAL_SIMILAR(ionseries4["b1-H2O1^2"], 56.5233)
TEST_REAL_SIMILAR(ionseries4["b1^2"], 65.5286)
TEST_REAL_SIMILAR(ionseries4["b1-H2O1^3"], 38.0180)
TEST_REAL_SIMILAR(ionseries4["b1^1"], 130.0499)
TEST_REAL_SIMILAR(ionseries4["b1^3"], 44.0215)
MRMIonSeries::IonSeries ionseries5 = mrmis.getIonSeries(AASequence::fromString(String("ES(Phospho)")), 3, fragment_types, fragment_charges, true, false);
TEST_EQUAL(ionseries5.size(), 9)
TEST_REAL_SIMILAR(ionseries5["y1^1"], 186.0162)
TEST_REAL_SIMILAR(ionseries5["y1-H3O4P1^2"], 44.5233)
TEST_REAL_SIMILAR(ionseries5["y1^2"], 93.5117)
TEST_REAL_SIMILAR(ionseries5["y1^3"], 62.6769)
TEST_REAL_SIMILAR(ionseries5["y1-H3O4P1^1"], 88.0393)
TEST_REAL_SIMILAR(ionseries5["y1-H3O4P1^3"], 30.018)
TEST_REAL_SIMILAR(ionseries5["b1^2"], 65.5285)
TEST_REAL_SIMILAR(ionseries5["b1^1"], 130.0498)
TEST_REAL_SIMILAR(ionseries5["b1^3"], 44.0214)
MRMIonSeries::IonSeries ionseries6 = mrmis.getIonSeries(AASequence::fromString(String("ES(Phospho)")), 3, fragment_types, fragment_charges, false, true);
TEST_EQUAL(ionseries6.size(), 9)
TEST_REAL_SIMILAR(ionseries6["y1^1"], 186.0162)
TEST_REAL_SIMILAR(ionseries6["y1^2"], 93.5117)
TEST_REAL_SIMILAR(ionseries6["y1^3"], 62.6769)
TEST_REAL_SIMILAR(ionseries6["b1-H2O1^1"], 112.0393)
TEST_REAL_SIMILAR(ionseries6["b1-H2O1^2"], 56.5233)
TEST_REAL_SIMILAR(ionseries6["b1^2"], 65.5285)
TEST_REAL_SIMILAR(ionseries6["b1-H2O1^3"], 38.018)
TEST_REAL_SIMILAR(ionseries6["b1^1"], 130.0498)
TEST_REAL_SIMILAR(ionseries6["b1^3"], 44.0214)
}
END_SECTION
START_SECTION((std::pair<String, double> MRMIonSeries::annotateIon(IonSeries ionseries, double ProductMZ, double mz_threshold)))
{
MRMIonSeries mrmis;
std::vector<String> fragment_types;
fragment_types.push_back(String("b"));
fragment_types.push_back(String("y"));
std::vector<size_t> fragment_charges;
fragment_charges.push_back(3);
fragment_charges.push_back(2);
fragment_charges.push_back(1);
// Standard peptide
MRMIonSeries::IonSeries ionseries1 = mrmis.getIonSeries(AASequence::fromString(String("PEPTIDEK")), 3, fragment_types, fragment_charges, false, false);
std::pair<String, double> ion1 = mrmis.annotateIon(ionseries1, 202.44287993, 0.05);
TEST_EQUAL(ion1.first, "y5^3")
TEST_REAL_SIMILAR(ion1.second, 202.44287993)
std::pair<String, double> ion2 = mrmis.annotateIon(ionseries1, 202.44287993, 0);
TEST_EQUAL(ion2.first, "unannotated")
TEST_REAL_SIMILAR(ion2.second, -1)
std::pair<String, double> ion3 = mrmis.annotateIon(ionseries1, 202.4, 0.05);
TEST_EQUAL(ion3.first, "y5^3")
TEST_REAL_SIMILAR(ion3.second, 202.44287993)
}
END_SECTION
START_SECTION((std::pair<String, double> MRMIonSeries::getIon(IonSeries ionseries, String ionid)))
{
MRMIonSeries mrmis;
std::vector<String> fragment_types;
fragment_types.push_back(String("b"));
fragment_types.push_back(String("y"));
std::vector<size_t> fragment_charges;
fragment_charges.push_back(3);
fragment_charges.push_back(2);
fragment_charges.push_back(1);
// Standard peptide
MRMIonSeries::IonSeries ionseries1 = mrmis.getIonSeries(AASequence::fromString(String("PEPTIDEK")), 3, fragment_types, fragment_charges, false, false);
std::pair<String, double> ion1 = mrmis.getIon(ionseries1, "y5^3");
TEST_EQUAL(ion1.first, "y5^3")
TEST_REAL_SIMILAR(ion1.second, 202.44287993)
}
END_SECTION
START_SECTION((void MRMIonSeries::annotateTransitionCV(ReactionMonitoringTransition & tr, String annotation)))
{
MRMIonSeries mrmis;
ReactionMonitoringTransition tr, tr2, tr3;
mrmis.annotateTransitionCV(tr, "y5^3");
mrmis.annotateTransitionCV(tr2, "y5-H2O1^3");
mrmis.annotateTransitionCV(tr3, "y5-18^3");
TEST_EQUAL(tr.getProduct().getChargeState(), 3)
TEST_EQUAL(tr.getProduct().getInterpretationList()[0].iontype, TargetedExperiment::IonType::YIon);
TEST_EQUAL(tr.getProduct().getInterpretationList()[0].ordinal, 5);
TEST_EQUAL(tr.getProduct().getInterpretationList()[0].hasCVTerm("MS:1001524"), false) // no neutral loss
TEST_EQUAL(tr2.getProduct().getChargeState(), 3)
TEST_EQUAL(tr2.getProduct().getInterpretationList()[0].iontype, TargetedExperiment::IonType::YIon);
TEST_EQUAL(tr2.getProduct().getInterpretationList()[0].ordinal, 5)
TEST_EQUAL(tr2.getProduct().getInterpretationList()[0].hasCVTerm("MS:1001524"), true)
TEST_REAL_SIMILAR(tr2.getProduct().getInterpretationList()[0].getCVTerms().at("MS:1001524")[0].getValue(), -18.0105650638)
TEST_EQUAL(tr3.getProduct().getChargeState(), 3)
TEST_EQUAL(tr3.getProduct().getInterpretationList()[0].iontype, TargetedExperiment::IonType::YIon);
TEST_EQUAL(tr3.getProduct().getInterpretationList()[0].ordinal, 5);
TEST_EQUAL(tr3.getProduct().getInterpretationList()[0].hasCVTerm("MS:1001524"), true)
TEST_REAL_SIMILAR(tr3.getProduct().getInterpretationList()[0].getCVTerms().at("MS:1001524")[0].getValue(), -18)
}
END_SECTION
START_SECTION((void MRMIonSeries::annotateTransition(ReactionMonitoringTransition & tr, const TargetedExperiment::Peptide peptide, const double precursor_mz_threshold, const double product_mz_threshold, bool enable_reannotation, std::vector<String> fragment_types, std::vector<size_t> fragment_charges, bool enable_specific_losses, bool enable_unspecific_losses)))
{
MRMIonSeries mrmis;
ReactionMonitoringTransition tr, tr2, tr3;
TargetedExperiment::Peptide peptide;
peptide.sequence = "PEPTIDEK";
peptide.setChargeState(3);
std::vector<String> fragment_types;
fragment_types.push_back(String("b"));
fragment_types.push_back(String("y"));
std::vector<size_t> fragment_charges;
fragment_charges.push_back(3);
fragment_charges.push_back(2);
fragment_charges.push_back(1);
tr.setProductMZ(202.44);
mrmis.annotateTransition(tr, peptide, 0.05, 0.05, true, fragment_types, fragment_charges, false, false);
TEST_REAL_SIMILAR(tr.getProductMZ(), 202.442879934638)
TEST_EQUAL(tr.getProduct().getChargeState(), 3)
TEST_EQUAL(tr.getProduct().getInterpretationList()[0].iontype, TargetedExperiment::IonType::YIon);
TEST_EQUAL(tr.getProduct().getInterpretationList()[0].ordinal, 5)
TEST_EQUAL(tr.getProduct().getInterpretationList()[0].hasCVTerm("MS:1001524"), false) // no neutral loss
tr2.setProductMZ(196.44287993);
mrmis.annotateTransition(tr2, peptide, 0.05, 0.05, true, fragment_types, fragment_charges, true, true);
TEST_EQUAL(tr2.getProduct().getChargeState(), 3)
TEST_EQUAL(tr2.getProduct().getInterpretationList()[0].iontype, TargetedExperiment::IonType::YIon);
TEST_EQUAL(tr2.getProduct().getInterpretationList()[0].ordinal, 5)
TEST_EQUAL(tr2.getProduct().getInterpretationList()[0].hasCVTerm("MS:1001524"), true)
TEST_EQUAL((int)tr2.getProduct().getInterpretationList()[0].getCVTerms().at("MS:1001524")[0].getValue().toString().toDouble(), -18)
tr3.setProductMZ(202.44);
mrmis.annotateTransition(tr3, peptide, 0.05, 0.05, false, fragment_types, fragment_charges, false, false);
TEST_REAL_SIMILAR(tr3.getProductMZ(), 202.44)
TEST_EQUAL(tr3.getProduct().hasCharge(), false)
TEST_EQUAL(tr3.getProduct().getInterpretationList()[0].iontype, TargetedExperiment::IonType::NonIdentified);
TEST_EQUAL(tr3.getProduct().getInterpretationList()[0].hasCVTerm("MS:1001524"), false)
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/FLASHDeconvAlgorithm_test.cpp | .cpp | 15,586 | 447 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Tom David Müller, Jaekwan Kim$
// $Authors: Tom David Müller, Jaekwan Kim$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/TOPDOWN/FLASHDeconvAlgorithm.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
///////////////////////////
START_TEST(FLASHDeconvAlgorithm, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
FLASHDeconvAlgorithm* ptr = nullptr;
FLASHDeconvAlgorithm* null_ptr = nullptr;
START_SECTION(FLASHDeconvAlgorithm())
ptr = new FLASHDeconvAlgorithm();
TEST_NOT_EQUAL(ptr, null_ptr)
END_SECTION
START_SECTION(FLASHDeconvAlgorithm(const FLASHDeconvAlgorithm& source))
FLASHDeconvAlgorithm copy(*ptr);
TEST_EQUAL(copy.getParameters(), ptr->getParameters())
END_SECTION
START_SECTION(FLASHDeconvAlgorithm& operator=(const FLASHDeconvAlgorithm& source))
FLASHDeconvAlgorithm copy;
copy = *ptr;
TEST_EQUAL(copy.getParameters(), ptr->getParameters())
END_SECTION
START_SECTION(~FLASHDeconvAlgorithm())
delete ptr;
END_SECTION
ptr = new FLASHDeconvAlgorithm();
START_SECTION(FLASHDeconvAlgorithm(FLASHDeconvAlgorithm&& source))
FLASHDeconvAlgorithm temp;
temp.setParameters(ptr->getParameters());
FLASHDeconvAlgorithm moved(std::move(temp));
TEST_EQUAL(moved.getParameters(), ptr->getParameters());
END_SECTION
START_SECTION(FLASHDeconvAlgorithm& operator=(FLASHDeconvAlgorithm&& source))
FLASHDeconvAlgorithm temp;
temp.setParameters(ptr->getParameters());
FLASHDeconvAlgorithm moved;
moved = std::move(temp);
TEST_EQUAL(moved.getParameters(), ptr->getParameters());
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
ptr = new FLASHDeconvAlgorithm();
Param params;
START_SECTION(std::vector<double> getTolerances())
params.setValue("SD:tol", ListUtils::create<double>("10.0,5.0"));
ptr->setParameters(params);
auto tolerances = ptr->getTolerances();
TEST_EQUAL(tolerances.size(), 2)
TEST_REAL_SIMILAR(tolerances[0], 10.0);
TEST_REAL_SIMILAR(tolerances[1], 5.0);
END_SECTION
// load test data
// TODO: minimize
PeakMap input;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("FLASHDeconv_1_input.mzML"), input);
// Store FD outputs
std::vector<DeconvolvedSpectrum> deconvolved_spectra;
std::vector<FLASHHelperClasses::MassFeature> deconvolved_features;
START_SECTION(void run())
ptr->run(input, deconvolved_spectra, deconvolved_features);
TEST_EQUAL(deconvolved_spectra.size(), input.size());
TEST_FALSE(deconvolved_features.empty());
END_SECTION
START_SECTION(int getScanNumber())
// The scan number depends on the test file; just verify it returns a positive value
TEST_EQUAL(FLASHDeconvAlgorithm::getScanNumber(input, 0) > 0, true);
END_SECTION
// Check if the precalculated averagine was initialized during runtime
START_SECTION(FLASHHelperClasses::PrecalculatedAveragine getAveragine())
TEST_NOT_EQUAL(ptr->getAveragine().getMaxIsotopeIndex(), 0);
TEST_FALSE(ptr->getAveragine().get(500.0).getContainer().empty());
END_SECTION
START_SECTION(FLASHHelperClasses::PrecalculatedAveragine getDecoyAveragine())
TEST_NOT_EQUAL(ptr->getDecoyAveragine().getMaxIsotopeIndex(), 0);
TEST_FALSE(ptr->getDecoyAveragine().get(500.0).getContainer().empty());
END_SECTION
// Decoy Averagine needs to be handled differently if FDR is reported
START_SECTION(FLASHHelperClasses::PrecalculatedAveragine getDecoyAveragine())
params.setValue("FD:report_FD", true);
ptr = new FLASHDeconvAlgorithm();
ptr->setParameters(params);
ptr->run(input, deconvolved_spectra, deconvolved_features);
TEST_NOT_EQUAL(ptr->getDecoyAveragine().getMaxIsotopeIndex(), 0);
TEST_FALSE(ptr->getDecoyAveragine().get(500.0).getContainer().empty());
END_SECTION
/////////////////////////////////////////////////////////////
// Phase 1: Averagine Model Tests (Enhanced)
/////////////////////////////////////////////////////////////
START_SECTION(Averagine model - protein vs RNA mode initialization)
// Test protein averagine (default)
FLASHDeconvAlgorithm algo_protein;
Param protein_params;
protein_params.setValue("use_RNA_averagine", "false");
algo_protein.setParameters(protein_params);
algo_protein.run(input, deconvolved_spectra, deconvolved_features);
auto& protein_avg = algo_protein.getAveragine();
TEST_NOT_EQUAL(protein_avg.getMaxIsotopeIndex(), 0)
TEST_FALSE(protein_avg.get(1000.0).getContainer().empty())
// Test RNA averagine
FLASHDeconvAlgorithm algo_rna;
Param rna_params;
rna_params.setValue("use_RNA_averagine", "true");
algo_rna.setParameters(rna_params);
algo_rna.run(input, deconvolved_spectra, deconvolved_features);
auto& rna_avg = algo_rna.getAveragine();
TEST_NOT_EQUAL(rna_avg.getMaxIsotopeIndex(), 0)
TEST_FALSE(rna_avg.get(1000.0).getContainer().empty())
END_SECTION
START_SECTION(Averagine model - mass range validation)
FLASHDeconvAlgorithm algo;
algo.run(input, deconvolved_spectra, deconvolved_features);
auto& avg = algo.getAveragine();
// Test averagine at various mass ranges
TEST_FALSE(avg.get(500.0).getContainer().empty())
TEST_FALSE(avg.get(1000.0).getContainer().empty())
TEST_FALSE(avg.get(5000.0).getContainer().empty())
TEST_FALSE(avg.get(10000.0).getContainer().empty())
END_SECTION
START_SECTION(Averagine model - consistency check)
FLASHDeconvAlgorithm algo;
algo.run(input, deconvolved_spectra, deconvolved_features);
auto& avg = algo.getAveragine();
// Verify max isotope index is reasonable
int max_iso_idx = avg.getMaxIsotopeIndex();
TEST_NOT_EQUAL(max_iso_idx, 0)
TEST_EQUAL(max_iso_idx > 0, true)
TEST_EQUAL(max_iso_idx < 1000, true) // Reasonable upper bound
END_SECTION
/////////////////////////////////////////////////////////////
// Phase 1: MS Level Processing Tests
/////////////////////////////////////////////////////////////
START_SECTION(MS level processing - scan number retrieval)
// Test getScanNumber with different indices - verify it returns positive values
TEST_EQUAL(FLASHDeconvAlgorithm::getScanNumber(input, 0) > 0, true)
// Test with valid index range
if (input.size() > 1)
{
int scan_num = FLASHDeconvAlgorithm::getScanNumber(input, 1);
TEST_NOT_EQUAL(scan_num, 0) // Should have a valid scan number
}
END_SECTION
/////////////////////////////////////////////////////////////
// Phase 1: Spectrum Merging Tests
/////////////////////////////////////////////////////////////
START_SECTION(Spectrum merging - merging method parameter validation)
FLASHDeconvAlgorithm algo;
Param merge_params;
// Test merging_method = 0 (no merging)
merge_params.setValue("FD:merging_method", 0);
algo.setParameters(merge_params);
TEST_EQUAL(algo.getParameters().exists("FD:merging_method"), true)
// Test merging_method = 1 (Gaussian)
merge_params.setValue("FD:merging_method", 1);
algo.setParameters(merge_params);
TEST_EQUAL(algo.getParameters().exists("FD:merging_method"), true)
// Test merging_method = 2 (block)
merge_params.setValue("FD:merging_method", 2);
algo.setParameters(merge_params);
TEST_EQUAL(algo.getParameters().exists("FD:merging_method"), true)
END_SECTION
START_SECTION(Spectrum merging - effect on output with no merging)
FLASHDeconvAlgorithm algo_no_merge;
Param no_merge_params;
no_merge_params.setValue("FD:merging_method", 0);
algo_no_merge.setParameters(no_merge_params);
std::vector<DeconvolvedSpectrum> no_merge_spectra;
std::vector<FLASHHelperClasses::MassFeature> no_merge_features;
algo_no_merge.run(input, no_merge_spectra, no_merge_features);
// With no merging, output spectrum count should equal input
TEST_EQUAL(no_merge_spectra.size(), input.size())
END_SECTION
START_SECTION(Spectrum merging - Gaussian merging mode)
FLASHDeconvAlgorithm algo_gaussian;
Param gaussian_params;
gaussian_params.setValue("FD:merging_method", 1);
algo_gaussian.setParameters(gaussian_params);
std::vector<DeconvolvedSpectrum> gaussian_spectra;
std::vector<FLASHHelperClasses::MassFeature> gaussian_features;
algo_gaussian.run(input, gaussian_spectra, gaussian_features);
// With Gaussian merging, we should have some output
// (exact count depends on merging parameters)
TEST_NOT_EQUAL(gaussian_spectra.size(), 0)
END_SECTION
/////////////////////////////////////////////////////////////
// Phase 1: FDR and Decoy Generation Tests
/////////////////////////////////////////////////////////////
START_SECTION(FDR - report_FDR parameter toggling)
// Test with FDR reporting disabled (default)
FLASHDeconvAlgorithm algo_no_fdr;
Param no_fdr_params;
no_fdr_params.setValue("FD:report_FD", "false");
algo_no_fdr.setParameters(no_fdr_params);
std::vector<DeconvolvedSpectrum> no_fdr_spectra;
std::vector<FLASHHelperClasses::MassFeature> no_fdr_features;
algo_no_fdr.run(input, no_fdr_spectra, no_fdr_features);
// Decoy averagine should still be initialized
auto& decoy_avg_no_fdr = algo_no_fdr.getDecoyAveragine();
TEST_NOT_EQUAL(decoy_avg_no_fdr.getMaxIsotopeIndex(), 0)
// Test with FDR reporting enabled
FLASHDeconvAlgorithm algo_with_fdr;
Param fdr_params;
fdr_params.setValue("FD:report_FD", "true");
algo_with_fdr.setParameters(fdr_params);
std::vector<DeconvolvedSpectrum> fdr_spectra;
std::vector<FLASHHelperClasses::MassFeature> fdr_features;
algo_with_fdr.run(input, fdr_spectra, fdr_features);
// Decoy averagine should be properly initialized for FDR
auto& decoy_avg_fdr = algo_with_fdr.getDecoyAveragine();
TEST_NOT_EQUAL(decoy_avg_fdr.getMaxIsotopeIndex(), 0)
TEST_FALSE(decoy_avg_fdr.get(500.0).getContainer().empty())
END_SECTION
START_SECTION(FDR - noise decoy weight validation)
FLASHDeconvAlgorithm algo;
Param fdr_params;
fdr_params.setValue("FD:report_FD", "true");
algo.setParameters(fdr_params);
algo.run(input, deconvolved_spectra, deconvolved_features);
// Get noise decoy weight
double noise_weight = algo.getNoiseDecoyWeight();
// Verify noise weight is reasonable (should be positive and bounded)
TEST_EQUAL(noise_weight > 0, true)
TEST_EQUAL(noise_weight <= 1.0, true) // Calculated weight should be at most 1.0
END_SECTION
START_SECTION(FDR - decoy averagine properties)
FLASHDeconvAlgorithm algo;
Param fdr_params;
fdr_params.setValue("FD:report_FD", "true");
algo.setParameters(fdr_params);
algo.run(input, deconvolved_spectra, deconvolved_features);
auto& decoy_avg = algo.getDecoyAveragine();
// Verify decoy averagine has similar properties to regular averagine
TEST_NOT_EQUAL(decoy_avg.getMaxIsotopeIndex(), 0)
// Test at different masses
TEST_FALSE(decoy_avg.get(500.0).getContainer().empty())
TEST_FALSE(decoy_avg.get(1000.0).getContainer().empty())
TEST_FALSE(decoy_avg.get(5000.0).getContainer().empty())
END_SECTION
START_SECTION(FDR - decoy generation consistency)
FLASHDeconvAlgorithm algo1;
FLASHDeconvAlgorithm algo2;
Param fdr_params;
fdr_params.setValue("FD:report_FD", "true");
algo1.setParameters(fdr_params);
algo2.setParameters(fdr_params);
std::vector<DeconvolvedSpectrum> spectra1, spectra2;
std::vector<FLASHHelperClasses::MassFeature> features1, features2;
algo1.run(input, spectra1, features1);
algo2.run(input, spectra2, features2);
// Both should generate decoy averagines with same max isotope index
TEST_EQUAL(algo1.getDecoyAveragine().getMaxIsotopeIndex(),
algo2.getDecoyAveragine().getMaxIsotopeIndex())
END_SECTION
/////////////////////////////////////////////////////////////
// Phase 1: Output Validation Tests
/////////////////////////////////////////////////////////////
START_SECTION(Output validation - deconvolved spectrum structure)
FLASHDeconvAlgorithm algo;
std::vector<DeconvolvedSpectrum> output_spectra;
std::vector<FLASHHelperClasses::MassFeature> output_features;
algo.run(input, output_spectra, output_features);
// Verify output has expected size
TEST_EQUAL(output_spectra.size(), input.size())
// Check that each deconvolved spectrum has valid properties
for (const auto& spec : output_spectra)
{
// Verify spectrum has been processed (has some metadata)
TEST_EQUAL(spec.getScanNumber() >= 0, true)
}
END_SECTION
START_SECTION(Output validation - mass features structure)
FLASHDeconvAlgorithm algo;
std::vector<DeconvolvedSpectrum> output_spectra;
std::vector<FLASHHelperClasses::MassFeature> output_features;
algo.run(input, output_spectra, output_features);
// Verify features were found (may be empty for some datasets)
// Just check that the vector is accessible
TEST_EQUAL(output_features.size() >= 0, true)
// If features exist, validate basic properties
for (const auto& feature : output_features)
{
// Verify feature has valid mass range
TEST_EQUAL(feature.avg_mass >= 0, true)
}
END_SECTION
START_SECTION(Output validation - PeakGroup properties in deconvolved spectra)
FLASHDeconvAlgorithm algo;
std::vector<DeconvolvedSpectrum> output_spectra;
std::vector<FLASHHelperClasses::MassFeature> output_features;
algo.run(input, output_spectra, output_features);
// Check deconvolved spectra for peak groups
bool found_peak_groups = false;
for (const auto& spec : output_spectra)
{
if (spec.size() > 0)
{
found_peak_groups = true;
// Verify peak groups have valid properties
for (Size i = 0; i < spec.size(); ++i)
{
const auto& pg = spec[i];
// Peak groups should have positive mass
TEST_EQUAL(pg.getMonoMass() >= 0, true)
}
}
}
// At least some spectra should have peak groups
TEST_EQUAL(found_peak_groups, true)
END_SECTION
START_SECTION(Output validation - consistent output vector sizes)
FLASHDeconvAlgorithm algo;
std::vector<DeconvolvedSpectrum> output_spectra;
std::vector<FLASHHelperClasses::MassFeature> output_features;
// Run twice to ensure consistency
algo.run(input, output_spectra, output_features);
size_t first_spectra_size = output_spectra.size();
output_spectra.clear();
output_features.clear();
algo.run(input, output_spectra, output_features);
size_t second_spectra_size = output_spectra.size();
// Should produce same number of spectra on repeated runs
TEST_EQUAL(first_spectra_size, second_spectra_size)
END_SECTION
START_SECTION(Output validation - output spectrum properties)
FLASHDeconvAlgorithm algo;
std::vector<DeconvolvedSpectrum> output_spectra;
std::vector<FLASHHelperClasses::MassFeature> output_features;
algo.run(input, output_spectra, output_features);
// Verify each output spectrum has consistent properties with input
for (size_t i = 0; i < output_spectra.size() && i < input.size(); ++i)
{
// Scan numbers should match
TEST_EQUAL(output_spectra[i].getScanNumber(),
FLASHDeconvAlgorithm::getScanNumber(input, i))
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/LogConfigHandler_test.cpp | .cpp | 10,924 | 283 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Stephan Aiche$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CONCEPT/LogConfigHandler.h>
///////////////////////////
#include <boost/regex.hpp>
using namespace OpenMS;
using namespace std;
START_TEST(LogConfigHandler, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION((virtual ~LogConfigHandler()))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((Param parse(const StringList &setting)))
{
StringList settings;
settings.push_back("DEBUG add cout");
settings.push_back("DEBUG add a.out");
settings.push_back("INFO add a.out");
settings.push_back("FATAL_ERROR add cerr");
Param p = LogConfigHandler::getInstance()->parse(settings);
// p should contain a list of the above set commands
std::vector<std::string> parsedConfigs = p.getValue(LogConfigHandler::PARAM_NAME);
TEST_EQUAL(parsedConfigs[0] , "DEBUG add cout FILE")
TEST_EQUAL(parsedConfigs[1] , "DEBUG add a.out FILE")
TEST_EQUAL(parsedConfigs[2] , "INFO add a.out FILE")
TEST_EQUAL(parsedConfigs[3] , "FATAL_ERROR add cerr FILE")
StringList settings2;
settings2.push_back("DEBUG");
TEST_EXCEPTION(Exception::ParseError, LogConfigHandler::getInstance()->parse(settings2));
}
END_SECTION
START_SECTION((void configure(const Param ¶m)))
{
// Note: LogConfigHandler configures the GLOBAL log streams, not thread-local streams.
// We must use global streams directly to test that configuration works correctly.
std::vector<std::string> settings = {"INFO add testing_info_warn_stream STRING",
"WARNING add testing_info_warn_stream STRING",
"ERROR add only_error_string_stream STRING",
"INFO remove cout FILE",
"WARNING remove cout",
"ERROR remove cerr FILE"};
Param p;
p.setValue(LogConfigHandler::PARAM_NAME, settings, "List of all settings that should be applied to the current Logging Configuration");
LogConfigHandler::getInstance()->configure(p);
// Use GLOBAL streams directly to test configuration (not OPENMS_LOG_* which use thread-local)
getGlobalLogInfo() << "1" << endl;
getGlobalLogInfo() << "2" << endl;
getGlobalLogWarn() << "3" << endl;
getGlobalLogError() << "4" << endl;
settings.clear();
settings.push_back("WARNING clear");
p.setValue(LogConfigHandler::PARAM_NAME, settings, "List of all settings that should be applied to the current Logging Configuration");
LogConfigHandler::getInstance()->configure(p);
// this should go into nowhere (warn stream was cleared)
getGlobalLogWarn() << "5" << endl;
ostringstream& info_warn_stream = static_cast<ostringstream&>(LogConfigHandler::getInstance()->getStream("testing_info_warn_stream"));
String info_warn_stream_content(info_warn_stream.str());
StringList info_warn_result;
info_warn_stream_content.trim().split('\n', info_warn_result, true );
TEST_EQUAL(info_warn_result.size() , 3)
// check output with regex
String pattern("\\[[0-9]+/[0-1][0-9]/[0-3][0-9], [0-2][0-9]:[0-5][0-9]:[0-5][0-9]\\] ");
boost::regex rx(pattern);
int i = 1;
for(StringList::iterator it = info_warn_result.begin() ; it != info_warn_result.end(); ++it)
{
rx.assign(pattern + i);
TEST_TRUE(regex_search(*it, rx)) // stream may be wrapped in ANSI color codes; only search infix
++i;
}
ostringstream& error_stream = static_cast<ostringstream&>(LogConfigHandler::getInstance()->getStream("only_error_string_stream"));
String error_stream_content(error_stream.str());
StringList error_result;
error_stream_content.trim().split('\n', error_result, true );
TEST_EQUAL(error_result.size(), 1)
String pattern2("\\[[0-9]+/[0-1][0-9]/[0-3][0-9], [0-2][0-9]:[0-5][0-9]:[0-5][0-9]\\] 4");
rx.assign(pattern2);
TEST_TRUE(regex_search(error_result[0], rx)) // stream may be wrapped in ANSI color codes; only search infix
}
END_SECTION
START_SECTION((ostream& getStream(const String &stream_name)))
{
// Use global streams directly to test LogConfigHandler configuration
std::vector<std::string> settings;
settings.push_back("INFO add testing_getStream STRING");
Param p;
p.setValue(LogConfigHandler::PARAM_NAME, settings, "List of all settings that should be applied to the current Logging Configuration");
LogConfigHandler::getInstance()->configure(p);
getGlobalLogInfo() << "getStream 1" << endl;
ostringstream& info_stream = static_cast<ostringstream&>(LogConfigHandler::getInstance()->getStream("testing_getStream"));
String info_content(info_stream.str());
StringList info_result;
info_content.trim().split('\n', info_result, true );
TEST_EQUAL(info_result.size() , 1)
// check if everything landed in the stream we wanted
String pattern("\\[[0-9]+/[0-1][0-9]/[0-3][0-9], [0-2][0-9]:[0-5][0-9]:[0-5][0-9]\\] getStream 1");
boost::regex rx(pattern);
TEST_EQUAL(regex_match(info_result[0], rx), true)
}
END_SECTION
LogConfigHandler* nullPointer = nullptr;
START_SECTION((static LogConfigHandler* getInstance()))
{
TEST_NOT_EQUAL(LogConfigHandler::getInstance(), nullPointer)
}
END_SECTION
START_SECTION((void setLogLevel(const String &log_level) - restoring streams))
{
// Test that setLogLevel can restore streams when lowering the log level
// Use global streams directly to test LogConfigHandler configuration
// Setup: Create a string stream for INFO level
std::vector<std::string> settings;
settings.push_back("INFO add test_setloglevel_stream STRING");
Param p;
p.setValue(LogConfigHandler::PARAM_NAME, settings, "List of all settings that should be applied to the current Logging Configuration");
LogConfigHandler::getInstance()->configure(p);
// Write a message at INFO level - should appear
getGlobalLogInfo() << "message1" << endl;
// Set log level to ERROR (should remove INFO streams)
LogConfigHandler::getInstance()->setLogLevel("ERROR");
// Write a message at INFO level - should NOT appear
getGlobalLogInfo() << "message2" << endl;
// Lower log level back to INFO (should restore INFO streams)
LogConfigHandler::getInstance()->setLogLevel("INFO");
// Write a message at INFO level - should appear again
getGlobalLogInfo() << "message3" << endl;
// Check the stream content
ostringstream& test_stream = static_cast<ostringstream&>(LogConfigHandler::getInstance()->getStream("test_setloglevel_stream"));
String content(test_stream.str());
StringList result;
content.trim().split('\n', result, true);
// Should have message1 and message3, but not message2
TEST_EQUAL(result.size(), 2)
TEST_TRUE(result[0].hasSubstring("message1"))
TEST_TRUE(result[1].hasSubstring("message3"))
}
END_SECTION
START_SECTION((removeAllStreams flushes buffers))
{
// Test that removeAllStreams flushes buffers before clearing
// Use global streams directly to test LogConfigHandler configuration
// Setup: Create a string stream for WARNING level
std::vector<std::string> settings;
settings.push_back("WARNING add test_flush_stream STRING");
Param p;
p.setValue(LogConfigHandler::PARAM_NAME, settings, "List of all settings that should be applied to the current Logging Configuration");
LogConfigHandler::getInstance()->configure(p);
// Write without endl (no flush yet)
getGlobalLogWarn() << "unflushed_message";
// Set log level to ERROR (which calls removeAllStreams on WARNING)
// This should flush the buffer before removing streams
LogConfigHandler::getInstance()->setLogLevel("ERROR");
// Check the stream content - the unflushed message should be there
ostringstream& test_stream = static_cast<ostringstream&>(LogConfigHandler::getInstance()->getStream("test_flush_stream"));
String content(test_stream.str());
// The message should be in the stream even though it wasn't flushed with endl
TEST_TRUE(content.hasSubstring("unflushed_message"))
}
END_SECTION
START_SECTION((void setLogLevel(const String &log_level) - NONE level))
{
// Test that setLogLevel("NONE") disables all logging and can be restored
// Use global streams directly to test LogConfigHandler configuration
// Setup: Create string streams for multiple levels
std::vector<std::string> settings;
settings.push_back("INFO add test_none_info_stream STRING");
settings.push_back("ERROR add test_none_error_stream STRING");
Param p;
p.setValue(LogConfigHandler::PARAM_NAME, settings, "List of all settings that should be applied to the current Logging Configuration");
LogConfigHandler::getInstance()->configure(p);
// Write messages - should appear
getGlobalLogInfo() << "before_none_info" << endl;
getGlobalLogError() << "before_none_error" << endl;
// Set log level to NONE (should remove all streams)
LogConfigHandler::getInstance()->setLogLevel("NONE");
// Write messages - should NOT appear
getGlobalLogInfo() << "during_none_info" << endl;
getGlobalLogError() << "during_none_error" << endl;
// Restore log level to INFO (should restore INFO and higher streams)
LogConfigHandler::getInstance()->setLogLevel("INFO");
// Write messages - should appear again
getGlobalLogInfo() << "after_none_info" << endl;
getGlobalLogError() << "after_none_error" << endl;
// Check INFO stream
ostringstream& info_stream = static_cast<ostringstream&>(LogConfigHandler::getInstance()->getStream("test_none_info_stream"));
String info_content(info_stream.str());
TEST_TRUE(info_content.hasSubstring("before_none_info"))
TEST_FALSE(info_content.hasSubstring("during_none_info"))
TEST_TRUE(info_content.hasSubstring("after_none_info"))
// Check ERROR stream
ostringstream& error_stream = static_cast<ostringstream&>(LogConfigHandler::getInstance()->getStream("test_none_error_stream"));
String error_content(error_stream.str());
TEST_TRUE(error_content.hasSubstring("before_none_error"))
TEST_FALSE(error_content.hasSubstring("during_none_error"))
TEST_TRUE(error_content.hasSubstring("after_none_error"))
}
END_SECTION
START_SECTION((void setLogLevel(const String &log_level) - invalid level))
{
// Test that setLogLevel throws an exception for invalid log levels
TEST_EXCEPTION(Exception::IllegalArgument, LogConfigHandler::getInstance()->setLogLevel("INVALID_LEVEL"))
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/CVMappingTerm_test.cpp | .cpp | 8,533 | 343 | // 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/CVMappingTerm.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(CVMappingTerm, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
CVMappingTerm* ptr = nullptr;
CVMappingTerm* nullPointer = nullptr;
START_SECTION(CVMappingTerm())
{
ptr = new CVMappingTerm();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(virtual ~CVMappingTerm())
{
delete ptr;
}
END_SECTION
ptr = new CVMappingTerm();
START_SECTION((CVMappingTerm(const CVMappingTerm &rhs)))
{
CVMappingTerm cvmt;
cvmt.setAccession("my_test_accession");
TEST_STRING_EQUAL(CVMappingTerm(cvmt).getAccession(), "my_test_accession")
cvmt.setUseTermName(true);
TEST_EQUAL(CVMappingTerm(cvmt).getUseTermName(), true)
cvmt.setUseTermName(false);
TEST_EQUAL(CVMappingTerm(cvmt).getUseTermName(), false)
cvmt.setUseTerm(true);
TEST_EQUAL(CVMappingTerm(cvmt).getUseTerm(), true)
cvmt.setUseTerm(false);
TEST_EQUAL(CVMappingTerm(cvmt).getUseTerm(), false)
cvmt.setTermName("my_test_termname");
TEST_STRING_EQUAL(CVMappingTerm(cvmt).getTermName(), "my_test_termname")
cvmt.setIsRepeatable(true);
TEST_EQUAL(CVMappingTerm(cvmt).getIsRepeatable(), true)
cvmt.setIsRepeatable(false);
TEST_EQUAL(CVMappingTerm(cvmt).getIsRepeatable(), false)
cvmt.setAllowChildren(true);
TEST_EQUAL(CVMappingTerm(cvmt).getAllowChildren(), true)
cvmt.setAllowChildren(false);
TEST_EQUAL(CVMappingTerm(cvmt).getAllowChildren(), false)
cvmt.setCVIdentifierRef("my_test_cvidentifierref");
TEST_STRING_EQUAL(CVMappingTerm(cvmt).getCVIdentifierRef(), "my_test_cvidentifierref")
}
END_SECTION
START_SECTION((CVMappingTerm& operator=(const CVMappingTerm &rhs)))
{
CVMappingTerm cvmt, cvmt_copy;
cvmt.setAccession("my_test_accession");
cvmt_copy = cvmt;
TEST_STRING_EQUAL(cvmt_copy.getAccession(), "my_test_accession")
cvmt.setUseTermName(true);
cvmt_copy = cvmt;
TEST_EQUAL(cvmt_copy.getUseTermName(), true)
cvmt.setUseTermName(false);
cvmt_copy = cvmt;
TEST_EQUAL(cvmt_copy.getUseTermName(), false)
cvmt.setUseTerm(true);
cvmt_copy = cvmt;
TEST_EQUAL(cvmt_copy.getUseTerm(), true)
cvmt.setUseTerm(false);
cvmt_copy = cvmt;
TEST_EQUAL(cvmt_copy.getUseTerm(), false)
cvmt.setTermName("my_test_termname");
cvmt_copy = cvmt;
TEST_STRING_EQUAL(cvmt_copy.getTermName(), "my_test_termname")
cvmt.setIsRepeatable(true);
cvmt_copy = cvmt;
TEST_EQUAL(cvmt_copy.getIsRepeatable(), true)
cvmt.setIsRepeatable(false);
cvmt_copy = cvmt;
TEST_EQUAL(cvmt_copy.getIsRepeatable(), false)
cvmt.setAllowChildren(true);
cvmt_copy = cvmt;
TEST_EQUAL(cvmt_copy.getAllowChildren(), true)
cvmt.setAllowChildren(false);
cvmt_copy = cvmt;
TEST_EQUAL(cvmt_copy.getAllowChildren(), false)
cvmt.setCVIdentifierRef("my_test_cvidentifierref");
cvmt_copy = cvmt;
TEST_STRING_EQUAL(cvmt_copy.getCVIdentifierRef(), "my_test_cvidentifierref")
}
END_SECTION
START_SECTION((bool operator == (const CVMappingTerm& rhs) const))
{
CVMappingTerm cvmt, cvmt_copy;
cvmt.setAccession("my_test_accession");
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setUseTermName(true);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setUseTermName(false);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setUseTerm(true);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setUseTerm(false);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setTermName("my_test_termname");
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setIsRepeatable(true);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setIsRepeatable(false);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setAllowChildren(true);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setAllowChildren(false);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setCVIdentifierRef("my_test_cvidentifierref");
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
}
END_SECTION
START_SECTION((bool operator != (const CVMappingTerm& rhs) const))
{
CVMappingTerm cvmt, cvmt_copy;
cvmt.setAccession("my_test_accession");
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setUseTermName(true);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setUseTermName(false);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setUseTerm(true);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setUseTerm(false);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setTermName("my_test_termname");
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setIsRepeatable(true);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setIsRepeatable(false);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setAllowChildren(true);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setAllowChildren(false);
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
cvmt.setCVIdentifierRef("my_test_cvidentifierref");
TEST_EQUAL(cvmt_copy == cvmt, false)
cvmt_copy = cvmt;
TEST_TRUE(cvmt_copy == cvmt)
}
END_SECTION
START_SECTION((void setAccession(const String &accession)))
{
ptr->setAccession("my_test_accession");
TEST_STRING_EQUAL(ptr->getAccession(), "my_test_accession")
}
END_SECTION
START_SECTION((const String& getAccession() const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((void setUseTermName(bool use_term_name)))
{
ptr->setUseTermName(true);
TEST_EQUAL(ptr->getUseTermName(), true)
ptr->setUseTermName(false);
TEST_EQUAL(ptr->getUseTermName(), false)
}
END_SECTION
START_SECTION((bool getUseTermName() const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((void setUseTerm(bool use_term)))
{
ptr->setUseTerm(true);
TEST_EQUAL(ptr->getUseTerm(), true)
ptr->setUseTerm(false);
TEST_EQUAL(ptr->getUseTerm(), false)
}
END_SECTION
START_SECTION((bool getUseTerm() const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((void setTermName(const String &term_name)))
{
ptr->setTermName("my_test_termname");
TEST_EQUAL(ptr->getTermName(), "my_test_termname")
}
END_SECTION
START_SECTION((const String& getTermName() const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((void setIsRepeatable(bool is_repeatable)))
{
ptr->setIsRepeatable(true);
TEST_EQUAL(ptr->getIsRepeatable(), true)
ptr->setIsRepeatable(false);
TEST_EQUAL(ptr->getIsRepeatable(), false)
}
END_SECTION
START_SECTION((bool getIsRepeatable() const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((void setAllowChildren(bool allow_children)))
{
ptr->setAllowChildren(true);
TEST_EQUAL(ptr->getAllowChildren(), true)
ptr->setAllowChildren(false);
TEST_EQUAL(ptr->getAllowChildren(), false)
}
END_SECTION
START_SECTION((bool getAllowChildren() const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((void setCVIdentifierRef(const String &cv_identifier_ref)))
{
ptr->setCVIdentifierRef("my_test_cvidentifierref");
TEST_EQUAL(ptr->getCVIdentifierRef(), "my_test_cvidentifierref")
}
END_SECTION
START_SECTION((const String& getCVIdentifierRef() const ))
{
NOT_TESTABLE
}
END_SECTION
delete ptr;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MsInspectFile_test.cpp | .cpp | 2,221 | 80 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/MsInspectFile.h>
///////////////////////////
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
using namespace OpenMS;
using namespace std;
START_TEST(MsInspectFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MsInspectFile* ptr = nullptr;
MsInspectFile* null_ptr = nullptr;
START_SECTION(MsInspectFile())
{
ptr = new MsInspectFile();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(virtual ~MsInspectFile())
{
delete ptr;
}
END_SECTION
START_SECTION((template < typename FeatureMapType > void load(const String &filename, FeatureMapType &feature_map)))
{
MsInspectFile f;
FeatureMap fm;
f.load(OPENMS_GET_TEST_DATA_PATH("MSInspectFile_test_1.msi"), fm);
TEST_EQUAL(fm.size(), 2)
ABORT_IF(fm.size()!=2)
TEST_REAL_SIMILAR(fm[0].getRT(), 12.92)
TEST_REAL_SIMILAR(fm[0].getMZ(), 501.51)
TEST_REAL_SIMILAR(fm[0].getIntensity(), 45677)
TEST_REAL_SIMILAR(fm[0].getOverallQuality(), 0.98)
TEST_EQUAL(double(fm[0].getMetaValue("background")), 0.11)
TEST_REAL_SIMILAR(fm[1].getRT(), 22.92)
TEST_REAL_SIMILAR(fm[1].getMZ(), 601.51)
TEST_REAL_SIMILAR(fm[1].getIntensity(), 245677)
TEST_REAL_SIMILAR(fm[1].getOverallQuality(), 0.99)
TEST_EQUAL(double(fm[1].getMetaValue("background")), 0.22)
}
END_SECTION
START_SECTION((template < typename SpectrumType > void store(const String &filename, const SpectrumType &spectrum) const ))
{
MsInspectFile f;
MSSpectrum spec;
TEST_EXCEPTION(Exception::NotImplemented, f.store("bla", spec))
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ParamValue_test.cpp | .cpp | 35,978 | 896 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Authors: Ruben Grünberg $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/ParamValue.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/DATASTRUCTURES/ListUtilsIO.h>
#include <sstream>
#include <iostream>
#include <unordered_set>
#include <unordered_map>
// we ignore the -Wunused-value warning here, since we do not want the compiler
// to report problems like
// ParamValue_test.cpp:285:3: warning: expression result unused [-Wunused-value]
// TEST_EXCEPTION(Exception::ConversionError, (StringList)ParamValue("abc,ab"))
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-value"
#endif
///////////////////////////
START_TEST(ParamValue, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
// default ctor
ParamValue* dv_ptr = nullptr;
ParamValue* dv_nullPointer = nullptr;
START_SECTION((ParamValue()))
// Just as a sanity check, the size of ParamValue should be exactly 16 bytes
// on a 64 bit system:
// - 1 byte for the data type
// - 7 byte padding
// - 8 bytes for the actual data / pointers to data
std::cout << "\n\n --- Size of ParamValue " << sizeof(ParamValue) << std::endl;
dv_ptr = new ParamValue;
TEST_NOT_EQUAL(dv_ptr, dv_nullPointer)
END_SECTION
// destructor
START_SECTION((virtual ~ParamValue()))
delete dv_ptr;
END_SECTION
// ctor for all supported types a ParamValue object can hold
START_SECTION((ParamValue(long double)))
long double x = -3.4L;
ParamValue d(x);
// Note: The implementation uses typedef double (as opposed to float, double, long double.)
TEST_REAL_SIMILAR((double)d, -3.4L)
END_SECTION
START_SECTION((ParamValue(double)))
double x = -3.0;
ParamValue d(x);
// Note: The implementation uses typedef double (as opposed to float, double, long double.)
TEST_REAL_SIMILAR((double)d, -3.0);
END_SECTION
START_SECTION((ParamValue(float)))
float x = 3.0;
ParamValue d(x);
// Note: The implementation uses typedef double (as opposed to float, double, long double.)
TEST_REAL_SIMILAR((double)d, 3.0);
END_SECTION
START_SECTION((ParamValue(short int)))
short int n = -3000;
ParamValue d(n);
TEST_EQUAL((short int)d, -3000)
END_SECTION
START_SECTION((ParamValue(unsigned short int)))
unsigned short int n = 3000u;
ParamValue d(n);
TEST_EQUAL((unsigned short)d, 3000u)
END_SECTION
START_SECTION((ParamValue(int)))
int n = -3000;
ParamValue d(n);
TEST_EQUAL((int)d, -3000)
END_SECTION
START_SECTION((ParamValue(unsigned)))
unsigned int n = 3000u;
ParamValue d(n);
TEST_EQUAL((unsigned int)d, 3000u)
END_SECTION
START_SECTION((ParamValue(long int)))
long int n = -3000;
ParamValue d(n);
TEST_EQUAL((long int)d, -3000)
END_SECTION
START_SECTION((ParamValue(unsigned long)))
unsigned long int n = 3000u;
ParamValue d(n);
TEST_EQUAL((unsigned long int)d, 3000u)
END_SECTION
START_SECTION((ParamValue(long long)))
long long n = -3000;
ParamValue d(n);
TEST_EQUAL((long long) d, -3000)
END_SECTION
START_SECTION((ParamValue(unsigned long long)))
unsigned long long n = 3000;
ParamValue d(n);
TEST_EQUAL((unsigned long long) d, 3000)
END_SECTION
START_SECTION((ParamValue(const char*)))
const char* s = "test char";
ParamValue d(s);
TEST_EQUAL((std::string)d, "test char")
END_SECTION
START_SECTION((ParamValue(const std::string&)))
string s = "test string";
ParamValue d(s);
TEST_EQUAL(d, "test string")
END_SECTION
START_SECTION((ParamValue(const vector<string> &)))
vector<string> sl = {"test string", "test String 2"};
ParamValue d(sl);
TEST_TRUE(d == sl)
END_SECTION
START_SECTION((ParamValue(const vector<int> &)))
vector<int> il = {1, 2};
ParamValue d(il);
TEST_TRUE(d == il)
END_SECTION
START_SECTION((ParamValue(const vector<double> &)))
vector<double> dl = {1.2, 22.3333};
ParamValue d(dl);
//vector<double> dldv = d;
TEST_TRUE(d == dl);
END_SECTION
// copy ctor
START_SECTION((ParamValue(const ParamValue&)))
{
ParamValue p1((double) 1.23);
ParamValue p3((float) 1.23);
ParamValue p4((Int) -3);
ParamValue p5((UInt) 123);
ParamValue p6("test char");
ParamValue p7(std::string("test string"));
ParamValue p8({"test string","string2","last string"});
ParamValue p9;
ParamValue p10(vector<int>{1,2,3,4,5});
ParamValue p11(vector<double>{1.2,2.3,3.4});
ParamValue copy_of_p1(p1);
ParamValue copy_of_p3(p3);
ParamValue copy_of_p4(p4);
ParamValue copy_of_p5(p5);
ParamValue copy_of_p6(p6);
ParamValue copy_of_p7(p7);
ParamValue copy_of_p8(p8);
ParamValue copy_of_p9(p9);
ParamValue copy_of_p10(p10);
ParamValue copy_of_p11(p11);
TEST_REAL_SIMILAR( (double) copy_of_p1, 1.23)
TEST_REAL_SIMILAR( (float) copy_of_p3, 1.23)
TEST_EQUAL( (Int) copy_of_p4, -3)
TEST_EQUAL( (UInt) copy_of_p5, 123)
TEST_EQUAL( (std::string) copy_of_p6, "test char")
TEST_EQUAL( (std::string) copy_of_p7, "test string")
TEST_EQUAL( copy_of_p8 == ListUtils::create<string>("test string,string2,last string"), true)
TEST_EQUAL( (copy_of_p9.isEmpty()), true)
TEST_EQUAL( copy_of_p10 == ListUtils::create<int>("1,2,3,4,5"), true)
TEST_EQUAL( copy_of_p11 == ListUtils::create<double>("1.2,2.3,3.4"), true)
}
END_SECTION
// move ctor
START_SECTION((ParamValue(ParamValue&&) noexcept))
{
// Ensure that ParamValue has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(ParamValue(std::declval<ParamValue&&>())), true)
ParamValue empty;
ParamValue p1((double) 1.23);
ParamValue p3((float) 1.23);
ParamValue p4((Int) -3);
ParamValue p5((UInt) 123);
ParamValue p6("test char");
ParamValue p7(std::string("test string"));
ParamValue p8({"test string","string2","last string"});
ParamValue p9;
ParamValue p10(vector<int>{1,2,3,4,5});
ParamValue p11(vector<double>{1.2,2.3,3.4});
ParamValue copy_of_p1(std::move(p1));
ParamValue copy_of_p3(std::move(p3));
ParamValue copy_of_p4(std::move(p4));
ParamValue copy_of_p5(std::move(p5));
ParamValue copy_of_p6(std::move(p6));
ParamValue copy_of_p7(std::move(p7));
ParamValue copy_of_p8(std::move(p8));
ParamValue copy_of_p9(std::move(p9));
ParamValue copy_of_p10(std::move(p10));
ParamValue copy_of_p11(std::move(p11));
TEST_REAL_SIMILAR( (double) copy_of_p1, 1.23)
TEST_REAL_SIMILAR( (float) copy_of_p3, 1.23)
TEST_EQUAL( (Int) copy_of_p4, -3)
TEST_EQUAL( (UInt) copy_of_p5, 123)
TEST_EQUAL( (std::string) copy_of_p6, "test char")
TEST_EQUAL( (std::string) copy_of_p7, "test string")
TEST_EQUAL( copy_of_p8 == ListUtils::create<string>("test string,string2,last string"), true)
TEST_EQUAL( (copy_of_p9.isEmpty()), true)
TEST_EQUAL( copy_of_p10 == ListUtils::create<int>("1,2,3,4,5"), true)
TEST_EQUAL( copy_of_p11 == ListUtils::create<double>("1.2,2.3,3.4"), true)
TEST_TRUE(p1 == empty)
TEST_TRUE(p3 == empty)
TEST_TRUE(p4 == empty)
TEST_TRUE(p5 == empty)
TEST_TRUE(p6 == empty)
TEST_TRUE(p7 == empty)
TEST_TRUE(p8 == empty)
TEST_TRUE(p9 == empty)
TEST_TRUE(p10 == empty)
TEST_TRUE(p11 == empty)
}
END_SECTION
// assignment operator
START_SECTION((ParamValue& operator=(const ParamValue&)))
{
ParamValue p1((double) 1.23);
ParamValue p3((float) 1.23);
ParamValue p4((Int) -3);
ParamValue p5((UInt) 123);
ParamValue p6("test char");
ParamValue p7(std::string("test string"));
ParamValue p8({"test string","string2","last string"});
ParamValue p9;
ParamValue p10(vector<int>{1,2,3,4,5});
ParamValue p11(vector<double>{1.2,2.3,3.4});
ParamValue copy_of_p;
copy_of_p = p1;
TEST_REAL_SIMILAR( (double) copy_of_p, 1.23)
copy_of_p = p3;
TEST_REAL_SIMILAR( (float) copy_of_p, 1.23)
copy_of_p = p4;
TEST_EQUAL( (Int) copy_of_p, -3)
copy_of_p = p5;
TEST_EQUAL( (UInt) copy_of_p, 123)
copy_of_p = p6;
TEST_EQUAL( (std::string) copy_of_p, "test char")
copy_of_p = p7;
TEST_EQUAL( (std::string) copy_of_p, "test string")
copy_of_p = p8;
TEST_EQUAL( copy_of_p == ListUtils::create<string>("test string,string2,last string"), true)
copy_of_p = p9;
TEST_EQUAL( (copy_of_p.isEmpty()), true)
copy_of_p = p10;
TEST_EQUAL(copy_of_p == ListUtils::create<int>("1,2,3,4,5"), true)
copy_of_p = p11;
TEST_EQUAL(copy_of_p == ListUtils::create<double>("1.2,2.3,3.4"), true)
}
END_SECTION
// move assignment operator
START_SECTION(( ParamValue& operator=(ParamValue&&) noexcept ))
{
// Ensure that ParamValue has a no-except move assignment operator.
TEST_EQUAL(noexcept(declval<ParamValue&>() = declval<ParamValue &&>()), true)
ParamValue empty;
ParamValue p1((double) 1.23);
ParamValue p3((float) 1.23);
ParamValue p4((Int) -3);
ParamValue p5((UInt) 123);
ParamValue p6("test char");
ParamValue p7(std::string("test string"));
ParamValue p8({"test string","string2","last string"});
ParamValue p9;
ParamValue p10(vector<int>{1,2,3,4,5});
ParamValue p11(vector<double>{1.2,2.3,3.4});
ParamValue copy_of_p;
copy_of_p = std::move(p1);
TEST_REAL_SIMILAR( (double) copy_of_p, 1.23)
copy_of_p = std::move(p3);
TEST_REAL_SIMILAR( (float) copy_of_p, 1.23)
copy_of_p = std::move(p4);
TEST_EQUAL( (Int) copy_of_p, -3)
copy_of_p = std::move(p5);
TEST_EQUAL( (UInt) copy_of_p, 123)
copy_of_p = std::move(p6);
TEST_EQUAL( (std::string) copy_of_p, "test char")
copy_of_p = std::move(p7);
TEST_EQUAL( (std::string) copy_of_p, "test string")
copy_of_p = std::move(p8);
TEST_EQUAL( copy_of_p == ListUtils::create<string>("test string,string2,last string"), true)
copy_of_p = std::move(p9);
TEST_EQUAL( (copy_of_p.isEmpty()), true)
copy_of_p = std::move(p10);
TEST_EQUAL(copy_of_p == ListUtils::create<int>("1,2,3,4,5"), true)
copy_of_p = std::move(p11);
TEST_EQUAL(copy_of_p == ListUtils::create<double>("1.2,2.3,3.4"), true)
TEST_TRUE(p1 == empty)
TEST_TRUE(p3 == empty)
TEST_TRUE(p4 == empty)
TEST_TRUE(p5 == empty)
TEST_TRUE(p6 == empty)
TEST_TRUE(p7 == empty)
TEST_TRUE(p8 == empty)
TEST_TRUE(p9 == empty)
TEST_TRUE(p10 == empty)
TEST_TRUE(p11 == empty)
}
END_SECTION
// Is ParamValue object empty?
START_SECTION((bool isEmpty() const))
{
ParamValue p1;
TEST_EQUAL(p1.isEmpty(), true);
ParamValue p2((float)1.2);
TEST_EQUAL(p2.isEmpty(), false);
TEST_REAL_SIMILAR((float) p2, 1.2);
ParamValue p3("");
TEST_EQUAL(p3.isEmpty(), false); // empty string does not count as empty!
ParamValue p4("2");
TEST_EQUAL(p4.isEmpty(), false)
TEST_EQUAL((std::string) p4, "2");
}
END_SECTION
// conversion operators
START_SECTION((operator std::string() const))
ParamValue d((std::string) "test string");
std::string k = d;
TEST_EQUAL(k,"test string")
END_SECTION
START_SECTION((operator vector<string>() const))
vector<string> sl = {"test string list"};
ParamValue d(sl);
vector<string> sl_op = d;
TEST_TRUE(sl_op == d)
END_SECTION
START_SECTION((vector<string> toStringVector() const))
vector<string> sl = {"test string list"};
ParamValue d(sl);
vector<string> sl_op = d.toStringVector();
TEST_TRUE(sl_op == d)
END_SECTION
START_SECTION((operator vector<int>() const))
vector<int> il = {1, 2};
ParamValue d(il);
vector<int> il_op = d;
TEST_TRUE(il_op == il)
TEST_EXCEPTION(Exception::ConversionError, vector<string> sl = ParamValue("abc,ab");)
END_SECTION
START_SECTION((vector<int> toIntVector() const))
vector<int> il = {1, 2};
ParamValue d(il);
vector<int> il_op = d.toIntVector();
TEST_TRUE(il_op == il)
TEST_EXCEPTION(Exception::ConversionError, vector<string> sl = ParamValue("abc,ab").toStringVector();)
END_SECTION
START_SECTION((operator vector<double>() const))
vector<double> dl = {1.2, 22.34455};
ParamValue d(dl);
vector<double> dl_op = d;
TEST_TRUE(dl_op == d);
END_SECTION
START_SECTION((DoubleList toDoubleVector() const))
vector<double> dl = {1.2, 22.34455};
ParamValue d(dl);
vector<double> dl_op = d.toDoubleVector();
TEST_TRUE(dl_op == d);
END_SECTION
START_SECTION((operator long double() const))
ParamValue d(5.4L);
long double k = d;
TEST_REAL_SIMILAR(k,5.4L)
END_SECTION
START_SECTION((operator double() const))
ParamValue d(5.4);
double k = d;
TEST_REAL_SIMILAR(k,5.4)
END_SECTION
START_SECTION((operator float() const))
ParamValue d(5.4f);
float k = d;
TEST_REAL_SIMILAR(k,5.4f)
END_SECTION
START_SECTION((operator int() const ))
ParamValue d((Int) -55);
int k = d;
TEST_EQUAL(k,-55)
TEST_EXCEPTION(Exception::ConversionError, (int)ParamValue(55.4))
END_SECTION
START_SECTION((operator unsigned int() const ))
ParamValue d((Int) 55);
unsigned int k = d;
TEST_EQUAL(k,55)
TEST_EXCEPTION(Exception::ConversionError, (unsigned int)ParamValue(-55))
TEST_EXCEPTION(Exception::ConversionError, (unsigned int)ParamValue(55.4))
END_SECTION
START_SECTION((operator short int() const))
ParamValue d((short int) -55);
short int k = d;
TEST_EQUAL(k,-55)
TEST_EXCEPTION(Exception::ConversionError, (short int)ParamValue(55.4))
END_SECTION
START_SECTION((operator unsigned short int() const))
ParamValue d((short int) 55);
unsigned short int k = d;
TEST_EQUAL(k,55)
TEST_EXCEPTION(Exception::ConversionError, (unsigned short int)ParamValue(-55))
TEST_EXCEPTION(Exception::ConversionError, (unsigned short int)ParamValue(55.4))
END_SECTION
START_SECTION((operator long int() const))
ParamValue d((long int) -55);
long int k = d;
TEST_EQUAL(k,-55)
TEST_EXCEPTION(Exception::ConversionError, (long int)ParamValue(55.4))
END_SECTION
START_SECTION((operator unsigned long int() const))
ParamValue d((long int) 55);
unsigned long int k = d;
TEST_EQUAL(k,55)
TEST_EXCEPTION(Exception::ConversionError, (unsigned long int)ParamValue(-55))
TEST_EXCEPTION(Exception::ConversionError, (unsigned long int)ParamValue(55.4))
END_SECTION
START_SECTION((operator long long() const))
{
{
ParamValue d((long long) 55);
long long k = d;
TEST_EQUAL(k,55)
}
{
ParamValue d((long long) -1);
long long k = d;
TEST_EQUAL(k,-1)
}
{
ParamValue d((SignedSize) -55);
SignedSize k = d;
TEST_EQUAL(k,-55)
}
TEST_EXCEPTION(Exception::ConversionError, (long int)ParamValue(55.4))
}
END_SECTION
START_SECTION((operator unsigned long long() const))
{
{
ParamValue d((unsigned long long) 55);
unsigned long long k = d;
TEST_EQUAL(k,55)
}
{
ParamValue d((Size) 55);
Size k = d;
TEST_EQUAL(k,55)
}
TEST_EXCEPTION(Exception::ConversionError, (unsigned long int)ParamValue(-55))
TEST_EXCEPTION(Exception::ConversionError, (unsigned long int)ParamValue(55.4))
}
END_SECTION
START_SECTION(([EXTRA] friend bool operator==(const ParamValue&, const ParamValue&)))
{
ParamValue a(5.0);
ParamValue b(5.0);
TEST_EQUAL(a==b,true);
a = ParamValue((double)15.13);
b = ParamValue((double)15.13);
TEST_EQUAL(a==b,true);
a = ParamValue((float)15.13);
b = ParamValue((float)(17-1.87));
TEST_EQUAL(a==b,true);
a = ParamValue((Int)5);
b = ParamValue((Int)5);
TEST_EQUAL(a==b,true);
a = ParamValue((UInt)5000);
b = ParamValue((UInt)5000);
TEST_EQUAL(a==b,true);
a = ParamValue("hello");
b = ParamValue(std::string("hello"));
TEST_EQUAL(a==b,true);
a = ParamValue((float)15.13);
b = ParamValue((float)(15.13001));
TEST_EQUAL(a==b,false);
}
END_SECTION
START_SECTION(([EXTRA] friend bool operator!=(const ParamValue&, const ParamValue&)))
{
ParamValue a(5.0);
ParamValue b(5.1);
TEST_EQUAL(a!=b,true);
a = ParamValue((double)15.13001);
b = ParamValue((double)15.13);
TEST_EQUAL(a!=b,true);
a = ParamValue("hello");
b = ParamValue(std::string("hello"));
TEST_EQUAL(a!=b,false);
}
END_SECTION
START_SECTION((const char* toChar() const))
ParamValue a;
TEST_EQUAL(a.toChar() == nullptr, true)
a = ParamValue("hello");
TEST_STRING_EQUAL(a.toChar(),"hello")
a = ParamValue(5);
TEST_EXCEPTION(Exception::ConversionError, a.toChar() )
END_SECTION
START_SECTION((String toString(bool full_precision) const))
ParamValue a;
TEST_EQUAL(a.toString(), "")
a = ParamValue("hello");
TEST_EQUAL(a.toString(),"hello")
a = ParamValue(5);
TEST_EQUAL(a.toString(), "5")
a = ParamValue(47.11);
TEST_EQUAL(a.toString(), "47.109999999999999")
TEST_EQUAL(a.toString(false), "47.11")
a = ParamValue(-23456.78);
TEST_EQUAL(a.toString(), "-2.345678e04")
a = ParamValue(ListUtils::create<string>("test string,string2,last string"));
TEST_EQUAL(a.toString(), "[test string, string2, last string]")
a = ParamValue(ListUtils::create<int>("1,2,3,4,5"));
TEST_EQUAL(a.toString(),"[1, 2, 3, 4, 5]")
a = ParamValue(ListUtils::create<double>("1.2,47.11,1.2345678e05"));
TEST_EQUAL(a.toString(),"[1.2, 47.109999999999999, 1.2345678e05]")
TEST_EQUAL(a.toString(false), "[1.2, 47.11, 1.235e05]")
END_SECTION
START_SECTION((bool toBool() const))
//valid cases
ParamValue a("true");
TEST_EQUAL(a.toBool(),true)
a = ParamValue("false");
TEST_EQUAL(a.toBool(),false)
//invalid cases
a = ParamValue();
TEST_EXCEPTION(Exception::ConversionError, a.toBool() )
a = ParamValue("bla");
TEST_EXCEPTION(Exception::ConversionError, a.toBool() )
a = ParamValue(12);
TEST_EXCEPTION(Exception::ConversionError, a.toBool() )
a = ParamValue(34.45);
TEST_EXCEPTION(Exception::ConversionError, a.toBool() )
END_SECTION
START_SECTION(([EXTRA] friend std::ostream& operator<<(std::ostream&, const ParamValue&)))
ParamValue a((Int)5), b((UInt)100), c((double)1.111), d((double)1.1), e("hello "), f(std::string("world")), g;
std::ostringstream os;
os << a << b << c << d << e << f << g;
TEST_EQUAL(os.str(),"51001.1111.1hello world")
END_SECTION
START_SECTION((DataType valueType() const))
ParamValue a;
TEST_EQUAL(a.valueType(), ParamValue::EMPTY_VALUE);
ParamValue a1(1.45);
TEST_EQUAL(a1.valueType(), ParamValue::DOUBLE_VALUE);
ParamValue a2(1.34f);
TEST_EQUAL(a2.valueType(), ParamValue::DOUBLE_VALUE);
ParamValue a3(123);
TEST_EQUAL(a3.valueType(), ParamValue::INT_VALUE);
ParamValue a4("bla");
TEST_EQUAL(a4.valueType(), ParamValue::STRING_VALUE);
ParamValue a5(ListUtils::create<string>("test string,string2,last string"));
TEST_EQUAL(a5.valueType(), ParamValue::STRING_LIST)
ParamValue a6(UInt(2));
TEST_EQUAL(a6.valueType(), ParamValue::INT_VALUE);
ParamValue a7(ListUtils::create<int>("1,2,3"));
TEST_EQUAL(a7.valueType(),ParamValue::INT_LIST)
ParamValue a8(ListUtils::create<double>("1.2,32.4567"));
TEST_EQUAL(a8.valueType(),ParamValue::DOUBLE_LIST);
END_SECTION
START_SECTION((ParamValue& operator=(const char*)))
{
const char * v = "value";
ParamValue a("v");
a = v;
TEST_EQUAL(a, "value")
}
END_SECTION
START_SECTION((ParamValue& operator=(const std::string&)))
{
std::string v = "value";
ParamValue a("v");
a = v;
TEST_EQUAL(a, "value")
}
END_SECTION
START_SECTION((ParamValue& operator=(const vector<string>&)))
{
vector<string> v = {"value","value2"};
ParamValue a("v");
a = v;
vector<string> sla = a;
TEST_EQUAL(sla.size(), 2)
ABORT_IF(sla.size() != 2)
TEST_EQUAL(sla[0], "value")
TEST_EQUAL(sla[1], "value2")
}
END_SECTION
START_SECTION((ParamValue& operator=(const vector<int>&)))
{
vector<int> v = {2,-3};
ParamValue a("v");
a = v;
vector<int> dv = a;
TEST_EQUAL(dv.size(), 2)
ABORT_IF(dv.size() != 2)
TEST_EQUAL(dv[0], 2)
TEST_EQUAL(dv[1], -3)
}
END_SECTION
START_SECTION((ParamValue& operator=(const vector<double>&)))
{
vector<double> v = {2.14,-3.45};
ParamValue a("v");
a = v;
vector<double> adl = a;
TEST_EQUAL(adl.size(), 2)
ABORT_IF(adl.size() != 2)
TEST_EQUAL(adl[0], 2.14)
TEST_EQUAL(adl[1], -3.45)
}
END_SECTION
START_SECTION((ParamValue& operator=(const long double)))
{
const long double v = 2.44;
ParamValue a("v");
a = v;
TEST_EQUAL((long double)a, 2.44)
}
END_SECTION
START_SECTION((ParamValue& operator=(const double)))
{
const double v = 2.44;
ParamValue a("v");
a = v;
TEST_EQUAL((double)a, 2.44)
}
END_SECTION
START_SECTION((ParamValue& operator=(const float)))
{
const float v = 2.44f;
ParamValue a("v");
a = v;
TEST_EQUAL((float)a, 2.44f)
}
END_SECTION
START_SECTION((ParamValue& operator=(const short int)))
{
const short int v = 2;
ParamValue a("v");
a = v;
TEST_EQUAL((short int)a, 2)
}
END_SECTION
START_SECTION((ParamValue& operator=(const unsigned short int)))
{
const unsigned short int v = 2;
ParamValue a("v");
a = v;
TEST_EQUAL((unsigned short int)a, 2)
}
END_SECTION
START_SECTION((ParamValue& operator=(const int)))
{
const int v = 2;
ParamValue a("v");
a = v;
TEST_EQUAL((int)a, 2)
}
END_SECTION
START_SECTION((ParamValue& operator=(const unsigned)))
{
const unsigned v = 2;
ParamValue a("v");
a = v;
TEST_EQUAL((unsigned)a, 2)
}
END_SECTION
START_SECTION((ParamValue& operator=(const long int)))
{
const long int v = 2;
ParamValue a("v");
a = v;
TEST_EQUAL((long int)a, 2)
}
END_SECTION
START_SECTION((ParamValue& operator=(const unsigned long)))
{
const unsigned long v = 2;
ParamValue a("v");
a = v;
TEST_EQUAL((unsigned long)a, 2)
}
END_SECTION
START_SECTION((ParamValue& operator=(const long long)))
{
const long long v = 2;
ParamValue a("v");
a = v;
TEST_EQUAL((long long)a, 2)
}
END_SECTION
START_SECTION((ParamValue& operator=(const unsigned long long)))
{
const unsigned long long v = 2;
ParamValue a("v");
a = v;
TEST_EQUAL((unsigned long long)a, 2)
}
END_SECTION
START_SECTION(([EXTRA] std::hash<ParamValue>))
{
std::hash<ParamValue> hasher;
// Test that equal objects have equal hashes
// Empty values
ParamValue empty1, empty2;
TEST_EQUAL(hasher(empty1), hasher(empty2))
// String values
ParamValue str1("hello"), str2("hello"), str3("world");
TEST_EQUAL(hasher(str1), hasher(str2))
TEST_NOT_EQUAL(hasher(str1), hasher(str3))
// Int values
ParamValue int1(42), int2(42), int3(-17);
TEST_EQUAL(hasher(int1), hasher(int2))
TEST_NOT_EQUAL(hasher(int1), hasher(int3))
// Double values
ParamValue dbl1(3.14159), dbl2(3.14159), dbl3(2.71828);
TEST_EQUAL(hasher(dbl1), hasher(dbl2))
TEST_NOT_EQUAL(hasher(dbl1), hasher(dbl3))
// String list values
ParamValue sl1(vector<string>{"a", "b", "c"});
ParamValue sl2(vector<string>{"a", "b", "c"});
ParamValue sl3(vector<string>{"x", "y"});
TEST_EQUAL(hasher(sl1), hasher(sl2))
TEST_NOT_EQUAL(hasher(sl1), hasher(sl3))
// Int list values
ParamValue il1(vector<int>{1, 2, 3});
ParamValue il2(vector<int>{1, 2, 3});
ParamValue il3(vector<int>{4, 5});
TEST_EQUAL(hasher(il1), hasher(il2))
TEST_NOT_EQUAL(hasher(il1), hasher(il3))
// Double list values
ParamValue dl1(vector<double>{1.1, 2.2, 3.3});
ParamValue dl2(vector<double>{1.1, 2.2, 3.3});
ParamValue dl3(vector<double>{4.4, 5.5});
TEST_EQUAL(hasher(dl1), hasher(dl2))
TEST_NOT_EQUAL(hasher(dl1), hasher(dl3))
// Different types should have different hashes
ParamValue pv_int(5);
ParamValue pv_dbl(5.0);
ParamValue pv_str("5");
TEST_NOT_EQUAL(hasher(pv_int), hasher(pv_dbl))
TEST_NOT_EQUAL(hasher(pv_int), hasher(pv_str))
TEST_NOT_EQUAL(hasher(pv_dbl), hasher(pv_str))
// Test use in unordered_set
std::unordered_set<ParamValue> pv_set;
pv_set.insert(ParamValue("test"));
pv_set.insert(ParamValue(42));
pv_set.insert(ParamValue(3.14));
pv_set.insert(ParamValue(vector<string>{"a", "b"}));
pv_set.insert(ParamValue(vector<int>{1, 2, 3}));
pv_set.insert(ParamValue(vector<double>{1.1, 2.2}));
pv_set.insert(ParamValue()); // empty value
TEST_EQUAL(pv_set.size(), 7)
// Inserting duplicate should not increase size
pv_set.insert(ParamValue("test"));
pv_set.insert(ParamValue(42));
TEST_EQUAL(pv_set.size(), 7)
// Test lookup
TEST_EQUAL(pv_set.count(ParamValue("test")), 1)
TEST_EQUAL(pv_set.count(ParamValue(42)), 1)
TEST_EQUAL(pv_set.count(ParamValue("not_present")), 0)
// Test use in unordered_map
std::unordered_map<ParamValue, std::string> pv_map;
pv_map[ParamValue("key1")] = "value1";
pv_map[ParamValue(123)] = "value2";
pv_map[ParamValue(4.56)] = "value3";
TEST_EQUAL(pv_map.size(), 3)
TEST_EQUAL(pv_map[ParamValue("key1")], "value1")
TEST_EQUAL(pv_map[ParamValue(123)], "value2")
TEST_EQUAL(pv_map[ParamValue(4.56)], "value3")
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MRMTransitionGroupPicker_test.cpp | .cpp | 38,410 | 817 | // 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/test_config.h>
#include <OpenMS/CONCEPT/ClassTest.h>
///////////////////////////
#include <OpenMS/ANALYSIS/OPENSWATH/MRMTransitionGroupPicker.h>
///////////////////////////
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/FORMAT/TraMLFile.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <boost/assign/std/vector.hpp>
using namespace OpenMS;
using namespace std;
typedef MSChromatogram RichPeakChromatogram;
// TODO also test the picker with the LightTransition interface
// typedef MRMTransitionGroup<RichPeakChromatogram, OpenSwath::LightTransition> MRMTransitionGroupType;
typedef MRMTransitionGroup<RichPeakChromatogram, ReactionMonitoringTransition> MRMTransitionGroupType;
void setup_transition_group(MRMTransitionGroupType & transition_group)
{
// this is a simulated SRM experiment where the two traces are not sampled at
// the exact same time points, thus a re-sampling is necessary before applying
// the algorithm.
// The MS1 trace intensity is a simple quadratic function.
//
/*
* Python code to create the MS1 trace :
*
datapoints = [-100*(x-9)*(x-9)+9000 for x in range(18) ]
sum(datapoints[3:10])
53900
*/
static const double rtdata_1[] = {1474.34, 1477.11, 1479.88, 1482.64,
1485.41, 1488.19, 1490.95, 1493.72, 1496.48, 1499.25, 1502.03, 1504.8,
1507.56, 1510.33, 1513.09, 1515.87, 1518.64, 1521.42};
static const double rtdata_2[] = {1473.55, 1476.31, 1479.08, 1481.84,
1484.61, 1487.39, 1490.15, 1492.92, 1495.69, 1498.45, 1501.23, 1504,
1506.76, 1509.53, 1512.29, 1515.07, 1517.84, 1520.62};
static const double intdata_1[] = {3.26958, 3.74189, 3.31075, 86.1901,
3.47528, 387.864, 13281 , 6375.84, 39852.6, 2.66726, 612.747, 3.34313,
793.12 , 3.29156, 4.00586, 4.1591 , 3.23035, 3.90591};
static const double intdata_2[] = {3.44054 , 2142.31 , 3.58763 , 3076.97 ,
6663.55 , 45681 , 157694 , 122844 , 86034.7 , 85391.1 , 15992.8 ,
2293.94 , 6934.85 , 2735.18 , 459.413 , 3.93863 , 3.36564 , 3.44005};
static const double ms1_intdata[] = {900, 2600, 4100, 5400, 6500, 7400,
8100, 8600, 8900, 9000, 8900, 8600, 8100, 7400, 6500, 5400, 4100, 2600};
// Transition trace 1
{
ReactionMonitoringTransition transition;
transition.setNativeID("1");
RichPeakChromatogram chromatogram;
for (int k = 0; k < 18; k++)
{
ChromatogramPeak peak;
peak.setRT(rtdata_1[k]);
peak.setIntensity(intdata_1[k]);
chromatogram.push_back(peak);
}
chromatogram.setMetaValue("product_mz", 618.31);
chromatogram.setNativeID("1");
transition_group.addChromatogram(chromatogram, chromatogram.getNativeID());
transition_group.addTransition(transition, transition.getNativeID());
}
// Transition trace 2
{
ReactionMonitoringTransition transition;
transition.setNativeID("2");
RichPeakChromatogram chromatogram;
for (int k = 0; k < 18; k++)
{
ChromatogramPeak peak;
peak.setRT(rtdata_2[k]);
peak.setIntensity(intdata_2[k]);
chromatogram.push_back(peak);
}
chromatogram.setMetaValue("product_mz", 619.31);
chromatogram.setNativeID("2");
transition_group.addChromatogram(chromatogram, chromatogram.getNativeID());
transition_group.addTransition(transition, transition.getNativeID());
}
// MS1 trace
{
RichPeakChromatogram chromatogram;
for (int k = 0; k < 18; k++)
{
ChromatogramPeak peak;
peak.setRT(rtdata_2[k] + 0.5); // shift the "MS1" retention time as well
peak.setIntensity(ms1_intdata[k]);
chromatogram.push_back(peak);
}
chromatogram.setNativeID("Precursor_i0");
transition_group.addPrecursorChromatogram(chromatogram, "Precursor_i0");
}
}
void setup_transition_group2(MRMTransitionGroupType & transition_group)
{
// Simulated SRM experiment with a large peak in trace 1,
// two smaller peaks in trace 2 that overlap with the peak in trace 1,
// and no peaks in trace 3
static const double rtdata_1[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29};
static const double rtdata_2[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29};
static const double rtdata_3[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29};
static const double intdata_1[] = {3,3,3,3,3,3,3,3,4,6,8,12,14,15,16,15,14,12,8,6,4,3,3,3,3,3,3,3,3,3};
static const double intdata_2[] = {3,3,4,6,8,10,11,11,10,8,6,4,4,6,8,10,11,11,10,8,6,4,3,3,3,3,3,3,3,3};
static const double intdata_3[] = {3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3};
// Transition trace 1
{
ReactionMonitoringTransition transition;
transition.setNativeID("1");
RichPeakChromatogram chromatogram;
for (int k = 0; k < 30; k++)
{
ChromatogramPeak peak;
peak.setRT(rtdata_1[k]);
peak.setIntensity(intdata_1[k]);
chromatogram.push_back(peak);
}
chromatogram.setMetaValue("product_mz", 618.31);
chromatogram.setNativeID("1");
transition_group.addChromatogram(chromatogram, chromatogram.getNativeID());
transition_group.addTransition(transition, transition.getNativeID());
}
// Transition trace 2
{
ReactionMonitoringTransition transition;
transition.setNativeID("2");
RichPeakChromatogram chromatogram;
for (int k = 0; k < 30; k++)
{
ChromatogramPeak peak;
peak.setRT(rtdata_2[k]);
peak.setIntensity(intdata_2[k]);
chromatogram.push_back(peak);
}
chromatogram.setMetaValue("product_mz", 619.31);
chromatogram.setNativeID("2");
transition_group.addChromatogram(chromatogram, chromatogram.getNativeID());
transition_group.addTransition(transition, transition.getNativeID());
}
// Transition trace 3
{
ReactionMonitoringTransition transition;
transition.setNativeID("3");
RichPeakChromatogram chromatogram;
for (int k = 0; k < 30; k++)
{
ChromatogramPeak peak;
peak.setRT(rtdata_3[k]);
peak.setIntensity(intdata_3[k]);
chromatogram.push_back(peak);
}
chromatogram.setMetaValue("product_mz", 812.2);
chromatogram.setNativeID("3");
transition_group.addChromatogram(chromatogram, chromatogram.getNativeID());
transition_group.addTransition(transition, transition.getNativeID());
}
}
void setup_toy_chromatogram(RichPeakChromatogram & chromatogram)
{
// Toy chromatogram
// data is taken from raw LC-MS/MS data points acquired for L-Glutamate in RBCs
std::vector<double> time={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};
std::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};
for (size_t k = 0; k < time.size(); k++)
{
ChromatogramPeak peak;
peak.setRT(time[k]);
peak.setIntensity(intensity[k]);
chromatogram.push_back(peak);
}
}
START_TEST(MRMTransitionGroupPicker, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MRMTransitionGroupPicker* ptr = nullptr;
MRMTransitionGroupPicker* nullPointer = nullptr;
START_SECTION(MRMTransitionGroupPicker())
{
ptr = new MRMTransitionGroupPicker();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~MRMTransitionGroupPicker())
{
delete ptr;
}
END_SECTION
START_SECTION((template < typename SpectrumT, typename TransitionT > void pickTransitionGroup(MRMTransitionGroup< SpectrumT, TransitionT > &transition_group)))
{
{ // transition group 1
MRMTransitionGroupType transition_group;
setup_transition_group(transition_group);
MRMTransitionGroupPicker trgroup_picker;
Param picker_param = trgroup_picker.getDefaults();
picker_param.setValue("PeakPickerChromatogram:method", "legacy"); // old parameters
picker_param.setValue("PeakPickerChromatogram:peak_width", 40.0); // old parameters
trgroup_picker.setParameters(picker_param);
trgroup_picker.pickTransitionGroup(transition_group);
TEST_EQUAL(transition_group.getFeatures().size(), 1)
MRMFeature mrmfeature = transition_group.getFeatures()[0];
TEST_REAL_SIMILAR(mrmfeature.getRT(), 1492.83060)
TEST_REAL_SIMILAR(mrmfeature.getIntensity(), 567375)
TEST_REAL_SIMILAR(mrmfeature.getMetaValue("leftWidth"), 1481.84)
TEST_REAL_SIMILAR(mrmfeature.getMetaValue("rightWidth"), 1501.23)
// test the number of hull points (should be equal)
TEST_EQUAL( mrmfeature.getFeature("1").getConvexHulls()[0].getHullPoints().size(), 7);
TEST_EQUAL( mrmfeature.getFeature("2").getConvexHulls()[0].getHullPoints().size(), 7);
// the intensity of the hull points should not have changed
// Check Feature 2
ConvexHull2D::PointArrayType data1_points = mrmfeature.getFeature("2").getConvexHulls()[0].getHullPoints();
double sum = 0.0;
for (ConvexHull2D::PointArrayType::iterator it = data1_points.begin(); it != data1_points.end(); it++)
{
sum += it->getY();
}
TEST_REAL_SIMILAR(sum, 507385.32);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity(), 507385.32);
// Check Feature 1
ConvexHull2D::PointArrayType data2_points = mrmfeature.getFeature("1").getConvexHulls()[0].getHullPoints();
sum = 0.0;
for (ConvexHull2D::PointArrayType::iterator it = data2_points.begin(); it != data2_points.end(); it++)
{
sum += it->getY();
}
TEST_REAL_SIMILAR(sum, 59989.8287208466);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getIntensity(), 59989.8287208466);
// Also check the MS1
std::vector<String> result;
mrmfeature.getPrecursorFeatureIDs(result);
TEST_EQUAL(result.size(), 1);
TEST_EQUAL(result[0], "Precursor_i0");
data2_points = mrmfeature.getPrecursorFeature("Precursor_i0").getConvexHulls()[0].getHullPoints();
sum = 0.0;
for (ConvexHull2D::PointArrayType::iterator it = data2_points.begin(); it != data2_points.end(); it++)
{
sum += it->getY();
}
// Part of the signal gets lost due to the re-sampling since the MS1 sampling
// positions are not at the same place as the MS2 sampling positions
double resampling_loss = 875.9514;
TEST_REAL_SIMILAR(sum, 53900 - resampling_loss);
TEST_REAL_SIMILAR(mrmfeature.getPrecursorFeature("Precursor_i0").getIntensity(),
// mrmfeature.getMS1Feature().getIntensity(), 53900 - resampling_loss);
53900 - resampling_loss);
}
{ // transition group 2 (Consensus)
MRMTransitionGroupType transition_group;
setup_transition_group2(transition_group);
MRMTransitionGroupPicker trgroup_picker;
Param picker_param = trgroup_picker.getDefaults();
picker_param.setValue("resample_boundary", 1.0);
picker_param.setValue("PeakPickerChromatogram:gauss_width", 10.0);
picker_param.setValue("PeakPickerChromatogram:peak_width", -1.0);
picker_param.setValue("PeakPickerChromatogram:signal_to_noise", 1.0);
picker_param.setValue("PeakPickerChromatogram:method", "corrected");
picker_param.setValue("use_consensus", "true");
trgroup_picker.setParameters(picker_param);
trgroup_picker.pickTransitionGroup(transition_group);
TEST_EQUAL(transition_group.getFeatures().size(), 1);
MRMFeature mrmfeature = transition_group.getFeatures()[0];
TEST_REAL_SIMILAR(mrmfeature.getRT(), 14);
TEST_REAL_SIMILAR(mrmfeature.getMetaValue("leftWidth"), 7);
TEST_REAL_SIMILAR(mrmfeature.getMetaValue("rightWidth"), 21);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getIntensity(), 140);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity(), 117);
TEST_REAL_SIMILAR(mrmfeature.getFeature("3").getIntensity(), 45);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getMetaValue("peak_apex_int"), 16);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getMetaValue("peak_apex_int"), 11);
TEST_REAL_SIMILAR(mrmfeature.getFeature("3").getMetaValue("peak_apex_int"), 3);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getMetaValue("peak_apex_position"), 14);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getMetaValue("peak_apex_position"), 7);
TEST_REAL_SIMILAR(mrmfeature.getFeature("3").getMetaValue("peak_apex_position"), 7);
}
{ // transition group 2 (no consensus)
MRMTransitionGroupType transition_group;
setup_transition_group2(transition_group);
MRMTransitionGroupPicker trgroup_picker;
Param picker_param = trgroup_picker.getDefaults();
picker_param.setValue("resample_boundary", 1.0);
picker_param.setValue("PeakPickerChromatogram:gauss_width", 10.0);
picker_param.setValue("PeakPickerChromatogram:peak_width", -1.0);
picker_param.setValue("PeakPickerChromatogram:signal_to_noise", 1.0);
picker_param.setValue("PeakPickerChromatogram:method", "corrected");
picker_param.setValue("use_consensus", "false");
trgroup_picker.setParameters(picker_param);
trgroup_picker.pickTransitionGroup(transition_group);
TEST_EQUAL(transition_group.getFeatures().size(), 2);
MRMFeature mrmfeature = transition_group.getFeatures()[0];
TEST_REAL_SIMILAR(mrmfeature.getRT(), 14);
TEST_REAL_SIMILAR(mrmfeature.getMetaValue("leftWidth"), 7);
TEST_REAL_SIMILAR(mrmfeature.getMetaValue("rightWidth"), 21);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getIntensity(), 140);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity(), 58); // consensus = 117
TEST_REAL_SIMILAR(mrmfeature.getFeature("3").getIntensity(), 45);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getMetaValue("peak_apex_int"), 16);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getMetaValue("peak_apex_int"), 11);
TEST_REAL_SIMILAR(mrmfeature.getFeature("3").getMetaValue("peak_apex_int"), 3);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getMetaValue("peak_apex_position"), 14);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getMetaValue("peak_apex_position"), 16); // consensus = 7
TEST_REAL_SIMILAR(mrmfeature.getFeature("3").getMetaValue("peak_apex_position"), 7);
}
{ // transition group 1 -- only quantifying
MRMTransitionGroupPicker trgroup_picker;
Param picker_param = trgroup_picker.getDefaults();
picker_param.setValue("PeakPickerChromatogram:method", "legacy"); // old parameters
picker_param.setValue("PeakPickerChromatogram:peak_width", 40.0); // old parameters
trgroup_picker.setParameters(picker_param);
{
MRMTransitionGroupType transition_group;
setup_transition_group(transition_group);
trgroup_picker.pickTransitionGroup(transition_group);
TEST_EQUAL(transition_group.getFeatures().size(), 1)
MRMFeature mrmfeature = transition_group.getFeatures()[0];
TEST_REAL_SIMILAR(mrmfeature.getIntensity(), 567375)
TEST_REAL_SIMILAR(mrmfeature.getRT(), 1492.83060);
}
{
MRMTransitionGroupType transition_group;
setup_transition_group(transition_group);
transition_group.getTransitionsMuteable()[0].setQuantifyingTransition(false);
trgroup_picker.pickTransitionGroup(transition_group);
TEST_EQUAL(transition_group.getFeatures().size(), 1)
MRMFeature mrmfeature = transition_group.getFeatures()[0];
TEST_REAL_SIMILAR(mrmfeature.getIntensity(), 507385)
TEST_REAL_SIMILAR(mrmfeature.getRT(), 1492.83060);
}
{
MRMTransitionGroupType transition_group;
setup_transition_group(transition_group);
transition_group.getTransitionsMuteable()[1].setQuantifyingTransition(false);
trgroup_picker.pickTransitionGroup(transition_group);
TEST_EQUAL(transition_group.getFeatures().size(), 1)
MRMFeature mrmfeature = transition_group.getFeatures()[0];
TEST_REAL_SIMILAR(mrmfeature.getIntensity(), 59989.8)
TEST_REAL_SIMILAR(mrmfeature.getRT(), 1492.83060);
}
{
MRMTransitionGroupType transition_group;
setup_transition_group(transition_group);
transition_group.getTransitionsMuteable()[0].setQuantifyingTransition(false);
transition_group.getTransitionsMuteable()[1].setQuantifyingTransition(false);
trgroup_picker.pickTransitionGroup(transition_group);
TEST_EQUAL(transition_group.getFeatures().size(), 0) // no results, since zero intensity transitions get removed
}
}
{ // transition group 1 -- only detecting
MRMTransitionGroupPicker trgroup_picker;
Param picker_param = trgroup_picker.getDefaults();
picker_param.setValue("resample_boundary", 1.0);
picker_param.setValue("PeakPickerChromatogram:gauss_width", 10.0);
picker_param.setValue("PeakPickerChromatogram:peak_width", -1.0);
picker_param.setValue("PeakPickerChromatogram:signal_to_noise", 1.0);
picker_param.setValue("PeakPickerChromatogram:method", "corrected");
picker_param.setValue("use_consensus", "false");
trgroup_picker.setParameters(picker_param);
{
MRMTransitionGroupType transition_group;
setup_transition_group2(transition_group);
trgroup_picker.pickTransitionGroup(transition_group);
TEST_EQUAL(transition_group.getFeatures().size(), 2);
MRMFeature mrmfeature = transition_group.getFeatures()[0];
TEST_REAL_SIMILAR(mrmfeature.getIntensity(), 243)
TEST_REAL_SIMILAR(mrmfeature.getRT(), 14.0);
TEST_REAL_SIMILAR(mrmfeature.getRT(), 14);
TEST_REAL_SIMILAR(mrmfeature.getMetaValue("leftWidth"), 7);
TEST_REAL_SIMILAR(mrmfeature.getMetaValue("rightWidth"), 21);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getIntensity(), 140);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity(), 58); // consensus = 117
TEST_REAL_SIMILAR(mrmfeature.getFeature("3").getIntensity(), 45);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getMetaValue("peak_apex_int"), 16);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getMetaValue("peak_apex_int"), 11);
TEST_REAL_SIMILAR(mrmfeature.getFeature("3").getMetaValue("peak_apex_int"), 3);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getMetaValue("peak_apex_position"), 14);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getMetaValue("peak_apex_position"), 16); // consensus = 7
TEST_REAL_SIMILAR(mrmfeature.getFeature("3").getMetaValue("peak_apex_position"), 7);
}
{
// cannot have non-consensus data where we wont use all transitions
MRMTransitionGroupType transition_group;
setup_transition_group2(transition_group);
transition_group.getTransitionsMuteable()[0].setDetectingTransition(false);
TEST_EXCEPTION(Exception::IllegalArgument, trgroup_picker.pickTransitionGroup(transition_group))
TEST_EQUAL(transition_group.getFeatures().size(), 0)
}
}
}
END_SECTION
START_SECTION((template <typename SpectrumT, typename TransitionT> MRMFeature createMRMFeature(MRMTransitionGroup<SpectrumT, TransitionT>& transition_group, std::vector<SpectrumT>& picked_chroms, std::vector<SpectrumT>& smoothed_chroms, int& chr_idx, int& peak_idx)))
{
MRMTransitionGroupType transition_group;
setup_transition_group(transition_group);
std::vector< RichPeakChromatogram > picked_chroms;
std::vector< RichPeakChromatogram > smoothed_chroms;
double left_start = 1481.840;
double right_end = 1512.290;
// do "peakpicking", create one peak
for(Size k = 0; k < transition_group.getChromatograms().size(); k++)
{
RichPeakChromatogram picked_chrom;
ChromatogramPeak peak;
peak.setRT(1490);
peak.setIntensity(170);
picked_chrom.push_back(peak);
picked_chrom.getFloatDataArrays().clear();
picked_chrom.getFloatDataArrays().resize(PeakPickerChromatogram::SIZE_OF_FLOATINDICES);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE].setName("IntegratedIntensity");
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].setName("leftWidth");
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].setName("rightWidth");
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE].push_back(1000.0);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(left_start);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(right_end);
picked_chrom.setNativeID(transition_group.getChromatograms()[k].getNativeID());
picked_chroms.push_back(picked_chrom);
}
// create the corresponding first mrm feature
int chr_idx = 1, peak_idx = 0;
{
MRMTransitionGroupPicker picker;
Param picker_param = picker.getDefaults();
picker_param.setValue("PeakPickerChromatogram::method", "legacy"); // old parameters
picker_param.setValue("PeakPickerChromatogram::peak_width", 40.0); // old parameters
picker.setParameters(picker_param);
MRMFeature mrmfeature = picker.createMRMFeature(transition_group, picked_chroms, smoothed_chroms, chr_idx, peak_idx);
TEST_REAL_SIMILAR(mrmfeature.getRT(), 1490.0)
// test the number of hull points (should be equal)
TEST_EQUAL( mrmfeature.getFeature("1").getConvexHulls()[0].getHullPoints().size(), 12);
TEST_EQUAL( mrmfeature.getFeature("2").getConvexHulls()[0].getHullPoints().size(), 12);
// the intensity of the hull points should not have changed
ConvexHull2D::PointArrayType data1_points = mrmfeature.getFeature("2").getConvexHulls()[0].getHullPoints();
double sum = 0.0;
for (ConvexHull2D::PointArrayType::iterator it = data1_points.begin(); it != data1_points.end(); it++)
{
sum += it->getY();
}
TEST_REAL_SIMILAR(sum, 535801.503);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity(), 535801.503);
TEST_REAL_SIMILAR((double)mrmfeature.getFeature("2").getMetaValue("peak_apex_int"), 157694);
ConvexHull2D::PointArrayType data2_points = mrmfeature.getFeature("1").getConvexHulls()[0].getHullPoints();
sum = 0.0;
for (ConvexHull2D::PointArrayType::iterator it = data2_points.begin(); it != data2_points.end(); it++)
{
sum += it->getY();
}
TEST_REAL_SIMILAR(sum, 61405.95106);
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getIntensity(), 61405.95106);
TEST_REAL_SIMILAR((double)mrmfeature.getFeature("1").getMetaValue("peak_apex_int"), 30286.9130513267);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity()/mrmfeature.getFeature("1").getIntensity(), 8.72556) // ratio should be stable
// feature dimension
TEST_EQUAL(mrmfeature.getRT(), 1490.0)
TEST_REAL_SIMILAR( mrmfeature.getMetaValue("leftWidth"), left_start);
TEST_REAL_SIMILAR( mrmfeature.getMetaValue("rightWidth"), right_end);
}
{
MRMTransitionGroupPicker picker;
Param picker_param = picker.getDefaults();
picker_param.setValue("PeakPickerChromatogram::method", "legacy"); // old parameters
picker_param.setValue("PeakPickerChromatogram::peak_width", 40.0); // old parameters
picker_param.setValue("background_subtraction", "original");
picker.setParameters(picker_param);
MRMFeature mrmfeature = picker.createMRMFeature(transition_group, picked_chroms, smoothed_chroms, chr_idx, peak_idx);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity(), 514583); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR((double)mrmfeature.getFeature("2").getMetaValue("peak_apex_int"), 155925.8085); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getIntensity(), 60913.8); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR((double)mrmfeature.getFeature("2").getMetaValue("peak_apex_int"), 155925.8085); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity()/mrmfeature.getFeature("1").getIntensity(), 8.44773) // ratio should be stable
}
// integration with Simpon's rule (with background subtraction)
{
MRMTransitionGroupPicker picker;
Param picker_param = picker.getDefaults();
picker_param.setValue("PeakPickerChromatogram::method", "legacy"); // old parameters
picker_param.setValue("PeakPickerChromatogram::peak_width", 40.0); // old parameters
picker_param.setValue("background_subtraction", "exact");
picker_param.setValue("PeakIntegrator:integration_type", "simpson");
picker.setParameters(picker_param);
MRMFeature mrmfeature = picker.createMRMFeature(transition_group, picked_chroms, smoothed_chroms, chr_idx, peak_idx);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity(), 1.42194e+06); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR((double)mrmfeature.getFeature("2").getMetaValue("peak_apex_int"), 155331.37806798); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getIntensity(), 168685); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR((double)mrmfeature.getFeature("1").getMetaValue("peak_apex_int"), 30251.2414481247); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity()/mrmfeature.getFeature("1").getIntensity(), 8.42957) // ratio should be stable
}
// background subtraction with peak integrator
{
MRMTransitionGroupPicker picker;
Param picker_param = picker.getDefaults();
picker_param.setValue("PeakPickerChromatogram::method", "legacy"); // old parameters
picker_param.setValue("PeakPickerChromatogram::peak_width", 40.0); // old parameters
picker_param.setValue("background_subtraction", "exact");
picker.setParameters(picker_param);
MRMFeature mrmfeature = picker.createMRMFeature(transition_group, picked_chroms, smoothed_chroms, chr_idx, peak_idx);
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity(), 514590); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR((double)mrmfeature.getFeature("2").getMetaValue("peak_apex_int"), 155331.37806798); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR(mrmfeature.getFeature("1").getIntensity(), 61009.7); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR((double)mrmfeature.getFeature("1").getMetaValue("peak_apex_int"), 30251.2414481247); // slightly reduced value due to background subtraction
TEST_REAL_SIMILAR(mrmfeature.getFeature("2").getIntensity()/mrmfeature.getFeature("1").getIntensity(), 8.43456040596823) // ratio should be stable
}
}
END_SECTION
///////////////////////////////////////////////////////////////////////////
/// Private methods
///////////////////////////////////////////////////////////////////////////
START_SECTION(( void findLargestPeak(std::vector<RichPeakChromatogram> & picked_chroms, int & chr_idx, int & peak_idx) ))
{
MRMTransitionGroupType transition_group;
std::vector< RichPeakChromatogram > picked_chroms;
// do peakpicking, e.g. find a peak at 3120 RT / 170 intensity in all the spectra
for(Size k = 0; k < 3; k++)
{
RichPeakChromatogram picked_chrom;
ChromatogramPeak peak;
peak.setRT(3120);
peak.setIntensity(100+k);
picked_chrom.push_back(peak);
peak.setRT(4120);
peak.setIntensity(200+k);
picked_chrom.push_back(peak);
picked_chrom.getFloatDataArrays().clear();
picked_chrom.getFloatDataArrays().resize(PeakPickerChromatogram::SIZE_OF_FLOATINDICES);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE].setName("IntegratedIntensity");
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].setName("leftWidth");
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].setName("rightWidth");
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE].push_back(1000.0);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(3100.0);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(3140.0);
picked_chroms.push_back(picked_chrom);
}
MRMTransitionGroupPicker picker;
int chr_idx = -1, peak_idx = -1;
picker.findLargestPeak(picked_chroms, chr_idx, peak_idx);
TEST_EQUAL(chr_idx, 2);
TEST_EQUAL(peak_idx, 1);
}
END_SECTION
START_SECTION(void findWidestPeakIndices(const std::vector<MSChromatogram>& picked_chroms, Int& chrom_idx, Int& point_idx) const)
{
std::vector<MSChromatogram> chromatograms;
MSChromatogram c;
c.push_back(ChromatogramPeak(110.0, 2000.0));
c.push_back(ChromatogramPeak(150.0, 6000.0));
c.push_back(ChromatogramPeak(190.0, 2000.0));
c.getFloatDataArrays().resize(PeakPickerChromatogram::SIZE_OF_FLOATINDICES);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(100.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(120.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(120.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(180.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(180.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(200.0);
chromatograms.push_back(c); // chromatogram containing a peak of highest intensity (should be skipped in favor of widest peak)
c.clear(true);
c.push_back(ChromatogramPeak(150.0, 5500.0)); // lower global intensity, if compared to the previous chromatogram
c.push_back(ChromatogramPeak(190.0, 2000.0));
c.getFloatDataArrays().resize(PeakPickerChromatogram::SIZE_OF_FLOATINDICES);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(100.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(180.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(180.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(200.0);
chromatograms.push_back(c); // chromatogram containing the widest peak (this should be chosen)
c.clear(true);
c.push_back(ChromatogramPeak(110.0, 2000.0));
c.push_back(ChromatogramPeak(150.0, 7000.0));
c.push_back(ChromatogramPeak(190.0, 2000.0));
c.getFloatDataArrays().resize(PeakPickerChromatogram::SIZE_OF_FLOATINDICES);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(105.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(115.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(125.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(175.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(185.0);
c.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(195.0);
chromatograms.push_back(c); // just another chromatogram (it won't be chosen, it contains short peaks)
MRMTransitionGroupPicker picker;
Int chr_idx{-1}, peak_idx{-1};
picker.findWidestPeakIndices(chromatograms, chr_idx, peak_idx);
TEST_EQUAL(chr_idx, 1);
TEST_EQUAL(peak_idx, 0); // the point [0] (first) is the apex of the widest peak within the chosen chromatogram
TEST_REAL_SIMILAR(chromatograms[chr_idx][peak_idx].getRT(), 150.0)
TEST_REAL_SIMILAR(chromatograms[chr_idx][peak_idx].getIntensity(), 5500.0)
TEST_REAL_SIMILAR(chromatograms[chr_idx].getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][peak_idx], 100.0)
TEST_REAL_SIMILAR(chromatograms[chr_idx].getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][peak_idx], 180.0)
}
END_SECTION
START_SECTION((template < typename SpectrumT > void remove_overlapping_features(std::vector< SpectrumT > &picked_chroms, double best_left, double best_right)))
{
MRMTransitionGroupType transition_group;
std::vector< RichPeakChromatogram > picked_chroms;
MRMTransitionGroupPicker picker;
double default_intensity = 170;
// create 3 peaks, at 3120, 3090 and 3060 which are all overlapping
{
RichPeakChromatogram picked_chrom;
picked_chrom.getFloatDataArrays().clear();
picked_chrom.getFloatDataArrays().resize(PeakPickerChromatogram::SIZE_OF_FLOATINDICES);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].setName("leftWidth");
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].setName("rightWidth");
{
ChromatogramPeak peak;
peak.setRT(3120);
peak.setIntensity(default_intensity);
picked_chrom.push_back(peak);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(3100.0);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(3140.0);
}
{
ChromatogramPeak peak;
peak.setRT(3090);
peak.setIntensity(default_intensity);
picked_chrom.push_back(peak);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(3070.0);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(3120.0);
}
{
ChromatogramPeak peak;
peak.setRT(3060);
peak.setIntensity(default_intensity);
picked_chrom.push_back(peak);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(3050.0);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(3090.0);
}
picked_chroms.push_back(picked_chrom);
}
// create 2 peaks, at 3120 and 3060 which are not overlapping
{
RichPeakChromatogram picked_chrom;
picked_chrom.getFloatDataArrays().clear();
picked_chrom.getFloatDataArrays().resize(PeakPickerChromatogram::SIZE_OF_FLOATINDICES);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].setName("leftWidth");
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].setName("rightWidth");
{
ChromatogramPeak peak;
peak.setRT(3120);
peak.setIntensity(default_intensity);
picked_chrom.push_back(peak);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(3100.0);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(3140.0);
}
{
ChromatogramPeak peak;
peak.setRT(3060);
peak.setIntensity(default_intensity);
picked_chrom.push_back(peak);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER].push_back(3050.0);
picked_chrom.getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER].push_back(3090.0);
}
picked_chroms.push_back(picked_chrom);
}
std::vector< RichPeakChromatogram > picked_chroms_orig = picked_chroms;
// First we look at the rightmost peak which should include the first two
// peaks in the first chromatogram and the first peak in the second
//chromatogram
double best_left = 3100; double best_right = 3140;
picked_chroms = picked_chroms_orig;
picker.remove_overlapping_features(picked_chroms, best_left, best_right);
TEST_REAL_SIMILAR(picked_chroms[0][0].getIntensity(), 0.0)
TEST_REAL_SIMILAR(picked_chroms[0][1].getIntensity(), 0.0)
TEST_REAL_SIMILAR(picked_chroms[0][2].getIntensity(), default_intensity)
TEST_REAL_SIMILAR(picked_chroms[1][0].getIntensity(), 0.0)
TEST_REAL_SIMILAR(picked_chroms[1][1].getIntensity(), default_intensity)
// Second we look at the middle peak which should include all peaks
best_left = 3070; best_right = 3120;
picked_chroms = picked_chroms_orig;
picker.remove_overlapping_features(picked_chroms, best_left, best_right);
TEST_REAL_SIMILAR(picked_chroms[0][0].getIntensity(), 0.0)
TEST_REAL_SIMILAR(picked_chroms[0][1].getIntensity(), 0.0)
TEST_REAL_SIMILAR(picked_chroms[0][2].getIntensity(), 0.0);
TEST_REAL_SIMILAR(picked_chroms[1][0].getIntensity(), 0.0)
TEST_REAL_SIMILAR(picked_chroms[1][1].getIntensity(), 0.0);
// Last we look at the leftmost peak which should include all peaks
best_left = 3050; best_right = 3090;
picked_chroms = picked_chroms_orig;
picker.remove_overlapping_features(picked_chroms, best_left, best_right);
TEST_REAL_SIMILAR(picked_chroms[0][0].getIntensity(), default_intensity)
TEST_REAL_SIMILAR(picked_chroms[0][1].getIntensity(), 0.0)
TEST_REAL_SIMILAR(picked_chroms[0][2].getIntensity(), 0.0);
TEST_REAL_SIMILAR(picked_chroms[1][0].getIntensity(), default_intensity)
TEST_REAL_SIMILAR(picked_chroms[1][1].getIntensity(), 0.0);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/NNLS_test.cpp | .cpp | 1,862 | 80 | // 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/ML/NNLS/NNLS.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(NNLS, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/*NNLS* ptr = 0;
NNLS* null_ptr = 0;
START_SECTION(NNLS())
{
ptr = new NNLS();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~NNLS())
{
delete ptr;
}
END_SECTION
*/
START_SECTION([EXTRA]int nnls_(double *a, integer *mda, integer *m, integer *n, double *b, double *x, double *rnorm, double *w, double *zz, integer *index, integer *mode))
// translate A to array a (column major order)
double a_vec[4]= {1, 0, 0, 1};
int a_rows = 2;
int a_cols = 2;
// translate b
double b_vec[2] = {2, 3};
// prepare solution array (directly copied from example)
double *x_vec = new double[2+1];
double rnorm;
double *w = new double[2+1];
double *zz = new double[2+1];
int *indx = new int[2+1];
int mode;
NNLS::nnls_(a_vec, &a_rows, &a_rows, &a_cols, b_vec, x_vec, &rnorm, w, zz, indx, &mode);
TEST_EQUAL(mode, 1)
double x_solution[2] = {2, 3};
for (Size i=0; i<2; ++i)
{
TEST_EQUAL(x_vec[i], x_solution[i])
}
delete[] x_vec;
delete[] w;
delete[] zz;
delete[] indx;
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/LowessSmoothing_test.cpp | .cpp | 2,628 | 113 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Erhan Kenar, Holger Franken $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/PROCESSING/SMOOTHING/LowessSmoothing.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/normal_distribution.hpp>
///////////////////////////
using namespace OpenMS;
using namespace std;
double targetFunction(double x)
{
return 10 + 20*x + 40*x*x;
}
START_TEST(LowessSmoothing, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
LowessSmoothing* ptr = nullptr;
LowessSmoothing* null_ptr = nullptr;
START_SECTION(LowessSmoothing())
{
ptr = new LowessSmoothing();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~LowessSmoothing())
{
delete ptr;
}
END_SECTION
/////
std::vector<double> x, y, y_noisy, out;
//exact data
for (double i = 1.0; i <= 20.0; i += 1.0)
{
x.push_back(i);
y.push_back(targetFunction(i));
}
//noisy data
// make some noise
boost::random::mt19937 rnd_gen_;
for (Size i = 0; i < y.size(); ++i)
{
boost::normal_distribution<float> udist (y.at(i), 0.05);
y_noisy.push_back( udist(rnd_gen_) );
}
LowessSmoothing lowsmooth;
Param lowpar;
lowpar.setValue("window_size", 15);
TOLERANCE_RELATIVE(1.0004);
TOLERANCE_ABSOLUTE(0.07);
START_SECTION(void smoothData(const DoubleVector&, const DoubleVector&, DoubleVector&))
{
y.push_back(-1.0);
TEST_EXCEPTION(Exception::InvalidValue, lowsmooth.smoothData(x, y, out));
y.pop_back();
out.clear();
lowsmooth.smoothData(x, y, out);
Size idx = 1;
for (Size i = 0; i < out.size(); ++i, ++idx)
{
TEST_REAL_SIMILAR(out[i], targetFunction(idx));
}
out.clear();
lowsmooth.setParameters(lowpar);
lowsmooth.smoothData(x, y, out);
idx = 1;
for (Size i = 0; i < out.size(); ++i, ++idx)
{
TEST_REAL_SIMILAR(out[i], targetFunction(idx));
}
out.clear();
lowsmooth.smoothData(x, y_noisy, out);
idx = 1;
for (Size i = 0; i < out.size(); ++i, ++idx)
{
TEST_REAL_SIMILAR(out[i], targetFunction(idx));
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MultiplexSatelliteCentroided_test.cpp | .cpp | 1,190 | 40 | // 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/MultiplexSatelliteCentroided.h>
using namespace OpenMS;
START_TEST(MultiplexSatelliteCentroided, "$Id$")
MultiplexSatelliteCentroided* nullPointer = nullptr;
MultiplexSatelliteCentroided* ptr;
START_SECTION(MultiplexSatelliteCentroided(size_t rt_idx, size_t mz_idx))
MultiplexSatelliteCentroided satellite(4, 7);
TEST_EQUAL(satellite.getMZidx(), 7);
ptr = new MultiplexSatelliteCentroided(4, 7);
TEST_NOT_EQUAL(ptr, nullPointer);
delete ptr;
END_SECTION
START_SECTION(size_t getMZidx())
MultiplexSatelliteCentroided satellite(4, 7);
TEST_EQUAL(satellite.getMZidx(), 7);
END_SECTION
START_SECTION(size_t getRTidx())
MultiplexSatelliteCentroided satellite(4, 7);
TEST_EQUAL(satellite.getRTidx(), 4);
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IsobaricChannelExtractor_test.cpp | .cpp | 24,297 | 733 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Stephan Aiche, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/QUANTITATION/IsobaricChannelExtractor.h>
///////////////////////////
#include <OpenMS/ANALYSIS/QUANTITATION/ItraqFourPlexQuantitationMethod.h>
#include <OpenMS/ANALYSIS/QUANTITATION/TMTTenPlexQuantitationMethod.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/FORMAT/MzDataFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
using namespace OpenMS;
using namespace std;
START_TEST(IsobaricChannelExtractor, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IsobaricChannelExtractor * ptr = nullptr;
IsobaricChannelExtractor* null_ptr = nullptr;
IsobaricQuantitationMethod* q_method = new ItraqFourPlexQuantitationMethod();
START_SECTION((IsobaricChannelExtractor(const IsobaricQuantitationMethod * const quant_method)))
{
ptr = new IsobaricChannelExtractor(q_method);
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IsobaricChannelExtractor())
{
delete ptr;
}
END_SECTION
START_SECTION((IsobaricChannelExtractor(const IsobaricChannelExtractor &other)))
{
IsobaricChannelExtractor ice(q_method);
Param p = ice.getParameters();
p.setValue("select_activation", "any");
ice.setParameters(p);
IsobaricChannelExtractor ice2(ice);
TEST_EQUAL(ice2.getParameters(), p)
}
END_SECTION
START_SECTION((IsobaricChannelExtractor& operator=(const IsobaricChannelExtractor& rhs)))
{
IsobaricChannelExtractor ice(q_method);
Param p = ice.getParameters();
p.setValue("reporter_mass_shift", 0.3);
ice.setParameters(p);
IsobaricChannelExtractor ice2(q_method);
ice2 = ice;
TEST_EQUAL(ice2.getParameters(), p)
}
END_SECTION
START_SECTION((void extractChannels(const PeakMap&ms_exp_data, ConsensusMap & consensus_map)))
{
{
// load test data
PeakMap exp;
MzMLFile mzmlfile;
mzmlfile.load(OPENMS_GET_TEST_DATA_PATH("IsobaricChannelExtractor_6.mzML"), exp);
// add some more information to the quant method
Param pItraq = q_method->getParameters();
pItraq.setValue("channel_114_description", "ref");
pItraq.setValue("channel_115_description", "something");
pItraq.setValue("channel_116_description", "else");
q_method->setParameters(pItraq);
IsobaricChannelExtractor ice(q_method);
// disable activation filtering
Param p = ice.getParameters();
p.setValue("select_activation", "any");
ice.setParameters(p);
// extract channels
ConsensusMap cm_out;
ice.extractChannels(exp, cm_out);
// check channel meta information
TEST_EQUAL(cm_out.getColumnHeaders().size(), 4)
ABORT_IF(cm_out.getColumnHeaders().size() != 4)
TEST_EQUAL(cm_out.getColumnHeaders()[0].label, "itraq4plex_114")
TEST_EQUAL(cm_out.getColumnHeaders()[0].getMetaValue("channel_name"), "114")
TEST_EQUAL(cm_out.getColumnHeaders()[0].getMetaValue("channel_id"), 0)
TEST_EQUAL(cm_out.getColumnHeaders()[0].getMetaValue("channel_description"), "ref")
TEST_EQUAL(cm_out.getColumnHeaders()[0].getMetaValue("channel_center"), 114.1112)
TEST_EQUAL(cm_out.getColumnHeaders()[1].label, "itraq4plex_115")
TEST_EQUAL(cm_out.getColumnHeaders()[1].getMetaValue("channel_name"), "115")
TEST_EQUAL(cm_out.getColumnHeaders()[1].getMetaValue("channel_id"), 1)
TEST_EQUAL(cm_out.getColumnHeaders()[1].getMetaValue("channel_description"), "something")
TEST_EQUAL(cm_out.getColumnHeaders()[1].getMetaValue("channel_center"), 115.1082)
TEST_EQUAL(cm_out.getColumnHeaders()[2].label, "itraq4plex_116")
TEST_EQUAL(cm_out.getColumnHeaders()[2].getMetaValue("channel_name"), "116")
TEST_EQUAL(cm_out.getColumnHeaders()[2].getMetaValue("channel_id"), 2)
TEST_EQUAL(cm_out.getColumnHeaders()[2].getMetaValue("channel_description"), "else")
TEST_EQUAL(cm_out.getColumnHeaders()[2].getMetaValue("channel_center"), 116.1116)
TEST_EQUAL(cm_out.getColumnHeaders()[3].label, "itraq4plex_117")
TEST_EQUAL(cm_out.getColumnHeaders()[3].getMetaValue("channel_name"), "117")
TEST_EQUAL(cm_out.getColumnHeaders()[3].getMetaValue("channel_id"), 3)
TEST_EQUAL(cm_out.getColumnHeaders()[3].getMetaValue("channel_description"), "")
TEST_EQUAL(cm_out.getColumnHeaders()[3].getMetaValue("channel_center"), 117.1149)
// compare results
TEST_EQUAL(cm_out.size(), 5)
ABORT_IF(cm_out.size() != 5)
ConsensusFeature::iterator cf_it;
TEST_EQUAL(cm_out[0].size(), 4)
TEST_EQUAL(cm_out[0].getMetaValue("scan_id"), "controllerType=0 controllerNumber=1 scan=2")
TEST_REAL_SIMILAR(cm_out[0].getMetaValue("precursor_intensity"), 5251952.5)
TEST_EQUAL(cm_out[0].getCharge(), 2)
TEST_REAL_SIMILAR(cm_out[0].getIntensity(), 1490501.21)
cf_it = cm_out[0].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 643005.56)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 458708.97)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 182238.38)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 206543.3)
++cf_it;
ABORT_IF(cf_it != cm_out[0].end())
TEST_EQUAL(cm_out[1].size(), 4)
TEST_EQUAL(cm_out[1].getMetaValue("scan_id"), "controllerType=0 controllerNumber=1 scan=4")
TEST_REAL_SIMILAR(cm_out[1].getMetaValue("precursor_intensity"), 7365030)
TEST_EQUAL(cm_out[1].getCharge(), 3)
TEST_REAL_SIMILAR(cm_out[1].getIntensity(), 2329603)
cf_it = cm_out[1].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 847251)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 861806)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 311899)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 308647)
++cf_it;
ABORT_IF(cf_it != cm_out[1].end())
TEST_EQUAL(cm_out[2].size(), 4)
TEST_EQUAL(cm_out[2].getMetaValue("scan_id"), "controllerType=0 controllerNumber=1 scan=6")
TEST_REAL_SIMILAR(cm_out[2].getMetaValue("precursor_intensity"), 6835636)
TEST_EQUAL(cm_out[2].getCharge(), 3)
TEST_REAL_SIMILAR(cm_out[2].getIntensity(), 2520967)
cf_it = cm_out[2].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 894414)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 958965)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 326443)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 341145)
++cf_it;
ABORT_IF(cf_it != cm_out[2].end())
TEST_EQUAL(cm_out[3].size(), 4)
TEST_EQUAL(cm_out[3].getMetaValue("scan_id"), "controllerType=0 controllerNumber=1 scan=8")
TEST_REAL_SIMILAR(cm_out[3].getMetaValue("precursor_intensity"), 6762358)
TEST_EQUAL(cm_out[3].getCharge(), 3)
TEST_REAL_SIMILAR(cm_out[3].getIntensity(), 1585286)
cf_it = cm_out[3].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 581601)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 623851)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 191352)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 188482)
++cf_it;
ABORT_IF(cf_it != cm_out[3].end())
TEST_EQUAL(cm_out[4].size(), 4)
TEST_EQUAL(cm_out[4].getMetaValue("scan_id"), "controllerType=0 controllerNumber=1 scan=10")
TEST_REAL_SIMILAR(cm_out[4].getMetaValue("precursor_intensity"), 5464634.5)
TEST_EQUAL(cm_out[4].getCharge(), 2)
TEST_REAL_SIMILAR(cm_out[4].getIntensity(), 1746368)
cf_it = cm_out[4].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 648863)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 632090)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 229391)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 236024)
++cf_it;
ABORT_IF(cf_it != cm_out[4].end())
}
{ // test -> keep_unannotated_precursor
// load test data
PeakMap exp;
MzMLFile mzmlfile;
mzmlfile.load(OPENMS_GET_TEST_DATA_PATH("IsobaricChannelExtractor_7.mzML"), exp);
// add some more information to the quant method
Param pItraq = q_method->getParameters();
pItraq.setValue("channel_114_description", "ref");
pItraq.setValue("channel_115_description", "something");
pItraq.setValue("channel_116_description", "else");
q_method->setParameters(pItraq);
IsobaricChannelExtractor ice(q_method);
// disable activation filtering
Param p = ice.getParameters();
p.setValue("select_activation", "any");
p.setValue("keep_unannotated_precursor", "false");
ice.setParameters(p);
// extract channels
ConsensusMap cm_out;
ice.extractChannels(exp, cm_out);
TEST_EQUAL(cm_out.size(), 4)
ABORT_IF(cm_out.size() != 4)
TEST_EQUAL(((double)cm_out[0].getMetaValue("precursor_intensity")) != 0.0, true)
p.setValue("keep_unannotated_precursor", "true");
ice.setParameters(p);
ConsensusMap cm_out_w_unannotated;
ice.extractChannels(exp, cm_out_w_unannotated);
TEST_EQUAL(cm_out_w_unannotated.size(), 5)
ABORT_IF(cm_out_w_unannotated.size() != 5)
TEST_REAL_SIMILAR(cm_out_w_unannotated[0].getMetaValue("precursor_intensity"), 0.0)
}
{
// load test data
PeakMap exp;
MzMLFile mzmlfile;
mzmlfile.load(OPENMS_GET_TEST_DATA_PATH("IsobaricChannelExtractor_6.mzML"), exp);
// add some more information to the quant method
Param pItraq = q_method->getParameters();
pItraq.setValue("channel_114_description", "ref");
pItraq.setValue("channel_115_description", "something");
pItraq.setValue("channel_116_description", "else");
q_method->setParameters(pItraq);
IsobaricChannelExtractor ice(q_method);
// disable activation filtering
Param p = ice.getParameters();
p.setValue("select_activation", "any");
p.setValue("min_precursor_intensity", 5300000.0);
ice.setParameters(p);
// extract channels
ConsensusMap cm_out;
ice.extractChannels(exp, cm_out);
// compare results
TEST_EQUAL(cm_out.size(), 4)
ABORT_IF(cm_out.size() != 4)
for(ConsensusMap::Iterator cf = cm_out.begin(); cf != cm_out.end(); ++cf)
{
double prec_intensity = cf->getMetaValue("precursor_intensity");
TEST_EQUAL(prec_intensity > 5300000.0, true)
}
}
{
// load test data
PeakMap exp;
MzMLFile mzmlfile;
mzmlfile.load(OPENMS_GET_TEST_DATA_PATH("IsobaricChannelExtractor_6.mzML"), exp);
// add some more information to the quant method
Param pItraq = q_method->getParameters();
pItraq.setValue("channel_114_description", "ref");
pItraq.setValue("channel_115_description", "something");
pItraq.setValue("channel_116_description", "else");
q_method->setParameters(pItraq);
IsobaricChannelExtractor ice(q_method);
// disable activation filtering
Param p = ice.getParameters();
p.setValue("select_activation", "any");
p.setValue("min_reporter_intensity", 200000.0);
ice.setParameters(p);
// extract channels
ConsensusMap cm_out;
ConsensusFeature::iterator cf_it;
ice.extractChannels(exp, cm_out);
TEST_EQUAL(cm_out.size(), 5)
ABORT_IF(cm_out.size() != 5)
TEST_EQUAL(cm_out[0].size(), 4)
cf_it = cm_out[0].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 643005.56)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 458708.97)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0) // is 182238.38 < 200.000
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 206543.3)
++cf_it;
ABORT_IF(cf_it != cm_out[0].end())
cf_it = cm_out[1].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 847251)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 861806)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 311899)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 308647)
++cf_it;
ABORT_IF(cf_it != cm_out[1].end())
cf_it = cm_out[2].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 894414)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 958965)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 326443)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 341145)
++cf_it;
ABORT_IF(cf_it != cm_out[2].end())
cf_it = cm_out[3].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 581601)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 623851)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0) // is 191352 < 200.000
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0) // is 188482 < 200.000
++cf_it;
ABORT_IF(cf_it != cm_out[3].end())
cf_it = cm_out[4].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 648863)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 632090)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 229391)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 236024)
++cf_it;
ABORT_IF(cf_it != cm_out[4].end())
}
{
// load test data
PeakMap exp;
MzMLFile mzmlfile;
mzmlfile.load(OPENMS_GET_TEST_DATA_PATH("IsobaricChannelExtractor_6.mzML"), exp);
// add some more information to the quant method
Param pItraq = q_method->getParameters();
pItraq.setValue("channel_114_description", "ref");
pItraq.setValue("channel_115_description", "something");
pItraq.setValue("channel_116_description", "else");
q_method->setParameters(pItraq);
IsobaricChannelExtractor ice(q_method);
// disable activation filtering
Param p = ice.getParameters();
p.setValue("select_activation", "any");
p.setValue("min_reporter_intensity", 200000.0);
p.setValue("discard_low_intensity_quantifications", "true");
ice.setParameters(p);
// extract channels
ConsensusMap cm_out;
ConsensusFeature::iterator cf_it;
ice.extractChannels(exp, cm_out);
TEST_EQUAL(cm_out.size(), 3)
ABORT_IF(cm_out.size() != 3)
cf_it = cm_out[0].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 847251)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 861806)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 311899)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 308647)
++cf_it;
ABORT_IF(cf_it != cm_out[0].end())
cf_it = cm_out[1].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 894414)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 958965)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 326443)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 341145)
++cf_it;
ABORT_IF(cf_it != cm_out[1].end())
cf_it = cm_out[2].begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 648863)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 632090)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 229391)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 236024)
++cf_it;
ABORT_IF(cf_it != cm_out[2].end())
}
{
// check precursor purity computation
// - tested purities were validated manually
// - dataset contains 2 ms1 and 5 ms2 spectra
// with the purity values listed below
PeakMap exp_purity;
MzMLFile mzmlfile;
mzmlfile.load(OPENMS_GET_TEST_DATA_PATH("IsobaricChannelExtractor_6.mzML"), exp_purity);
Param pItraq = q_method->getParameters();
pItraq.setValue("channel_114_description", "ref");
pItraq.setValue("channel_115_description", "something");
pItraq.setValue("channel_116_description", "else");
q_method->setParameters(pItraq);
IsobaricChannelExtractor ice(q_method);
// disable activation filtering
Param p = ice.getParameters();
p.setValue("select_activation", "any");
ice.setParameters(p);
// extract channels
ConsensusMap cm_out;
ice.extractChannels(exp_purity, cm_out);
TEST_EQUAL(cm_out.size(), 5)
ABORT_IF(cm_out.size() != 5)
// check results
TEST_REAL_SIMILAR(cm_out[0].getMetaValue("precursor_purity"), 1.0)
TEST_REAL_SIMILAR(cm_out[1].getMetaValue("precursor_purity"), 0.692434)
TEST_REAL_SIMILAR(cm_out[2].getMetaValue("precursor_purity"), 0.824561)
TEST_REAL_SIMILAR(cm_out[3].getMetaValue("precursor_purity"), 0.731295)
TEST_REAL_SIMILAR(cm_out[4].getMetaValue("precursor_purity"), 1.0)
// now filter by purity
p.setValue("min_precursor_purity", 0.75);
ice.setParameters(p);
ConsensusMap cm_filtered;
ice.extractChannels(exp_purity, cm_filtered);
TEST_EQUAL(cm_filtered.size(), 3)
ABORT_IF(cm_filtered.size() != 3)
// check results
TEST_REAL_SIMILAR(cm_filtered[0].getMetaValue("precursor_purity"), 1.0)
TEST_REAL_SIMILAR(cm_filtered[1].getMetaValue("precursor_purity"), 0.824561)
TEST_REAL_SIMILAR(cm_filtered[2].getMetaValue("precursor_purity"), 1.0)
}
}
END_SECTION
START_SECTION(([EXTRA] purity computation without interpolation))
{
// check precursor purity computation
// - tested purities were validated manually
// - dataset contains 2 ms1 and 5 ms2 spectra
// with the purity values listed below
PeakMap exp_purity;
MzMLFile mzmlfile;
mzmlfile.load(OPENMS_GET_TEST_DATA_PATH("IsobaricChannelExtractor_6.mzML"), exp_purity);
Param pItraq = q_method->getParameters();
pItraq.setValue("channel_114_description", "ref");
pItraq.setValue("channel_115_description", "something");
pItraq.setValue("channel_116_description", "else");
q_method->setParameters(pItraq);
IsobaricChannelExtractor ice(q_method);
// disable activation filtering
Param p = ice.getParameters();
p.setValue("select_activation", "any");
p.setValue("purity_interpolation", "false");
ice.setParameters(p);
// extract channels
ConsensusMap cm_out;
ice.extractChannels(exp_purity, cm_out);
TEST_EQUAL(cm_out.size(), 5)
ABORT_IF(cm_out.size() != 5)
// check results
TEST_REAL_SIMILAR(cm_out[0].getMetaValue("precursor_purity"), 1.0)
TEST_REAL_SIMILAR(cm_out[1].getMetaValue("precursor_purity"), 0.65472)
TEST_REAL_SIMILAR(cm_out[2].getMetaValue("precursor_purity"), 0.775739)
TEST_REAL_SIMILAR(cm_out[3].getMetaValue("precursor_purity"), 0.72009)
TEST_REAL_SIMILAR(cm_out[4].getMetaValue("precursor_purity"), 1.0)
// now filter by purity
p.setValue("min_precursor_purity", 0.75);
ice.setParameters(p);
ConsensusMap cm_filtered;
ice.extractChannels(exp_purity, cm_filtered);
TEST_EQUAL(cm_filtered.size(), 3)
ABORT_IF(cm_filtered.size() != 3)
// check results
TEST_REAL_SIMILAR(cm_filtered[0].getMetaValue("precursor_purity"), 1.0)
TEST_REAL_SIMILAR(cm_filtered[1].getMetaValue("precursor_purity"), 0.775739)
TEST_REAL_SIMILAR(cm_filtered[2].getMetaValue("precursor_purity"), 1.0)
}
END_SECTION
// extra test for tmt10plex to ensure high-res extraction works
START_SECTION(([EXTRA] TMT 10plex support))
{
PeakMap tmt10plex_exp;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("IsobaricChannelExtractor_8.mzML"), tmt10plex_exp);
TMTTenPlexQuantitationMethod tmt10plex;
IsobaricChannelExtractor ice(&tmt10plex);
// disable activation filtering
Param p = ice.getParameters();
p.setValue("reporter_mass_shift", 0.003);
ice.setParameters(p);
// extract channels
ConsensusMap cm_out;
ice.extractChannels(tmt10plex_exp, cm_out);
TEST_EQUAL(cm_out.size(), 5)
ABORT_IF(cm_out.size() != 5)
ConsensusMap::iterator cm_it = cm_out.begin();
ConsensusFeature::iterator cf_it;
TEST_EQUAL(cm_it->size(), 10)
ABORT_IF(cm_it->size() != 10)
TEST_EQUAL(cm_it->getMetaValue("scan_id"), "controllerType=0 controllerNumber=1 scan=7811")
// test the extracted intensities
cf_it = cm_it->begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 7759.65)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 6637.34)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 9147.74)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 8026)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 9454.86)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 21048.8)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 27783.1)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 27442.5)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 15765.4)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 17543.5)
++cf_it;
ABORT_IF(cf_it != cm_it->end())
// next scan
++cm_it;
TEST_EQUAL(cm_it->size(), 10)
ABORT_IF(cm_it->size() != 10)
TEST_EQUAL(cm_it->getMetaValue("scan_id"), "controllerType=0 controllerNumber=1 scan=7812")
// test the extracted intensities .. acutally no reporter in this scan
cf_it = cm_it->begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
ABORT_IF(cf_it != cm_it->end())
// next scan
++cm_it;
TEST_EQUAL(cm_it->size(), 10)
ABORT_IF(cm_it->size() != 10)
TEST_EQUAL(cm_it->getMetaValue("scan_id"), "controllerType=0 controllerNumber=1 scan=7813")
// test the extracted intensities
cf_it = cm_it->begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 1888.23)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 1692.61)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 1902.28)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 1234.26)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 1961.36)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 1560.74)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 0.0)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 2308.15)
++cf_it;
ABORT_IF(cf_it != cm_it->end())
// next scan
++cm_it;
TEST_EQUAL(cm_it->size(), 10)
ABORT_IF(cm_it->size() != 10)
TEST_EQUAL(cm_it->getMetaValue("scan_id"), "controllerType=0 controllerNumber=1 scan=7814")
// test the extracted intensities
cf_it = cm_it->begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 26266.6)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 20802.2)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 36053.4)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 30815.4)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 34762.3)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 27767.8)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 45284.8)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 51015.2)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 29435.1)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 40080.7)
++cf_it;
ABORT_IF(cf_it != cm_it->end())
// next scan
++cm_it;
TEST_EQUAL(cm_it->size(), 10)
ABORT_IF(cm_it->size() != 10)
TEST_EQUAL(cm_it->getMetaValue("scan_id"), "controllerType=0 controllerNumber=1 scan=7815")
// test the extracted intensities
cf_it = cm_it->begin();
TEST_REAL_SIMILAR(cf_it->getIntensity(), 30760.9)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 17172)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 19647.1)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 24401.9)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 32279.3)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 19115.6)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 35027.3)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 34874.2)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 24060.4)
++cf_it;
TEST_REAL_SIMILAR(cf_it->getIntensity(), 30866.5)
++cf_it;
ABORT_IF(cf_it != cm_it->end())
}
END_SECTION
delete q_method;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Contaminants_test.cpp | .cpp | 9,913 | 209 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow$
// $Authors: Dominik Schmitz, Chris Bielow$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/METADATA/DataProcessing.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/QC/Contaminants.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(Contaminants, "$Id$")
FeatureMap fmap;
FeatureMap emptyFmap;
Feature f;
fmap.getProteinIdentifications().resize(1);
DigestionEnzymeProtein noenzyme("unknown_enzyme", "", set<String>(), "");
// set no digestion enzyme
fmap.getProteinIdentifications()[0].getSearchParameters().digestion_enzyme = noenzyme;
// set empty contaminants database
vector<FASTAFile::FASTAEntry> contaminantsFile;
// fill the featureMap of features with set sequence and intensity
{
PeptideIdentification id;
PeptideIdentification scnd_id;
PeptideHit hit;
PeptideHit scnd_hit;
hit.setSequence(AASequence::fromString("AAAAAAAAAAK"));
id.setHits({hit});
f.setPeptideIdentifications({id});
f.setIntensity(12.0);
fmap.push_back(f);
hit.setSequence(AASequence::fromString("R"));
id.setHits({hit});
f.setPeptideIdentifications({id});
f.setIntensity(8.0);
fmap.push_back(f);
hit.setSequence(AASequence::fromString("R"));
scnd_hit.setSequence(AASequence::fromString("QQQQQQQQQQ"));
id.setHits({hit});
scnd_id.setHits({scnd_hit});
f.setPeptideIdentifications({id, scnd_id});
f.setIntensity(10.0);
fmap.push_back(f);
hit.setSequence(AASequence::fromString("AAAAAAAAAAKR"));
id.setHits({hit});
f.setPeptideIdentifications({id});
f.setIntensity(20.0);
fmap.push_back(f);
hit.setSequence(AASequence::fromString("AAAAAAAAAAKRAAAAAAAAAAKRCCCCCCCCCCKRCCCCCCCCCC"));
id.setHits({hit});
f.setPeptideIdentifications({id});
f.setIntensity(10.0);
fmap.push_back(f);
f.setPeptideIdentifications({});
fmap.push_back(f);
}
// set the unassigned peptideidentifications
PeptideIdentificationList ids2(3);
PeptideHit hit2;
hit2.setSequence(AASequence::fromString("AAAAAAAAAAK"));
ids2[0].setHits({hit2});
hit2.setSequence(AASequence::fromString("RCCCCCCCCCCK"));
ids2[1].setHits({hit2});
hit2.setSequence(AASequence::fromString("DDDDDDDDDD"));
ids2[2].setHits({hit2});
// check the constructor
Contaminants* ptr = nullptr;
Contaminants* nullPointer = nullptr;
START_SECTION(Contaminants())
ptr = new Contaminants();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~Contaminants())
delete ptr;
END_SECTION
START_SECTION((void compute(FeatureMap& features, const std::vector<FASTAFile::FASTAEntry>& contaminants)))
{
Contaminants conts1, conts2, conts3, conts4, conts5, conts6, conts7;
// test exception when the contaminants database is empty
TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, conts1.compute(fmap, contaminantsFile), "No contaminants provided.");
// set contaminant database "contaminantsFile"
FASTAFile::FASTAEntry contaminantsProtein("test_protein", "protein consists of only Alanine or Cytosine", "AAAAAAAAAAKRAAAAAAAAAAKRCCCCCCCCCCKRCCCCCCCCCC");
contaminantsFile.push_back(contaminantsProtein);
// test exception when the proteinidentification in the FeatureMap is empty
TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, conts2.compute(emptyFmap, contaminantsFile), "No proteinidentifications in FeatureMap.");
// test exception when no digestion enzyme is given
TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, conts6.compute(fmap, contaminantsFile), "No digestion enzyme in FeatureMap detected. No computation possible.");
// tests without given missed cleavages and without given enzyme
fmap.getProteinIdentifications()[0].getSearchParameters().digestion_enzyme = *ProteaseDB::getInstance()->getEnzyme("no cleavage");
conts3.compute(fmap, contaminantsFile);
std::vector<Contaminants::ContaminantsSummary> result3 = conts3.getResults();
ABORT_IF(result3.size() != 1);
TEST_REAL_SIMILAR(result3[0].assigned_contaminants_ratio, 1 / 6.0);
TEST_REAL_SIMILAR(result3[0].assigned_contaminants_intensity_ratio, 1 / 7.0);
TEST_REAL_SIMILAR(result3[0].all_contaminants_ratio, 1 / 6.0);
TEST_EQUAL(fmap[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap[1].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap[2].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap[2].getPeptideIdentifications()[1].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap[3].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap[4].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
// set digestion enzyme to trypsin
fmap.getProteinIdentifications()[0].getSearchParameters().digestion_enzyme = *ProteaseDB::getInstance()->getEnzyme("trypsin");
conts7.compute(fmap, contaminantsFile);
std::vector<Contaminants::ContaminantsSummary> result7 = conts7.getResults();
TEST_REAL_SIMILAR(result7[0].assigned_contaminants_ratio, 3 / 6.0);
TEST_REAL_SIMILAR(result7[0].assigned_contaminants_intensity_ratio, 3 / 7.0);
TEST_REAL_SIMILAR(result7[0].all_contaminants_ratio, 3 / 6.0);
TEST_EQUAL(fmap[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap[1].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap[2].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap[2].getPeptideIdentifications()[1].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap[3].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap[4].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 0);
// fill the unassigned peptideidentifications
fmap.setUnassignedPeptideIdentifications(ids2);
// tests without given missed cleavages but with set enzyme
conts4.compute(fmap, contaminantsFile);
std::vector<Contaminants::ContaminantsSummary> result4 = conts4.getResults();
ABORT_IF(result4.size() != 1);
TEST_REAL_SIMILAR(result4[0].assigned_contaminants_ratio, 3 / 6.0);
TEST_REAL_SIMILAR(result4[0].assigned_contaminants_intensity_ratio, 3 / 7.0);
TEST_REAL_SIMILAR(result4[0].unassigned_contaminants_ratio, 1 / 3.0);
TEST_REAL_SIMILAR(result4[0].all_contaminants_ratio, 4 / 9.0);
TEST_EQUAL(fmap[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap[1].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap[2].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap[2].getPeptideIdentifications()[1].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap[3].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap[4].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap.getUnassignedPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap.getUnassignedPeptideIdentifications()[1].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap.getUnassignedPeptideIdentifications()[2].getHits()[0].getMetaValue("is_contaminant"), 0);
// set missed cleavages to 1
fmap.getProteinIdentifications()[0].getSearchParameters().missed_cleavages = 1;
// tests with set missed cleavages and set enzyme
// also checks if the empty feature count is as expected
conts5.compute(fmap, contaminantsFile);
std::vector<Contaminants::ContaminantsSummary> result5 = conts5.getResults();
ABORT_IF(result5.size() != 1);
TEST_REAL_SIMILAR(result5[0].assigned_contaminants_ratio, 4 / 6.0);
TEST_REAL_SIMILAR(result5[0].assigned_contaminants_intensity_ratio, 5 / 7.0);
TEST_REAL_SIMILAR(result5[0].unassigned_contaminants_ratio, 2 / 3.0);
TEST_REAL_SIMILAR(result5[0].all_contaminants_ratio, 6 / 9.0);
TEST_EQUAL(fmap[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap[1].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap[2].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap[2].getPeptideIdentifications()[1].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap[3].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap[4].getPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(fmap.getUnassignedPeptideIdentifications()[0].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap.getUnassignedPeptideIdentifications()[1].getHits()[0].getMetaValue("is_contaminant"), 1);
TEST_EQUAL(fmap.getUnassignedPeptideIdentifications()[2].getHits()[0].getMetaValue("is_contaminant"), 0);
TEST_EQUAL(result5[0].empty_features.first, 1);
TEST_EQUAL(result5[0].empty_features.second, 6);
}
END_SECTION
Contaminants temp;
START_SECTION(const String& getName() const override) {TEST_EQUAL(temp.getName(), "Contaminants")} END_SECTION
START_SECTION(Status requirements() const override)
{
TEST_EQUAL(temp.requirements() == (QCBase::Status(QCBase::Requires::POSTFDRFEAT) | QCBase::Requires::CONTAMINANTS), true);
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/NeedlemanWunsch_test.cpp | .cpp | 2,254 | 78 | #include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/ANALYSIS/SEQUENCE/NeedlemanWunsch.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(NeedlemanWunsch, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
NeedlemanWunsch* ptr = nullptr;
START_SECTION(NeedlemanWunsch(ScoringMatrix matrix, int penalty)())
{
ptr = new NeedlemanWunsch(NeedlemanWunsch::ScoringMatrix::PAM30MS, 5);
TEST_EQUAL(ptr == nullptr, false)
}
END_SECTION
START_SECTION(~NeedlemanWunsch())
{
delete (ptr);
}
END_SECTION
String seq1 = "IGGATLIGQLAIQQAHVHL";
String seq2 = "IGGATLIGALDQVVAQQAHVHL";
START_SECTION(double align(const String& seq1, const String& seq2))
{
NeedlemanWunsch alignment = NeedlemanWunsch(NeedlemanWunsch::ScoringMatrix::identity, 5);
TEST_EQUAL(alignment.align(seq1, seq2), 1);
TEST_EQUAL(alignment.align(seq1, seq1), 19);
TEST_EQUAL(alignment.align(seq2, seq2), 22);
}
END_SECTION
START_SECTION(void setMatrix(const ScoringMatrix& matrix))
{
NeedlemanWunsch alignment = NeedlemanWunsch(NeedlemanWunsch::ScoringMatrix::identity, 5);
alignment.setMatrix(NeedlemanWunsch::ScoringMatrix::PAM30MS);
TEST_EQUAL(alignment.align(seq1, seq2), 93);
TEST_EQUAL(alignment.align(seq1, seq1), 131);
TEST_EQUAL(alignment.align(seq2, seq2), 151);
}
END_SECTION
START_SECTION(void setMatrix(const std::string& matrix))
{
NeedlemanWunsch alignment = NeedlemanWunsch(NeedlemanWunsch::ScoringMatrix::PAM30MS, 5);
TEST_EXCEPTION(Exception::IllegalArgument, alignment.setMatrix("Identity"))
alignment.setMatrix("identity");
TEST_EQUAL(alignment.align(seq1, seq2), 1);
TEST_EQUAL(alignment.align(seq1, seq1), 19);
TEST_EQUAL(alignment.align(seq2, seq2), 22);
}
END_SECTION
START_SECTION(void setPenalty(const int penalty))
{
NeedlemanWunsch alignment = NeedlemanWunsch(NeedlemanWunsch::ScoringMatrix::PAM30MS, 5);
alignment.setPenalty(1);
TEST_EQUAL(alignment.align(seq1, seq2), 113);
TEST_EQUAL(alignment.getPenalty(), 1);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MSPFile_test.cpp | .cpp | 5,692 | 155 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/MSPFile.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(MSPFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MSPFile* ptr = nullptr;
MSPFile* nullPointer = nullptr;
START_SECTION((MSPFile()))
ptr = new MSPFile;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~MSPFile()))
delete ptr;
END_SECTION
START_SECTION(MSPFile(const MSPFile &rhs))
MSPFile f1, f2;
Param p = f1.getParameters();
p.setValue("instrument", "it");
f1.setParameters(p);
TEST_EQUAL(f1.getParameters() == f2.getParameters(), false)
MSPFile f3(f1);
TEST_EQUAL(f1.getParameters() == f3.getParameters(), true)
END_SECTION
START_SECTION(MSPFile& operator=(const MSPFile &rhs))
MSPFile f1, f2;
Param p = f1.getParameters();
p.setValue("instrument", "it");
f1.setParameters(p);
TEST_EQUAL(f1.getParameters() == f2.getParameters(), false)
f2 = f1;
TEST_EQUAL(f1.getParameters() == f2.getParameters(), true)
END_SECTION
START_SECTION(void load(const String &filename, std::vector< PeptideIdentification > &ids, PeakMap &exp))
MSPFile msp_file;
PeptideIdentificationList ids;
PeakMap exp;
msp_file.load(OPENMS_GET_TEST_DATA_PATH("MSPFile_test.msp"), ids, exp);
TEST_EQUAL(exp.size(), 7)
TEST_EQUAL(ids.size(), 7)
//test DocumentIdentifier addition
TEST_STRING_EQUAL(exp.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("MSPFile_test.msp"));
TEST_STRING_EQUAL(FileTypes::typeToName(exp.getLoadedFileType()),"msp");
TEST_STRING_EQUAL(exp[0].getNativeID(), "index=0")
TEST_STRING_EQUAL(exp[1].getNativeID(), "index=1")
TEST_STRING_EQUAL(exp[2].getNativeID(), "index=2")
TEST_STRING_EQUAL(exp[3].getNativeID(), "index=3")
TEST_STRING_EQUAL(exp[4].getNativeID(), "index=4")
TEST_STRING_EQUAL(exp[5].getNativeID(), "index=5")
TEST_STRING_EQUAL(exp[6].getNativeID(), "index=6")
TEST_STRING_EQUAL(ids[5].getHits()[0].getSequence().toString(), ".(Acetyl)AAAAAAGAGPEM(Oxidation)VR")
TEST_STRING_EQUAL( ids[5].getHits()[0].getPeakAnnotations()[0].annotation, "a3")
TEST_STRING_EQUAL( ids[5].getHits()[0].getPeakAnnotations()[1].annotation, "b3")
TEST_EQUAL( ids[5].getHits()[0].getPeakAnnotations()[1].charge, 1)
// next only with parse_firstonly = false
//TEST_STRING_EQUAL( ids[5].getHits()[0].getPeakAnnotations()[2].annotation, "y2-H2O")
//TEST_EQUAL( ids[5].getHits()[0].getPeakAnnotations()[2].charge, 1)
TEST_STRING_EQUAL( ids[5].getHits()[0].getPeakAnnotations()[2].annotation, "?")
TEST_EQUAL( ids[5].getHits()[0].getPeakAnnotations()[2].charge, 0)
TEST_STRING_EQUAL( ids[5].getHits()[0].getPeakAnnotations()[3].annotation, "y4")
TEST_EQUAL( ids[5].getHits()[0].getPeakAnnotations()[3].charge, 2)
TEST_STRING_EQUAL(ids[6].getHits()[0].getSequence().toString(), ".(Acetyl)AAAAAAVGPGAGGAGSAVPGGAGPC(Carbamidomethyl)ATVSVFPGAR")
Param p(msp_file.getParameters());
p.setValue("instrument", "qtof");
msp_file.setParameters(p);
ids.clear();
exp.clear(true);
msp_file.load(OPENMS_GET_TEST_DATA_PATH("MSPFile_test.msp"), ids, exp);
TEST_EQUAL(exp.size(), 2)
TEST_EQUAL(ids.size(), 2)
TEST_STRING_EQUAL(exp[0].getNativeID(), "index=0")
TEST_STRING_EQUAL(exp[1].getNativeID(), "index=1")
p.setValue("instrument", "it");
msp_file.setParameters(p);
ids.clear();
exp.clear(true);
msp_file.load(OPENMS_GET_TEST_DATA_PATH("MSPFile_test.msp"), ids, exp);
TEST_EQUAL(exp.size(), 5)
TEST_EQUAL(ids.size(), 5)
TEST_STRING_EQUAL(exp[0].getNativeID(), "index=2")
TEST_STRING_EQUAL(exp[1].getNativeID(), "index=3")
TEST_STRING_EQUAL(exp[2].getNativeID(), "index=4")
END_SECTION
START_SECTION(void store(const String& filename, const AnnotatedMSRun& annot_exp) const)
MSPFile msp_file;
AnnotatedMSRun annot_exp;
msp_file.load(OPENMS_GET_TEST_DATA_PATH("MSPFile_test.msp"), annot_exp);
String filename;
NEW_TMP_FILE(filename);
msp_file.store(filename, annot_exp);
PeakMap exp;
PeptideIdentificationList ids;
msp_file.load(filename, ids, exp);
TEST_EQUAL(ids.size(), 7)
TEST_EQUAL(exp.size(), 7)
TEST_EQUAL(ids[0].getHits().size(), 1)
TEST_EQUAL(ids[1].getHits().size(), 1)
TEST_EQUAL(ids[2].getHits().size(), 1)
TEST_EQUAL(ids[3].getHits().size(), 1)
TEST_EQUAL(ids[4].getHits().size(), 1)
TEST_EQUAL(ids[0].getHits().begin()->getSequence().isModified(), false)
TEST_EQUAL(ids[1].getHits().begin()->getSequence().isModified(), false)
TEST_EQUAL(ids[2].getHits().begin()->getSequence().isModified(), false)
TEST_EQUAL(ids[3].getHits().begin()->getSequence().isModified(), true)
TEST_EQUAL(ids[4].getHits().begin()->getSequence().isModified(), false)
TEST_EQUAL(ids[0].getHits().begin()->getCharge(), 2)
TEST_EQUAL(ids[1].getHits().begin()->getCharge(), 2)
TEST_EQUAL(ids[2].getHits().begin()->getCharge(), 2)
TEST_EQUAL(ids[3].getHits().begin()->getCharge(), 2)
TEST_EQUAL(ids[4].getHits().begin()->getCharge(), 3)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IMSElement_test.cpp | .cpp | 7,659 | 252 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Stephan Aiche $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/CHEMISTRY/ResidueDB.h>
///////////////////////////
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSElement.h>
///////////////////////////
using namespace OpenMS;
using namespace ims;
using namespace std;
START_TEST(IMSElement, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IMSElement* ptr = nullptr;
IMSElement* null_ptr = nullptr;
IMSIsotopeDistribution::peaks_container peaks;
peaks.push_back(IMSIsotopeDistribution::peak_type(0.0078250319,.999885));
peaks.push_back(IMSIsotopeDistribution::peak_type(0.01410178,.000115));
peaks.push_back(IMSIsotopeDistribution::peak_type(0.01604927,.0));
IMSIsotopeDistribution iso(peaks, 1);
START_SECTION(IMSElement())
{
ptr = new IMSElement();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IMSElement())
{
delete ptr;
}
END_SECTION
IMSElement * hydrogen = nullptr;
START_SECTION((IMSElement(const name_type &name, const isotopes_type &isotopes)))
{
hydrogen = new IMSElement("H",iso);
TEST_NOT_EQUAL(hydrogen, null_ptr)
TEST_STRING_EQUAL(hydrogen->getName(), "H")
TEST_EQUAL(hydrogen->getIsotopeDistribution(), iso)
}
END_SECTION
START_SECTION((IMSElement(const IMSElement &element)))
{
IMSElement hydrogen_copy(*hydrogen);
TEST_EQUAL(hydrogen->getAverageMass(), hydrogen_copy.getAverageMass())
TEST_EQUAL(hydrogen->getIonMass(), hydrogen_copy.getIonMass())
TEST_EQUAL(hydrogen->getIsotopeDistribution(), hydrogen_copy.getIsotopeDistribution())
TEST_EQUAL(hydrogen->getMass(), hydrogen_copy.getMass())
TEST_EQUAL(hydrogen->getName(), hydrogen_copy.getName())
TEST_EQUAL(hydrogen->getNominalMass(), hydrogen_copy.getNominalMass())
TEST_EQUAL(hydrogen->getSequence(), hydrogen_copy.getSequence())
}
END_SECTION
START_SECTION((IMSElement(const name_type &name, mass_type mass)))
{
double oxygen_mass = 15.9994;
IMSElement element("O", oxygen_mass);
IMSIsotopeDistribution oxygen(oxygen_mass);
TEST_EQUAL(element.getName(), "O")
TEST_EQUAL(element.getNominalMass(), 0)
TEST_EQUAL(element.getMass(), oxygen_mass)
TEST_EQUAL(element.getIsotopeDistribution(), oxygen)
}
END_SECTION
START_SECTION((IMSElement(const name_type &name, nominal_mass_type nominal_mass=0)))
{
IMSElement::nominal_mass_type nominal_mass = 16;
IMSElement element("O", nominal_mass);
IMSIsotopeDistribution oxygen(nominal_mass);
TEST_EQUAL(element.getName(), "O")
TEST_EQUAL(element.getNominalMass(), nominal_mass)
TEST_EQUAL(element.getIsotopeDistribution(), oxygen)
}
END_SECTION
START_SECTION((const name_type& getName() const ))
{
TEST_STRING_SIMILAR(hydrogen->getName(), "H")
}
END_SECTION
START_SECTION((void setName(const name_type &name)))
{
hydrogen->setName("D");
TEST_STRING_SIMILAR(hydrogen->getName(), "D")
hydrogen->setName("H");
TEST_STRING_SIMILAR(hydrogen->getName(), "H")
}
END_SECTION
START_SECTION((const name_type& getSequence() const ))
{
TEST_STRING_SIMILAR(hydrogen->getSequence(), "H")
}
END_SECTION
START_SECTION((void setSequence(const name_type &sequence)))
{
hydrogen->setSequence("H2");
TEST_STRING_SIMILAR(hydrogen->getSequence(), "H2")
hydrogen->setSequence("H");
TEST_STRING_SIMILAR(hydrogen->getSequence(), "H")
}
END_SECTION
START_SECTION((nominal_mass_type getNominalMass() const ))
{
TEST_EQUAL(hydrogen->getNominalMass(), iso.getNominalMass())
}
END_SECTION
START_SECTION((mass_type getMass(size_type index=0) const ))
{
TEST_EQUAL(hydrogen->getMass(), 1.0078250319)
TEST_EQUAL(hydrogen->getMass(0), 1.0078250319)
TEST_EQUAL(hydrogen->getMass(1), 2.01410178)
TEST_EQUAL(hydrogen->getMass(2), 3.01604927)
}
END_SECTION
START_SECTION((mass_type getAverageMass() const ))
{
TEST_EQUAL(hydrogen->getAverageMass(), iso.getAverageMass())
}
END_SECTION
START_SECTION((mass_type getIonMass(int electrons_number=1) const ))
{
double expected_ion_mass = hydrogen->getMass() - IMSElement::ELECTRON_MASS_IN_U;
TEST_EQUAL(hydrogen->getIonMass(), expected_ion_mass)
TEST_EQUAL(hydrogen->getIonMass(1), expected_ion_mass)
expected_ion_mass = hydrogen->getMass() - 2 * IMSElement::ELECTRON_MASS_IN_U;
TEST_EQUAL(hydrogen->getIonMass(2), expected_ion_mass)
}
END_SECTION
START_SECTION((const IMSIsotopeDistribution& getIsotopeDistribution() const ))
{
TEST_EQUAL(hydrogen->getIsotopeDistribution(), iso)
}
END_SECTION
START_SECTION((void setIsotopeDistribution(const IMSIsotopeDistribution &isotopes)))
{
IMSIsotopeDistribution::peaks_container peaks_copy(peaks);
peaks_copy.push_back(IMSIsotopeDistribution::peak_type(0.03604927,.0));
IMSIsotopeDistribution modified_iso(peaks_copy, 1);
hydrogen->setIsotopeDistribution(modified_iso);
TEST_EQUAL(hydrogen->getIsotopeDistribution(), modified_iso)
hydrogen->setIsotopeDistribution(iso);
TEST_EQUAL(hydrogen->getIsotopeDistribution(), iso)
}
END_SECTION
START_SECTION((IMSElement& operator=(const IMSElement &element)))
{
IMSElement hydrogen_copy;
hydrogen_copy = *hydrogen;
TEST_EQUAL(*hydrogen == hydrogen_copy, true)
TEST_EQUAL(hydrogen->getAverageMass(), hydrogen_copy.getAverageMass())
TEST_EQUAL(hydrogen->getIonMass(), hydrogen_copy.getIonMass())
TEST_EQUAL(hydrogen->getIsotopeDistribution(), hydrogen_copy.getIsotopeDistribution())
TEST_EQUAL(hydrogen->getMass(), hydrogen_copy.getMass())
TEST_EQUAL(hydrogen->getName(), hydrogen_copy.getName())
TEST_EQUAL(hydrogen->getNominalMass(), hydrogen_copy.getNominalMass())
TEST_EQUAL(hydrogen->getSequence(), hydrogen_copy.getSequence())
}
END_SECTION
START_SECTION((bool operator==(const IMSElement &element) const ))
{
IMSElement also_hydrogen("H",iso);
TEST_EQUAL(*hydrogen == also_hydrogen, true)
also_hydrogen.setName("D");
TEST_EQUAL(*hydrogen == also_hydrogen, false)
also_hydrogen.setName("H");
also_hydrogen.setSequence("D");
TEST_EQUAL(*hydrogen == also_hydrogen, false)
also_hydrogen.setSequence("H");
IMSIsotopeDistribution::peaks_container peaks_copy(peaks);
peaks_copy.push_back(IMSIsotopeDistribution::peak_type(0.03604927,.0));
IMSIsotopeDistribution modified_iso(peaks_copy, 1);
also_hydrogen.setIsotopeDistribution(modified_iso);
TEST_EQUAL(*hydrogen == also_hydrogen, false)
IMSElement not_hydrogen;
TEST_EQUAL(*hydrogen == not_hydrogen, false)
}
END_SECTION
START_SECTION((bool operator!=(const IMSElement &element) const ))
{
IMSElement also_hydrogen("H",iso);
TEST_EQUAL(*hydrogen != also_hydrogen, false)
also_hydrogen.setName("D");
TEST_EQUAL(*hydrogen != also_hydrogen, true)
also_hydrogen.setName("H");
also_hydrogen.setSequence("D");
TEST_EQUAL(*hydrogen != also_hydrogen, true)
also_hydrogen.setSequence("H");
IMSIsotopeDistribution::peaks_container peaks_copy(peaks);
peaks_copy.push_back(IMSIsotopeDistribution::peak_type(0.03604927,.0));
IMSIsotopeDistribution modified_iso(peaks_copy, 1);
also_hydrogen.setIsotopeDistribution(modified_iso);
TEST_EQUAL(*hydrogen != also_hydrogen, true)
IMSElement not_hydrogen;
TEST_EQUAL(*hydrogen != not_hydrogen, true)
}
END_SECTION
delete hydrogen;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Types_test.cpp | .cpp | 1,717 | 56 | // 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/CONCEPT/Types.h>
///////////////////////////
#include <clocale>
#include <string>
START_TEST(Types, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
START_SECTION([EXTRA] OpenMS_locale initialization preserves system locale)
{
// This test verifies that initializing OpenMS doesn't permanently change
// the system locale, which is important for Python bindings
// Get the current locale
const char* current = setlocale(LC_ALL, nullptr);
TEST_NOT_EQUAL(current, nullptr);
std::string current_locale(current);
// OpenMS_locale should contain "C"
TEST_STRING_EQUAL(OpenMS::Internal::OpenMS_locale, "C");
// But the system locale should still be what it was
const char* after = setlocale(LC_ALL, nullptr);
TEST_NOT_EQUAL(after, nullptr);
std::string after_locale(after);
// The system locale should not have been changed to "C" by OpenMS initialization
// (unless it was "C" to begin with)
TEST_EQUAL(current_locale, after_locale);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MSDataTransformingConsumer_test.cpp | .cpp | 4,377 | 143 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/DATAACCESS/MSDataTransformingConsumer.h>
///////////////////////////
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FORMAT/MzMLFile.h>
START_TEST(MSDataTransformingConsumer, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
MSDataTransformingConsumer* transforming_consumer_ptr = nullptr;
MSDataTransformingConsumer* transforming_consumer_nullPointer = nullptr;
PeakMap expc;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), expc);
START_SECTION((MSDataTransformingConsumer()))
transforming_consumer_ptr = new MSDataTransformingConsumer();
TEST_NOT_EQUAL(transforming_consumer_ptr, transforming_consumer_nullPointer)
END_SECTION
START_SECTION((~MSDataTransformingConsumer()))
delete transforming_consumer_ptr;
END_SECTION
START_SECTION((void consumeSpectrum(SpectrumType & s)))
{
MSDataTransformingConsumer transforming_consumer;
PeakMap exp = expc;
TEST_EQUAL(exp.getNrSpectra() > 0, true)
MSSpectrum first_spectrum = exp.getSpectrum(0);
transforming_consumer.setExpectedSize(2,0);
transforming_consumer.consumeSpectrum(exp.getSpectrum(0));
TEST_EQUAL(first_spectrum == exp.getSpectrum(0), true) // nothing happened
}
END_SECTION
START_SECTION((void consumeChromatogram(ChromatogramType & c)))
{
MSDataTransformingConsumer transforming_consumer;
PeakMap exp = expc;
TEST_EQUAL(exp.getNrChromatograms() > 0, true)
MSChromatogram first_chromatogram = exp.getChromatogram(0);
transforming_consumer.setExpectedSize(0,1);
transforming_consumer.consumeChromatogram(exp.getChromatogram(0));
TEST_EQUAL(first_chromatogram == exp.getChromatogram(0), true) // nothing happened
}
END_SECTION
START_SECTION((void setExpectedSize(Size, Size)))
NOT_TESTABLE // tested above
END_SECTION
START_SECTION((void setExperimentalSettings(const ExperimentalSettings&)))
{
MSDataTransformingConsumer transforming_consumer;
transforming_consumer.setExpectedSize(2,0);
ExperimentalSettings s;
transforming_consumer.setExperimentalSettings( s );
NOT_TESTABLE
}
END_SECTION
START_SECTION(( void MSDataTransformingConsumer::setSpectraProcessingFunc( std::function<void (SpectrumType&)> f_spec ) ))
{
MSDataTransformingConsumer transforming_consumer;
PeakMap exp = expc;
TEST_EQUAL(exp.getNrSpectra() > 0, true)
exp.getSpectrum(0).sortByPosition();
MSSpectrum first_spectrum = exp.getSpectrum(0);
auto f = [](OpenMS::MSSpectrum & s)
{
s.sortByIntensity();
};
transforming_consumer.setExpectedSize(2,0);
transforming_consumer.setSpectraProcessingFunc(f);
transforming_consumer.consumeSpectrum(exp.getSpectrum(0));
TEST_EQUAL(first_spectrum == exp.getSpectrum(0), false) // something happened
TEST_EQUAL(first_spectrum.isSorted(), true)
TEST_EQUAL(exp.getSpectrum(0).isSorted(), false)
}
END_SECTION
START_SECTION(( void MSDataTransformingConsumer::setChromatogramProcessingFunc( std::function<void (ChromatogramType&)> f_chrom ) ))
{
MSDataTransformingConsumer transforming_consumer;
PeakMap exp = expc;
TEST_EQUAL(exp.getNrChromatograms() > 0, true)
exp.getChromatogram(0).sortByPosition();
MSChromatogram first_chromatogram = exp.getChromatogram(0);
auto f2 = [](OpenMS::MSChromatogram & c)
{
c.sortByIntensity();
};
transforming_consumer.setExpectedSize(0,1);
transforming_consumer.setChromatogramProcessingFunc(f2);
transforming_consumer.consumeChromatogram(exp.getChromatogram(0));
TEST_EQUAL(first_chromatogram == exp.getChromatogram(0), false) // something happened
TEST_EQUAL(first_chromatogram.isSorted(), true)
TEST_EQUAL(exp.getChromatogram(0).isSorted(), false)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/BaseSuperimposer_test.cpp | .cpp | 2,086 | 74 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Clemens Groepl, Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/MAPMATCHING/BaseSuperimposer.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
class TestSuperimposer
: public BaseSuperimposer
{
public:
TestSuperimposer()
: BaseSuperimposer()
{
check_defaults_ = false;
}
void run(const ConsensusMap& , const ConsensusMap& , TransformationDescription& transformation) override
{
Param params;
params.setValue("slope",1.1);
params.setValue("intercept", 5.0);
transformation.fitModel("linear", params);
}
};
START_TEST(BaseSuperimposer, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
TestSuperimposer* ptr = nullptr;
TestSuperimposer* nullPointer = nullptr;
START_SECTION((BaseSuperimposer()))
ptr = new TestSuperimposer();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~BaseSuperimposer()))
delete ptr;
END_SECTION
START_SECTION((virtual void run(const ConsensusMap& map_model, const ConsensusMap& map_scene, TransformationDescription& transformation)=0))
{
TransformationDescription transformation;
TestSuperimposer si;
std::vector<ConsensusMap> maps;
maps.resize(2);
si.run(maps[0], maps[1], transformation);
TEST_STRING_EQUAL(transformation.getModelType(), "linear");
Param params = transformation.getModelParameters();
TEST_REAL_SIMILAR(params.getValue("slope"), 1.1)
TEST_REAL_SIMILAR(params.getValue("intercept"), 5.0)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ConvexHull2D_test.cpp | .cpp | 12,211 | 420 | // 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/ConvexHull2D.h>
#include <unordered_set>
#include <unordered_map>
///////////////////////////
START_TEST(ConvexHull2D, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
ConvexHull2D* ptr = nullptr;
ConvexHull2D* nullPointer = nullptr;
START_SECTION((ConvexHull2D()))
ptr = new ConvexHull2D;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(([EXTRA] ~ConvexHull2D()))
delete ptr;
END_SECTION
START_SECTION((const PointArrayType& getHullPoints() const))
ConvexHull2D tmp;
TEST_EQUAL(tmp.getHullPoints().size(),0)
END_SECTION
//do not change these definitions, they are used in many tests
DPosition<2> p1(1.0,2.0);
DPosition<2> p2(3.0,4.0);
DPosition<2> p3(5.0,0.0);
DPosition<2> p4(1.0,1.0);
DPosition<2> p5(3.0,1.0);
DPosition<2> p6(1.0,3.0);
vector<DPosition<2> > vec;
vec.push_back(p1);
vec.push_back(p2);
vec.push_back(p3);
vector<DPosition<2> > vec2;
vec2.push_back(p4);
vec2.push_back(p5);
vec2.push_back(p6);
START_SECTION(void setHullPoints(const PointArrayType& points))
ConvexHull2D tmp;
vector<DPosition<2> > vec3;
vec3.push_back(p1);
tmp.setHullPoints(vec3);
TEST_EQUAL(tmp.getHullPoints().size(),1)
vec3.push_back(p2);
tmp.setHullPoints(vec3);
TEST_EQUAL(tmp.getHullPoints().size(),2)
vec3.push_back(p3);
tmp.setHullPoints(vec3);
TEST_EQUAL(tmp.getHullPoints().size(),3)
vec3.push_back(p5);
tmp.setHullPoints(vec3);
TEST_EQUAL(tmp.getHullPoints().size(),4)
END_SECTION
START_SECTION((ConvexHull2D& operator=(const ConvexHull2D& rhs)))
ConvexHull2D tmp,tmp2;
tmp.setHullPoints(vec);
tmp2 = tmp;
TEST_EQUAL(tmp2.getHullPoints().size(),3)
END_SECTION
START_SECTION((ConvexHull2D(const ConvexHull2D&& source)))
{
#ifndef OPENMS_COMPILER_MSVC
// Ensure that ConvexHull2D has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
// Note that MSVS does not support noexcept move constructors for STL
// constructs such as std::map.
TEST_EQUAL(noexcept(ConvexHull2D(std::declval<ConvexHull2D&&>())), true)
#endif
}
END_SECTION
START_SECTION((void addPoints(const PointArrayType &points)))
ConvexHull2D tmp;
TEST_EQUAL(tmp.getHullPoints().size(),0)
tmp.addPoints(vec);
TEST_EQUAL(!tmp.getHullPoints().empty(),true)
END_SECTION
START_SECTION((void clear()))
vector<DPosition<2> > vec3;
vec3.push_back(p1);
vec3.push_back(p2);
vec3.push_back(p3);
vec3.push_back(p5);
ConvexHull2D tmp;
tmp.setHullPoints(vec3);
TEST_EQUAL(tmp.getHullPoints().size(),4)
tmp.clear();
TEST_EQUAL(tmp.getHullPoints().size(),0)
tmp.addPoints(vec3);
TEST_EQUAL(tmp.getHullPoints().size(),4)
tmp.clear();
TEST_EQUAL(tmp.getHullPoints().size(),0)
END_SECTION
START_SECTION((bool encloses(const PointType& point) const))
ConvexHull2D tmp;
// setting hull points alone does not allow to query encloses()
tmp.setHullPoints(vec2);
TEST_EXCEPTION(Exception::NotImplemented, tmp.encloses(DPosition<2>(1.0,1.0)))
tmp.addPoints(vec);
tmp.addPoints(vec2);
TEST_EQUAL(tmp.encloses(DPosition<2>(3.0,3.0)),true)
TEST_EQUAL(tmp.encloses(DPosition<2>(0.0,0.0)),false)
TEST_EQUAL(tmp.encloses(DPosition<2>(6.0,0.0)),false)
TEST_EQUAL(tmp.encloses(DPosition<2>(0.0,6.0)),false)
TEST_EQUAL(tmp.encloses(DPosition<2>(1.5,1.5)),true)
TEST_EQUAL(tmp.encloses(DPosition<2>(1.0,1.0)),true)
TEST_EQUAL(tmp.encloses(DPosition<2>(1.1,1.0)),true)
TEST_EQUAL(tmp.encloses(DPosition<2>(1.2,2.5)),true)
TEST_EQUAL(tmp.encloses(DPosition<2>(1.2,3.21)),false)
TEST_EQUAL(tmp.encloses(DPosition<2>(1.4,0.99)),false)
TEST_EQUAL(tmp.encloses(DPosition<2>(2.5,1.2)),true)
TEST_EQUAL(tmp.encloses(DPosition<2>(1.0,1.1)),true)
TEST_EQUAL(tmp.encloses(DPosition<2>(3.0,1.0)),true)
TEST_EQUAL(tmp.encloses(DPosition<2>(5.0,0.0)),true)
END_SECTION
START_SECTION((bool operator==(const ConvexHull2D& rhs) const))
ConvexHull2D tmp,tmp2;
tmp.setHullPoints(vec2);
TEST_EQUAL(tmp==tmp2,false)
tmp2.setHullPoints(vec);
TEST_EQUAL(tmp==tmp2,false)
tmp2.setHullPoints(vec2);
TEST_EQUAL(tmp==tmp2,true)
tmp2.addPoints(vec);
TEST_EQUAL(tmp==tmp2,false)
tmp.addPoints(vec);
TEST_EQUAL(tmp==tmp2,true)
END_SECTION
START_SECTION((DBoundingBox<2> getBoundingBox() const))
//empty
ConvexHull2D tmp2;
TEST_EQUAL(tmp2.getBoundingBox().isEmpty(), true);
tmp2.setHullPoints(vec);
DBoundingBox<2> bb2 = tmp2.getBoundingBox();
TEST_REAL_SIMILAR(bb2.minPosition()[0],1.0)
TEST_REAL_SIMILAR(bb2.minPosition()[1],0.0)
TEST_REAL_SIMILAR(bb2.maxPosition()[0],5.0)
TEST_REAL_SIMILAR(bb2.maxPosition()[1],4.0)
//full
ConvexHull2D tmp;
DBoundingBox<2> bb;
bb = tmp.getBoundingBox();
TEST_EQUAL(bb.isEmpty(),true)
tmp.setHullPoints(vec2);
bb = tmp.getBoundingBox();
TEST_REAL_SIMILAR(bb.minPosition()[0],1.0)
TEST_REAL_SIMILAR(bb.minPosition()[1],1.0)
TEST_REAL_SIMILAR(bb.maxPosition()[0],3.0)
TEST_REAL_SIMILAR(bb.maxPosition()[1],3.0)
tmp.setHullPoints(vec);
bb = tmp.getBoundingBox();
TEST_REAL_SIMILAR(bb.minPosition()[0],1.0)
TEST_REAL_SIMILAR(bb.minPosition()[1],0.0)
TEST_REAL_SIMILAR(bb.maxPosition()[0],5.0)
TEST_REAL_SIMILAR(bb.maxPosition()[1],4.0)
vector<DPosition<2> > vec3;
vec3.push_back(p1);
tmp.setHullPoints(vec3);
bb = tmp.getBoundingBox();
TEST_REAL_SIMILAR(bb.minPosition()[0],1.0)
TEST_REAL_SIMILAR(bb.minPosition()[1],2.0)
TEST_REAL_SIMILAR(bb.maxPosition()[0],1.0)
TEST_REAL_SIMILAR(bb.maxPosition()[1],2.0)
vec3.push_back(p2);
tmp.setHullPoints(vec3);
bb = tmp.getBoundingBox();
TEST_REAL_SIMILAR(bb.minPosition()[0],1.0)
TEST_REAL_SIMILAR(bb.minPosition()[1],2.0)
TEST_REAL_SIMILAR(bb.maxPosition()[0],3.0)
TEST_REAL_SIMILAR(bb.maxPosition()[1],4.0)
END_SECTION
START_SECTION((bool addPoint(const PointType& point)))
ConvexHull2D tmp;
TEST_EQUAL(tmp.addPoint(DPosition<2>(1.5,1.5)),true)
TEST_EQUAL(tmp.addPoint(DPosition<2>(1.0,1.0)),true)
TEST_EQUAL(tmp.addPoint(DPosition<2>(1.0,1.5)),true)
TEST_EQUAL(tmp.addPoint(DPosition<2>(1.0,1.2)),false)
TEST_EQUAL(tmp.addPoint(DPosition<2>(3.0,2.5)),true)
TEST_EQUAL(tmp.addPoint(DPosition<2>(3.0,1.5)),true)
TEST_EQUAL(tmp.addPoint(DPosition<2>(3.0,2.5)),false)
TEST_EQUAL(tmp.addPoint(DPosition<2>(3.0,2.0)),false)
TEST_EQUAL(tmp.addPoint(DPosition<2>(0.5,0.5)),true)
END_SECTION
START_SECTION((Size compress()))
{
ConvexHull2D tmp;
tmp.addPoint(DPosition<2>(1.,1.));
tmp.addPoint(DPosition<2>(1.,10.));
tmp.addPoint(DPosition<2>(2.,1.));
tmp.addPoint(DPosition<2>(2.,10.));
tmp.addPoint(DPosition<2>(3.,1.));
tmp.addPoint(DPosition<2>(3.,10.));
DBoundingBox<2> beforeCompress = tmp.getBoundingBox();
TEST_EQUAL(tmp.compress() , 1)
// second call should remove no points
TEST_EQUAL(tmp.compress() , 0)
TEST_EQUAL(tmp.getBoundingBox(), beforeCompress)
tmp.addPoint(DPosition<2>(4.,1.));
tmp.addPoint(DPosition<2>(4.,10.));
tmp.addPoint(DPosition<2>(5.,2.));
tmp.addPoint(DPosition<2>(5.,10.));
tmp.addPoint(DPosition<2>(6.,1.));
tmp.addPoint(DPosition<2>(6.,10.));
beforeCompress = tmp.getBoundingBox();
TEST_EQUAL(tmp.compress() , 1)
// second call should remove no points
TEST_EQUAL(tmp.compress() , 0)
TEST_EQUAL(tmp.getBoundingBox(), beforeCompress)
// check if encloses still works correct
TEST_EQUAL(tmp.encloses(DPosition<2>(1.1, 5.)), true)
TEST_EQUAL(tmp.encloses(DPosition<2>(2.1, 5.)), true)
TEST_EQUAL(tmp.encloses(DPosition<2>(3.1, 5.)), true)
TEST_EQUAL(tmp.encloses(DPosition<2>(4.1, 5.)), true)
TEST_EQUAL(tmp.encloses(DPosition<2>(5.1, 5.)), true)
TEST_EQUAL(tmp.encloses(DPosition<2>(5.1, 1.)), false)
TEST_EQUAL(tmp.encloses(DPosition<2>(5.9, 5.)), true)
}
END_SECTION
START_SECTION((void expandToBoundingBox()))
{
ConvexHull2D tmp;
tmp.addPoint(DPosition<2>(1.,1.));
tmp.addPoint(DPosition<2>(1.,10.));
tmp.addPoint(DPosition<2>(2.,1.));
tmp.addPoint(DPosition<2>(2.,10.));
tmp.addPoint(DPosition<2>(3.,1.));
tmp.addPoint(DPosition<2>(3.,10.));
tmp.addPoint(DPosition<2>(4.,1.));
tmp.addPoint(DPosition<2>(4.,10.));
tmp.addPoint(DPosition<2>(5.,2.));
tmp.addPoint(DPosition<2>(5.,10.));
tmp.addPoint(DPosition<2>(6.,1.));
tmp.addPoint(DPosition<2>(6.,10.));
ConvexHull2D original(tmp);
// Make sure we are left with only four points afterwards.
tmp.expandToBoundingBox();
TEST_EQUAL(tmp.getHullPoints().size(), 4)
// second call should remove no points
tmp.expandToBoundingBox();
TEST_EQUAL(tmp.getHullPoints().size(), 4)
// Check that values agree with min/max of the
// enclosed points.
float min_x, min_y, max_x, max_y;
min_x = tmp.getHullPoints()[0][0];
min_y = tmp.getHullPoints()[0][1];
max_x = min_x;
max_y = min_y;
for (Size i = 0; i < tmp.getHullPoints().size(); ++i)
{
float x = tmp.getHullPoints()[i][0];
float y = tmp.getHullPoints()[i][1];
min_x = std::min(min_x, x);
max_x = std::max(max_x, x);
min_y = std::min(min_y, y);
max_y = std::max(max_y, y);
}
float o_min_x, o_min_y, o_max_x, o_max_y;
o_min_x = original.getHullPoints()[0][0];
o_min_y = original.getHullPoints()[0][1];
o_max_x = o_min_x;
o_max_y = o_min_y;
for (Size i = 0; i < original.getHullPoints().size(); ++i)
{
float x = original.getHullPoints()[i][0];
float y = original.getHullPoints()[i][1];
o_min_x = std::min(o_min_x, x);
o_max_x = std::max(o_max_x, x);
o_min_y = std::min(o_min_y, y);
o_max_y = std::max(o_max_y, y);
}
TEST_REAL_SIMILAR(min_x, o_min_x)
TEST_REAL_SIMILAR(min_y, o_min_y)
TEST_REAL_SIMILAR(max_x, o_max_x)
TEST_REAL_SIMILAR(max_y, o_max_y)
}
END_SECTION
START_SECTION(([EXTRA] std::hash<ConvexHull2D>))
{
// Test that std::hash is defined and usable
std::hash<ConvexHull2D> hasher;
// Create two equal ConvexHull2D objects
ConvexHull2D h1, h2;
vector<DPosition<2>> points;
points.push_back(DPosition<2>(1.0, 2.0));
points.push_back(DPosition<2>(3.0, 4.0));
points.push_back(DPosition<2>(5.0, 0.0));
h1.setHullPoints(points);
h2.setHullPoints(points);
// Equal objects must have equal hashes
TEST_EQUAL(h1 == h2, true)
TEST_EQUAL(hasher(h1), hasher(h2))
// Different objects should (likely) have different hashes
ConvexHull2D h3;
vector<DPosition<2>> points2;
points2.push_back(DPosition<2>(10.0, 20.0));
points2.push_back(DPosition<2>(30.0, 40.0));
h3.setHullPoints(points2);
TEST_EQUAL(h1 == h3, false)
// Note: different hashes are not guaranteed, but highly likely
TEST_NOT_EQUAL(hasher(h1), hasher(h3))
// Test use in unordered_set
std::unordered_set<ConvexHull2D> hull_set;
hull_set.insert(h1);
hull_set.insert(h2); // duplicate, should not increase size
hull_set.insert(h3);
TEST_EQUAL(hull_set.size(), 2)
TEST_EQUAL(hull_set.count(h1), 1)
TEST_EQUAL(hull_set.count(h3), 1)
// Test use in unordered_map
std::unordered_map<ConvexHull2D, int> hull_map;
hull_map[h1] = 1;
hull_map[h3] = 3;
TEST_EQUAL(hull_map.size(), 2)
TEST_EQUAL(hull_map[h1], 1)
TEST_EQUAL(hull_map[h2], 1) // h2 == h1, so should get same value
TEST_EQUAL(hull_map[h3], 3)
// Test with hulls built using addPoint
ConvexHull2D h4, h5;
h4.addPoint(DPosition<2>(1.0, 1.0));
h4.addPoint(DPosition<2>(2.0, 2.0));
h4.addPoint(DPosition<2>(3.0, 3.0));
h5.addPoint(DPosition<2>(1.0, 1.0));
h5.addPoint(DPosition<2>(2.0, 2.0));
h5.addPoint(DPosition<2>(3.0, 3.0));
TEST_EQUAL(h4 == h5, true)
TEST_EQUAL(hasher(h4), hasher(h5))
// Empty hulls should have equal hashes
ConvexHull2D empty1, empty2;
TEST_EQUAL(empty1 == empty2, true)
TEST_EQUAL(hasher(empty1), hasher(empty2))
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/AcquisitionInfo_test.cpp | .cpp | 3,296 | 122 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/METADATA/AcquisitionInfo.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(AcquisitionInfo, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
AcquisitionInfo* ptr = nullptr;
AcquisitionInfo* nullPointer = nullptr;
START_SECTION(AcquisitionInfo())
ptr = new AcquisitionInfo();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~AcquisitionInfo())
delete ptr;
END_SECTION
START_SECTION(const String& getMethodOfCombination() const)
AcquisitionInfo tmp;
TEST_EQUAL(tmp.getMethodOfCombination(),"");
END_SECTION
START_SECTION(void setMethodOfCombination(const String& method_of_combination))
AcquisitionInfo tmp;
tmp.setMethodOfCombination("TEST");
TEST_EQUAL(tmp.getMethodOfCombination(),"TEST");
END_SECTION
START_SECTION(AcquisitionInfo(const AcquisitionInfo& source))
AcquisitionInfo tmp;
Acquisition a;
a.setIdentifier("4711");
tmp.push_back(a);
tmp.setMethodOfCombination("Combo");
tmp.setMetaValue("bla",4.0);
AcquisitionInfo tmp2(tmp);
TEST_EQUAL(tmp2.size(), 1);
TEST_EQUAL(tmp2[0].getIdentifier(), "4711");
TEST_EQUAL(tmp2.getMethodOfCombination(), "Combo");
TEST_REAL_SIMILAR((double)(tmp2.getMetaValue("bla")), 4.0)
END_SECTION
START_SECTION(AcquisitionInfo& operator= (const AcquisitionInfo& source))
AcquisitionInfo tmp;
Acquisition a;
a.setIdentifier("4711");
tmp.push_back(a);
tmp.setMethodOfCombination("Combo");
tmp.setMetaValue("bla",4.0);
//normal assignment
AcquisitionInfo tmp2;
tmp2 = tmp;
TEST_EQUAL(tmp2.size(), 1);
TEST_EQUAL(tmp2[0].getIdentifier(), "4711");
TEST_EQUAL(tmp2.getMethodOfCombination(), "Combo");
TEST_REAL_SIMILAR((double)(tmp2.getMetaValue("bla")), 4.0)
//assignment of a empty value
tmp2 = AcquisitionInfo();
TEST_EQUAL(tmp2.size(), 0);
TEST_EQUAL(tmp2.getMethodOfCombination(), "");
TEST_EQUAL(tmp2.metaValueExists("bla"), false)
END_SECTION
START_SECTION(bool operator== (const AcquisitionInfo& rhs) const)
AcquisitionInfo empty,edit;
TEST_EQUAL(empty==edit,true);
Acquisition a;
edit.push_back(a);
TEST_EQUAL(empty==edit,false);
edit.setMetaValue("bla",4.0);
TEST_EQUAL(empty==edit,false);
edit = empty;
edit.setMethodOfCombination("Combo");
TEST_EQUAL(empty==edit,false);
END_SECTION
START_SECTION(bool operator!= (const AcquisitionInfo& rhs) const)
AcquisitionInfo empty,edit;
TEST_EQUAL(empty!=edit,false);
Acquisition a;
edit.push_back(a);
TEST_EQUAL(empty!=edit,true);
edit.setMetaValue("bla",4.0);
TEST_EQUAL(empty!=edit,true);
edit = empty;
edit.setMethodOfCombination("Combo");
TEST_EQUAL(empty!=edit,true);
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MSPGenericFile_test.cpp | .cpp | 12,174 | 372 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/MSPGenericFile.h>
#include <OpenMS/KERNEL/SpectrumHelper.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MSPGenericFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MSPGenericFile* ptr = nullptr;
MSPGenericFile* null_ptr = nullptr;
const String input_filepath = OPENMS_GET_TEST_DATA_PATH("MSPGenericFile_input.msp");
START_SECTION(MSPGenericFile())
{
ptr = new MSPGenericFile();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~MSPGenericFile())
{
delete ptr;
}
END_SECTION
START_SECTION(void load(const String& filename, MSExperiment& experiment) const)
{
MSPGenericFile msp;
MSExperiment experiment;
msp.load(input_filepath, experiment);
const vector<MSSpectrum>& spectra = experiment.getSpectra();
TEST_EQUAL(spectra.size(), 3)
const MSSpectrum& s1 = spectra[0];
TEST_EQUAL(s1.size(), 14)
TEST_EQUAL(s1.getName(), "name1 of first")
TEST_EQUAL(s1.metaValueExists("Synon"), true)
TEST_STRING_EQUAL(s1.getMetaValue("Synon"), "name2 of 1st|name3 of firsttt")
TEST_EQUAL(s1.metaValueExists("Formula"), true)
TEST_STRING_EQUAL(s1.getMetaValue("Formula"), "A11B22C333")
TEST_EQUAL(s1.metaValueExists("MW"), true)
TEST_STRING_EQUAL(s1.getMetaValue("MW"), "156")
TEST_EQUAL(s1.metaValueExists("CAS#"), true)
TEST_STRING_EQUAL(s1.getMetaValue("CAS#"), "0123-45-6")
TEST_EQUAL(s1.metaValueExists("NIST#"), true)
TEST_STRING_EQUAL(s1.getMetaValue("NIST#"), "654321")
TEST_EQUAL(s1.metaValueExists("DB#"), true)
TEST_STRING_EQUAL(s1.getMetaValue("DB#"), "1")
TEST_EQUAL(s1.metaValueExists("Comments"), true)
TEST_STRING_EQUAL(s1.getMetaValue("Comments"), "Some comment")
TEST_EQUAL(s1.metaValueExists("Num Peaks"), true)
TEST_STRING_EQUAL(s1.getMetaValue("Num Peaks"), "14")
TEST_EQUAL(s1[0].getPos(), 27)
TEST_EQUAL(s1[0].getIntensity(), 29)
TEST_EQUAL(s1[5].getPos(), 60)
TEST_EQUAL(s1[5].getIntensity(), 41)
TEST_EQUAL(s1[10].getPos(), 90)
TEST_EQUAL(s1[10].getIntensity(), 168)
TEST_EQUAL(s1[13].getPos(), 105)
TEST_EQUAL(s1[13].getIntensity(), 36)
const MSSpectrum& s2 = spectra[1];
TEST_EQUAL(s2.size(), 15)
TEST_EQUAL(s2.getName(), "name1 of second")
TEST_EQUAL(s2.metaValueExists("Synon"), true)
TEST_STRING_EQUAL(s2.getMetaValue("Synon"), "name2 of 2nd|name3 of seconddd")
TEST_EQUAL(s2.metaValueExists("Formula"), true)
TEST_STRING_EQUAL(s2.getMetaValue("Formula"), "A44B55C666")
TEST_EQUAL(s2.metaValueExists("MW"), true)
TEST_STRING_EQUAL(s2.getMetaValue("MW"), "589")
TEST_EQUAL(s2.metaValueExists("CAS#"), true)
TEST_STRING_EQUAL(s2.getMetaValue("CAS#"), "3210-45-6")
TEST_EQUAL(s2.metaValueExists("NIST#"), true)
TEST_STRING_EQUAL(s2.getMetaValue("NIST#"), "789564")
TEST_EQUAL(s2.metaValueExists("DB#"), true)
TEST_STRING_EQUAL(s2.getMetaValue("DB#"), "2")
TEST_EQUAL(s2.metaValueExists("Comments"), true)
TEST_STRING_EQUAL(s2.getMetaValue("Comments"), "Some other comment")
TEST_EQUAL(s2.metaValueExists("Num Peaks"), true)
TEST_STRING_EQUAL(s2.getMetaValue("Num Peaks"), "15")
TEST_EQUAL(s2[0].getPos(), 27)
TEST_EQUAL(s2[0].getIntensity(), 29)
TEST_EQUAL(s2[5].getPos(), 260)
TEST_EQUAL(s2[5].getIntensity(), 41)
TEST_EQUAL(s2[10].getPos(), 290)
TEST_EQUAL(s2[10].getIntensity(), 168)
TEST_EQUAL(s2[14].getPos(), 310)
TEST_EQUAL(s2[14].getIntensity(), 20)
const MSSpectrum& s3 = spectra[2];
TEST_EQUAL(s3.size(), 16)
TEST_EQUAL(s3.getName(), "name1 of third")
TEST_EQUAL(s3.metaValueExists("Synon"), true)
TEST_STRING_EQUAL(s3.getMetaValue("Synon"), "name2 of 3rd|name3 of thirddd")
TEST_EQUAL(s3.metaValueExists("Formula"), true)
TEST_STRING_EQUAL(s3.getMetaValue("Formula"), "A12B12C123")
TEST_EQUAL(s3.metaValueExists("MW"), true)
TEST_STRING_EQUAL(s3.getMetaValue("MW"), "562")
TEST_EQUAL(s3.metaValueExists("CAS#"), true)
TEST_STRING_EQUAL(s3.getMetaValue("CAS#"), "4210-47-4")
TEST_EQUAL(s3.metaValueExists("NIST#"), true)
TEST_STRING_EQUAL(s3.getMetaValue("NIST#"), "749514")
TEST_EQUAL(s3.metaValueExists("DB#"), true)
TEST_STRING_EQUAL(s3.getMetaValue("DB#"), "3")
TEST_EQUAL(s3.metaValueExists("Comments"), false) // this spectrum doesn't have a comment
TEST_EQUAL(s3.metaValueExists("Num Peaks"), true)
TEST_STRING_EQUAL(s3.getMetaValue("Num Peaks"), "16")
TEST_EQUAL(s3[0].getPos(), 27)
TEST_EQUAL(s3[0].getIntensity(), 29)
TEST_EQUAL(s3[5].getPos(), 260)
TEST_EQUAL(s3[5].getIntensity(), 41)
TEST_EQUAL(s3[10].getPos(), 290)
TEST_EQUAL(s3[10].getIntensity(), 168)
TEST_EQUAL(s3[14].getPos(), 310)
TEST_EQUAL(s3[14].getIntensity(), 20)
TEST_EQUAL(s3[15].getPos(), 111)
TEST_EQUAL(s3[15].getIntensity(), 44)
}
END_SECTION
START_SECTION(void store(const String& filename, const MSExperiment& library) const)
{
MSPGenericFile msp;
MSExperiment exp;
PeakMap::SpectrumType spec;
PeakMap::PeakType peak;
spec.setName("first spectrum");
spec.setMetaValue("Synon", "first1|first2|first3");
spec.setMetaValue("CAS#", "0123-45-6");
spec.setMetaValue("NIST#", "654321");
spec.setRT(11.1);
spec.setMSLevel(1);
peak.getPosition()[0] = 1;
peak.setIntensity(1.50f);
spec.push_back(peak);
peak.getPosition()[0] = 2;
peak.setIntensity(2.5f);
spec.push_back(peak);
peak.getPosition()[0] = 3;
peak.setIntensity(3.5f);
spec.push_back(peak);
exp.addSpectrum(spec);
spec.clear(true);
spec.setName("second spectrum");
spec.setMetaValue("Synon", "second1");
spec.setMetaValue("CAS#", "0123-45-2");
spec.setMetaValue("NIST#", "654322");
spec.setMetaValue("other_metadata1", "value1");
spec.setMetaValue("other_metadata2", "value2");
spec.setRT(22.2);
spec.setMSLevel(1);
peak.getPosition()[0] = 11;
peak.setIntensity(11.50f);
spec.push_back(peak);
peak.getPosition()[0] = 12;
peak.setIntensity(12.5f);
spec.push_back(peak);
peak.getPosition()[0] = 13;
peak.setIntensity(13.5f);
spec.push_back(peak);
peak.getPosition()[0] = 14;
peak.setIntensity(14.5f);
spec.push_back(peak);
peak.getPosition()[0] = 15;
peak.setIntensity(15.5f);
spec.push_back(peak);
peak.getPosition()[0] = 16;
peak.setIntensity(16.5f);
spec.push_back(peak);
exp.addSpectrum(spec);
spec.clear(true);
spec.setName("third spectrum");
spec.setMetaValue("CAS#", "0123-45-3");
spec.setMetaValue("NIST#", "654323");
spec.setRT(33.3);
spec.setMSLevel(1);
peak.getPosition()[0] = 101;
peak.setIntensity(101.50f);
spec.push_back(peak);
peak.getPosition()[0] = 102;
peak.setIntensity(102.5f);
spec.push_back(peak);
peak.getPosition()[0] = 103;
peak.setIntensity(103.5f);
spec.push_back(peak);
exp.addSpectrum(spec);
String output_filepath;
NEW_TMP_FILE(output_filepath)
msp.store(output_filepath, exp);
// read back created file
MSExperiment exp_test;
msp.load(output_filepath, exp_test);
const vector<MSSpectrum>& spectra = exp_test.getSpectra();
TEST_EQUAL(spectra.size(), 3)
const MSSpectrum& s1 = spectra[0];
TEST_EQUAL(s1.getName(), "first spectrum")
TEST_EQUAL(s1.metaValueExists("Synon"), true)
TEST_STRING_EQUAL(s1.getMetaValue("Synon"), "first1|first2|first3")
TEST_EQUAL(s1.metaValueExists("CAS#"), true)
TEST_STRING_EQUAL(s1.getMetaValue("CAS#"), "0123-45-6")
TEST_EQUAL(s1.metaValueExists("NIST#"), true)
TEST_STRING_EQUAL(s1.getMetaValue("NIST#"), "654321")
TEST_EQUAL(s1.size(), 3)
TEST_REAL_SIMILAR(s1[0].getMZ(), 1)
TEST_REAL_SIMILAR(s1[0].getIntensity(), 1.5)
TEST_REAL_SIMILAR(s1[1].getMZ(), 2)
TEST_REAL_SIMILAR(s1[1].getIntensity(), 2.5)
TEST_REAL_SIMILAR(s1[2].getMZ(), 3)
TEST_REAL_SIMILAR(s1[2].getIntensity(), 3.5)
const MSSpectrum& s2 = spectra[1];
TEST_EQUAL(s2.getName(), "second spectrum")
TEST_EQUAL(s2.metaValueExists("Synon"), true)
TEST_STRING_EQUAL(s2.getMetaValue("Synon"), "second1")
TEST_EQUAL(s2.metaValueExists("CAS#"), true)
TEST_STRING_EQUAL(s2.getMetaValue("CAS#"), "0123-45-2")
TEST_EQUAL(s2.metaValueExists("NIST#"), true)
TEST_STRING_EQUAL(s2.getMetaValue("NIST#"), "654322")
TEST_EQUAL(s2.size(), 6)
TEST_REAL_SIMILAR(s2[0].getMZ(), 11)
TEST_REAL_SIMILAR(s2[0].getIntensity(), 11.5)
TEST_REAL_SIMILAR(s2[1].getMZ(), 12)
TEST_REAL_SIMILAR(s2[1].getIntensity(), 12.5)
TEST_REAL_SIMILAR(s2[2].getMZ(), 13)
TEST_REAL_SIMILAR(s2[2].getIntensity(), 13.5)
TEST_REAL_SIMILAR(s2[3].getMZ(), 14)
TEST_REAL_SIMILAR(s2[3].getIntensity(), 14.5)
TEST_REAL_SIMILAR(s2[4].getMZ(), 15)
TEST_REAL_SIMILAR(s2[4].getIntensity(), 15.5)
TEST_REAL_SIMILAR(s2[5].getMZ(), 16)
TEST_REAL_SIMILAR(s2[5].getIntensity(), 16.5)
const MSSpectrum& s3 = spectra[2];
TEST_EQUAL(s3.getName(), "third spectrum")
TEST_EQUAL(s3.metaValueExists("Synon"), false)
TEST_EQUAL(s3.metaValueExists("CAS#"), true)
TEST_STRING_EQUAL(s3.getMetaValue("CAS#"), "0123-45-3")
TEST_EQUAL(s3.metaValueExists("NIST#"), true)
TEST_STRING_EQUAL(s3.getMetaValue("NIST#"), "654323")
TEST_EQUAL(s3.size(), 3)
TEST_REAL_SIMILAR(s3[0].getMZ(), 101)
TEST_REAL_SIMILAR(s3[0].getIntensity(), 101.5)
TEST_REAL_SIMILAR(s3[1].getMZ(), 102)
TEST_REAL_SIMILAR(s3[1].getIntensity(), 102.5)
TEST_REAL_SIMILAR(s3[2].getMZ(), 103)
TEST_REAL_SIMILAR(s3[2].getIntensity(), 103.5)
// test invalid spectrum (no name).
MSExperiment invalid_exp;
PeakMap::SpectrumType invalid_spec;
PeakMap::PeakType invalid_peak;
invalid_spec.setMetaValue("Synon", "first1|first2|first3");
invalid_spec.setMetaValue("CAS#", "0123-45-6");
invalid_spec.setMetaValue("NIST#", "654321");
invalid_spec.setRT(11.1);
invalid_spec.setMSLevel(1);
invalid_peak.getPosition()[0] = 1;
invalid_peak.setIntensity(1.50f);
invalid_spec.push_back(invalid_peak);
invalid_peak.getPosition()[0] = 2;
invalid_peak.setIntensity(2.5f);
invalid_spec.push_back(invalid_peak);
invalid_peak.getPosition()[0] = 3;
invalid_peak.setIntensity(3.5f);
invalid_spec.push_back(invalid_peak);
invalid_exp.addSpectrum(invalid_spec);
NEW_TMP_FILE(output_filepath)
TEST_EXCEPTION(Exception::MissingInformation, msp.store(output_filepath, invalid_exp))
}
END_SECTION
START_SECTION(void addSpectrumToLibrary(
MSSpectrum& spectrum,
MSExperiment& library
))
{
MSPGenericFile_friend msp_f;
MSExperiment lib;
MSSpectrum spec;
spec.setName(""); // empty name
spec.setMetaValue("is_valid", 1);
TEST_EXCEPTION(Exception::MissingInformation, msp_f.addSpectrumToLibrary(spec, lib))
TEST_EQUAL(lib.size(), 0)
spec.setName("foo"); // Num Peaks still absent!
TEST_EXCEPTION(Exception::MissingInformation, msp_f.addSpectrumToLibrary(spec, lib))
TEST_EQUAL(lib.size(), 0)
spec.setMetaValue("Num Peaks", "2");
// Num Peaks is set but raw data poins have not been added
TEST_EXCEPTION(Exception::ParseError, msp_f.addSpectrumToLibrary(spec, lib))
TEST_EQUAL(lib.size(), 0)
spec.push_back(Peak1D(1.0, 2.0));
spec.push_back(Peak1D(3.0, 4.0)); // now the spectrum is valid
msp_f.addSpectrumToLibrary(spec, lib);
TEST_EQUAL(lib.size(), 1)
spec.setName("bar");
spec.setMetaValue("is_valid", 1);
msp_f.addSpectrumToLibrary(spec, lib);
TEST_EQUAL(lib.size(), 2)
spec.setMetaValue("is_valid", 1);
msp_f.addSpectrumToLibrary(spec, lib); // duplicate, won't be added
TEST_EQUAL(lib.size(), 2)
spec.setMetaValue("is_valid", 0);
spec.setName("not a duplicate");
msp_f.addSpectrumToLibrary(spec, lib);
TEST_EQUAL(lib.size(), 2)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/QuantmsIO_test.cpp | .cpp | 19,402 | 530 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/QuantmsIO.h>
///////////////////////////
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideHit.h>
#include <OpenMS/METADATA/PeptideEvidence.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <arrow/api.h>
#include <arrow/io/api.h>
#include <parquet/arrow/reader.h>
using namespace OpenMS;
using namespace std;
START_TEST(QuantmsIO, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
QuantmsIO* ptr = nullptr;
QuantmsIO* null_ptr = nullptr;
START_SECTION(QuantmsIO())
{
ptr = new QuantmsIO();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~QuantmsIO())
{
delete ptr;
}
END_SECTION
START_SECTION((void store(const String& filename, const std::vector<ProteinIdentification>& protein_identifications, const PeptideIdentificationList& peptide_identifications)))
{
QuantmsIO file;
// Create test data
vector<ProteinIdentification> protein_ids;
PeptideIdentificationList peptide_ids;
ProteinIdentification protein_id;
protein_id.setIdentifier("test_search");
protein_id.setSearchEngine("TestEngine");
protein_id.setScoreType("TestScore");
protein_id.setHigherScoreBetter(true);
protein_ids.push_back(protein_id);
std::vector<String> pep_strs = {"PEPTIDER", "PEM(Oxidation)TIDER", "DFPIANGER"};
// Create multiple peptide identifications to test row count
for (size_t i = 0; i < pep_strs.size(); ++i)
{
PeptideIdentification peptide_id;
peptide_id.setIdentifier("test_search");
peptide_id.setRT(1234.5 + i * 100);
peptide_id.setMZ(500.25 + i * 50);
peptide_id.setScoreType("TestScore");
PeptideHit hit;
hit.setSequence(AASequence::fromString(pep_strs[i]));
hit.setScore(0.95 - i * 0.1);
hit.setCharge(2 + i);
// Add target_decoy metavalue for testing decoy detection
if (i % 2 == 0)
{
hit.setMetaValue("target_decoy", "target");
}
else
{
hit.setMetaValue("target_decoy", "decoy");
}
// Add PEP score as metavalue for testing
hit.setMetaValue("pep", 0.01 + i * 0.005);
PeptideEvidence evidence;
evidence.setProteinAccession("TEST_PROTEIN_" + String(i));
hit.setPeptideEvidences(vector<PeptideEvidence>{evidence});
// Add multiple hits, but only first should be processed
vector<PeptideHit> hits = {hit};
if (i == 0) {
PeptideHit second_hit;
second_hit.setSequence(AASequence::fromString("SECOND"));
second_hit.setScore(0.5);
second_hit.setCharge(1);
hits.push_back(second_hit);
}
peptide_id.setHits(hits);
peptide_ids.push_back(peptide_id);
}
String output_file;
NEW_TMP_FILE(output_file)
// Store the data
TEST_NOT_EQUAL(peptide_ids.size(), 0)
file.store(output_file, protein_ids, peptide_ids);
// Read back the parquet file and verify rows and columns
arrow::MemoryPool* pool = arrow::default_memory_pool();
std::shared_ptr<arrow::io::ReadableFile> infile;
auto result = arrow::io::ReadableFile::Open(output_file.c_str());
TEST_EQUAL(result.ok(), true)
infile = result.ValueOrDie();
std::unique_ptr<parquet::arrow::FileReader> reader;
PARQUET_ASSIGN_OR_THROW(reader, parquet::arrow::OpenFile(infile, pool));
std::shared_ptr<arrow::Table> table;
auto read_status = reader->ReadTable(&table);
TEST_EQUAL(read_status.ok(), true)
// Verify number of rows (should equal number of peptide identifications)
TEST_EQUAL(table->num_rows(), 3)
// Verify number of columns (should match the quantms.io PSM schema without file_metadata)
TEST_EQUAL(table->num_columns(), 19)
// Verify column names match the schema
auto schema = table->schema();
TEST_EQUAL(schema->field(0)->name(), "sequence")
TEST_EQUAL(schema->field(1)->name(), "peptidoform")
TEST_EQUAL(schema->field(2)->name(), "modifications")
TEST_EQUAL(schema->field(3)->name(), "precursor_charge")
TEST_EQUAL(schema->field(4)->name(), "posterior_error_probability")
TEST_EQUAL(schema->field(5)->name(), "is_decoy")
TEST_EQUAL(schema->field(6)->name(), "calculated_mz")
TEST_EQUAL(schema->field(7)->name(), "observed_mz")
TEST_EQUAL(schema->field(8)->name(), "additional_scores")
TEST_EQUAL(schema->field(9)->name(), "protein_accessions")
TEST_EQUAL(schema->field(10)->name(), "predicted_rt")
TEST_EQUAL(schema->field(11)->name(), "reference_file_name")
TEST_EQUAL(schema->field(12)->name(), "cv_params")
TEST_EQUAL(schema->field(13)->name(), "scan")
TEST_EQUAL(schema->field(14)->name(), "rt")
TEST_EQUAL(schema->field(15)->name(), "ion_mobility")
TEST_EQUAL(schema->field(16)->name(), "number_peaks")
TEST_EQUAL(schema->field(17)->name(), "mz_array")
TEST_EQUAL(schema->field(18)->name(), "intensity_array")
// TODO: Add verification of file-level metadata when parquet metadata API is available
// The file metadata should be stored at the Parquet file level, not as schema fields
}
END_SECTION
START_SECTION((void store(const String& filename, const std::vector<ProteinIdentification>& protein_identifications, const PeptideIdentificationList& peptide_identifications, bool export_all_psms)))
{
QuantmsIO file;
// Create test data with multiple hits per peptide identification
vector<ProteinIdentification> protein_ids;
PeptideIdentificationList peptide_ids;
ProteinIdentification protein_id;
protein_id.setIdentifier("test_search");
protein_id.setSearchEngine("TestEngine");
protein_id.setScoreType("TestScore");
protein_id.setHigherScoreBetter(true);
protein_ids.push_back(protein_id);
// Create one peptide identification with multiple hits
PeptideIdentification peptide_id;
peptide_id.setIdentifier("test_search");
peptide_id.setRT(1234.5);
peptide_id.setMZ(500.25);
peptide_id.setScoreType("TestScore");
vector<PeptideHit> hits;
vector<String> pep_strs = {"PEPTIDER", "ALTERNATIVE", "THIRDPSM"};
for (int i = 0; i < 3; ++i)
{
PeptideHit hit;
hit.setSequence(AASequence::fromString(pep_strs[i]));
hit.setScore(0.95 - i * 0.1);
hit.setCharge(2 + i);
hit.setRank(i); // Set rank explicitly (0-based)
hit.setMetaValue("target_decoy", "target");
PeptideEvidence evidence;
evidence.setProteinAccession("TEST_PROTEIN_" + String(i));
hit.setPeptideEvidences(vector<PeptideEvidence>{evidence});
hits.push_back(hit);
}
peptide_id.setHits(hits);
peptide_ids.push_back(peptide_id);
String output_file;
NEW_TMP_FILE(output_file)
// Store the data with export_all_psms = true
file.store(output_file, protein_ids, peptide_ids, true);
// Read back the parquet file and verify rows and columns
arrow::MemoryPool* pool = arrow::default_memory_pool();
std::shared_ptr<arrow::io::ReadableFile> infile;
auto result = arrow::io::ReadableFile::Open(output_file.c_str());
TEST_EQUAL(result.ok(), true)
infile = result.ValueOrDie();
std::unique_ptr<parquet::arrow::FileReader> reader;
PARQUET_ASSIGN_OR_THROW(reader, parquet::arrow::OpenFile(infile, pool));
std::shared_ptr<arrow::Table> table;
auto read_status = reader->ReadTable(&table);
TEST_EQUAL(read_status.ok(), true)
// Verify number of rows (should equal number of peptide hits, not peptide identifications)
TEST_EQUAL(table->num_rows(), 3)
// Verify number of columns (should include rank column)
TEST_EQUAL(table->num_columns(), 20) // 19 + 1 rank column
// Verify rank column exists and is in the correct position (after precursor_charge)
auto schema = table->schema();
TEST_EQUAL(schema->field(4)->name(), "rank")
// Verify rank values
auto rank_column = table->GetColumnByName("rank");
TEST_NOT_EQUAL(rank_column, nullptr)
auto rank_array = std::static_pointer_cast<arrow::Int32Array>(rank_column->chunk(0));
TEST_EQUAL(rank_array->Value(0), 1) // First hit should have rank 1
TEST_EQUAL(rank_array->Value(1), 2) // Second hit should have rank 2
TEST_EQUAL(rank_array->Value(2), 3) // Third hit should have rank 3
}
END_SECTION
START_SECTION((void store(const String& filename, const std::vector<ProteinIdentification>& protein_identifications, const PeptideIdentificationList& peptide_identifications, bool export_all_psms, const std::set<String>& meta_value_keys)))
{
QuantmsIO file;
// Create test data
vector<ProteinIdentification> protein_ids;
PeptideIdentificationList peptide_ids;
ProteinIdentification protein_id;
protein_id.setIdentifier("test_search");
protein_id.setSearchEngine("TestEngine");
protein_id.setScoreType("TestScore");
protein_id.setHigherScoreBetter(true);
protein_ids.push_back(protein_id);
// Create peptide identification with meta values
PeptideIdentification peptide_id;
peptide_id.setIdentifier("test_search");
peptide_id.setRT(1234.5);
peptide_id.setMZ(500.25);
peptide_id.setScoreType("TestScore");
PeptideHit hit;
hit.setSequence(AASequence::fromString("PEPTIDER"));
hit.setScore(0.95);
hit.setCharge(2);
hit.setMetaValue("target_decoy", "target");
// Add meta values for testing
hit.setMetaValue("confidence", 0.85);
hit.setMetaValue("mass_error", 2.5);
hit.setMetaValue("score_type", String("E-value"));
PeptideEvidence evidence;
evidence.setProteinAccession("TEST_PROTEIN");
hit.setPeptideEvidences(vector<PeptideEvidence>{evidence});
peptide_id.setHits(vector<PeptideHit>{hit});
peptide_ids.push_back(peptide_id);
// Define meta value keys to export
std::set<String> meta_keys = {"confidence", "mass_error", "nonexistent_key"};
String output_file;
NEW_TMP_FILE(output_file)
// Store the data with meta values
file.store(output_file, protein_ids, peptide_ids, false, meta_keys);
// Read back the parquet file
arrow::MemoryPool* pool = arrow::default_memory_pool();
std::shared_ptr<arrow::io::ReadableFile> infile;
auto result = arrow::io::ReadableFile::Open(output_file.c_str());
TEST_EQUAL(result.ok(), true)
infile = result.ValueOrDie();
std::unique_ptr<parquet::arrow::FileReader> reader;
PARQUET_ASSIGN_OR_THROW(reader, parquet::arrow::OpenFile(infile, pool));
std::shared_ptr<arrow::Table> table;
auto read_status = reader->ReadTable(&table);
TEST_EQUAL(read_status.ok(), true)
// Verify number of columns (19 standard + 3 meta value columns)
TEST_EQUAL(table->num_columns(), 22)
// Verify meta value columns exist
auto schema = table->schema();
TEST_EQUAL(schema->field(19)->name(), "confidence")
TEST_EQUAL(schema->field(20)->name(), "mass_error")
TEST_EQUAL(schema->field(21)->name(), "nonexistent_key")
// Verify meta value data and types
auto confidence_column = table->GetColumnByName("confidence");
TEST_NOT_EQUAL(confidence_column, nullptr)
// confidence should be a double array since 0.85 is a double value
auto confidence_array = std::static_pointer_cast<arrow::DoubleArray>(confidence_column->chunk(0));
TEST_EQUAL(confidence_array->Value(0), 0.85)
auto mass_error_column = table->GetColumnByName("mass_error");
TEST_NOT_EQUAL(mass_error_column, nullptr)
// mass_error should be a double array since 2.5 is a double value
auto mass_error_array = std::static_pointer_cast<arrow::DoubleArray>(mass_error_column->chunk(0));
TEST_EQUAL(mass_error_array->Value(0), 2.5)
auto nonexistent_column = table->GetColumnByName("nonexistent_key");
TEST_NOT_EQUAL(nonexistent_column, nullptr)
// nonexistent_key should be string type (default) with null value
auto nonexistent_array = std::static_pointer_cast<arrow::StringArray>(nonexistent_column->chunk(0));
TEST_EQUAL(nonexistent_array->IsNull(0), true)
}
END_SECTION
START_SECTION((Test meta value type detection and proper Arrow column types))
{
QuantmsIO file;
// Create test data with different meta value types
vector<ProteinIdentification> protein_ids;
PeptideIdentificationList peptide_ids;
ProteinIdentification protein_id;
protein_id.setIdentifier("test_search");
protein_id.setSearchEngine("TestEngine");
protein_id.setScoreType("TestScore");
protein_id.setHigherScoreBetter(true);
protein_ids.push_back(protein_id);
// Create peptide identification with different types of meta values
PeptideIdentification peptide_id;
peptide_id.setIdentifier("test_search");
peptide_id.setRT(1234.5);
peptide_id.setMZ(500.25);
peptide_id.setScoreType("TestScore");
PeptideHit hit;
hit.setSequence(AASequence::fromString("PEPTIDER"));
hit.setScore(0.95);
hit.setCharge(2);
hit.setMetaValue("target_decoy", "target");
// Add different types of meta values for testing
hit.setMetaValue("string_value", String("test_string")); // STRING_VALUE
hit.setMetaValue("int_value", 42); // INT_VALUE
hit.setMetaValue("double_value", 3.14159); // DOUBLE_VALUE
hit.setMetaValue("string_list", StringList{"a", "b", "c"}); // STRING_LIST
hit.setMetaValue("int_list", IntList{1, 2, 3}); // INT_LIST
hit.setMetaValue("double_list", DoubleList{1.1, 2.2, 3.3}); // DOUBLE_LIST
PeptideEvidence evidence;
evidence.setProteinAccession("TEST_PROTEIN");
hit.setPeptideEvidences(vector<PeptideEvidence>{evidence});
peptide_id.setHits(vector<PeptideHit>{hit});
peptide_ids.push_back(peptide_id);
// Define meta value keys to export - test all types
std::set<String> meta_keys = {"string_value", "int_value", "double_value", "string_list", "int_list", "double_list"};
String output_file;
NEW_TMP_FILE(output_file)
// Store the data with meta values
file.store(output_file, protein_ids, peptide_ids, false, meta_keys);
// Read back the parquet file
arrow::MemoryPool* pool = arrow::default_memory_pool();
std::shared_ptr<arrow::io::ReadableFile> infile;
auto result = arrow::io::ReadableFile::Open(output_file.c_str());
TEST_EQUAL(result.ok(), true)
infile = result.ValueOrDie();
std::unique_ptr<parquet::arrow::FileReader> reader;
PARQUET_ASSIGN_OR_THROW(reader, parquet::arrow::OpenFile(infile, pool));
std::shared_ptr<arrow::Table> table;
auto read_status = reader->ReadTable(&table);
TEST_EQUAL(read_status.ok(), true)
// Verify number of columns (19 standard + 6 meta value columns)
TEST_EQUAL(table->num_columns(), 25)
// Verify schema types for meta value columns
auto schema = table->schema();
// Check that string_value is utf8 type
auto string_field = schema->GetFieldByName("string_value");
TEST_NOT_EQUAL(string_field, nullptr)
TEST_EQUAL(string_field->type()->id(), arrow::Type::STRING)
// Check that int_value is int64 type
auto int_field = schema->GetFieldByName("int_value");
TEST_NOT_EQUAL(int_field, nullptr)
TEST_EQUAL(int_field->type()->id(), arrow::Type::INT64)
// Check that double_value is float64 type
auto double_field = schema->GetFieldByName("double_value");
TEST_NOT_EQUAL(double_field, nullptr)
TEST_EQUAL(double_field->type()->id(), arrow::Type::DOUBLE)
// Check that string_list is list of string type
auto string_list_field = schema->GetFieldByName("string_list");
TEST_NOT_EQUAL(string_list_field, nullptr)
TEST_EQUAL(string_list_field->type()->id(), arrow::Type::LIST)
// Check that int_list is list of int64 type
auto int_list_field = schema->GetFieldByName("int_list");
TEST_NOT_EQUAL(int_list_field, nullptr)
TEST_EQUAL(int_list_field->type()->id(), arrow::Type::LIST)
// Check that double_list is list of double type
auto double_list_field = schema->GetFieldByName("double_list");
TEST_NOT_EQUAL(double_list_field, nullptr)
TEST_EQUAL(double_list_field->type()->id(), arrow::Type::LIST)
// Verify actual data values
auto string_column = table->GetColumnByName("string_value");
auto string_array = std::static_pointer_cast<arrow::StringArray>(string_column->chunk(0));
TEST_EQUAL(string_array->GetString(0), "test_string")
auto int_column = table->GetColumnByName("int_value");
auto int_array = std::static_pointer_cast<arrow::Int64Array>(int_column->chunk(0));
TEST_EQUAL(int_array->Value(0), 42)
auto double_column = table->GetColumnByName("double_value");
auto double_array = std::static_pointer_cast<arrow::DoubleArray>(double_column->chunk(0));
TEST_REAL_SIMILAR(double_array->Value(0), 3.14159)
}
END_SECTION
START_SECTION((Test meta value type conflict detection throws exception))
{
QuantmsIO file;
// Create test data with type conflicts for the same meta value key
vector<ProteinIdentification> protein_ids;
PeptideIdentificationList peptide_ids;
ProteinIdentification protein_id;
protein_id.setIdentifier("test_search");
protein_id.setSearchEngine("TestEngine");
protein_id.setScoreType("TestScore");
protein_id.setHigherScoreBetter(true);
protein_ids.push_back(protein_id);
// Create two peptide identifications with different types for the same meta value key
PeptideIdentification peptide_id1;
peptide_id1.setIdentifier("test_search");
peptide_id1.setRT(1234.5);
peptide_id1.setMZ(500.25);
peptide_id1.setScoreType("TestScore");
PeptideHit hit1;
hit1.setSequence(AASequence::fromString("PEPTIDER"));
hit1.setScore(0.95);
hit1.setCharge(2);
hit1.setMetaValue("target_decoy", "target");
hit1.setMetaValue("conflicting_value", 42); // INT_VALUE
PeptideEvidence evidence1;
evidence1.setProteinAccession("TEST_PROTEIN_1");
hit1.setPeptideEvidences(vector<PeptideEvidence>{evidence1});
peptide_id1.setHits(vector<PeptideHit>{hit1});
peptide_ids.push_back(peptide_id1);
// Second peptide identification with different type for same key
PeptideIdentification peptide_id2;
peptide_id2.setIdentifier("test_search");
peptide_id2.setRT(1334.5);
peptide_id2.setMZ(600.25);
peptide_id2.setScoreType("TestScore");
PeptideHit hit2;
hit2.setSequence(AASequence::fromString("ALTERNATIVE"));
hit2.setScore(0.85);
hit2.setCharge(2);
hit2.setMetaValue("target_decoy", "target");
hit2.setMetaValue("conflicting_value", String("text")); // STRING_VALUE - conflicts with INT_VALUE above
PeptideEvidence evidence2;
evidence2.setProteinAccession("TEST_PROTEIN_2");
hit2.setPeptideEvidences(vector<PeptideEvidence>{evidence2});
peptide_id2.setHits(vector<PeptideHit>{hit2});
peptide_ids.push_back(peptide_id2);
// Define meta value keys that include the conflicting key
std::set<String> meta_keys = {"conflicting_value"};
String output_file;
NEW_TMP_FILE(output_file)
// This should throw an InvalidParameter exception due to type conflict
TEST_EXCEPTION(Exception::InvalidParameter, file.store(output_file, protein_ids, peptide_ids, false, meta_keys))
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SavitzkyGolayFilter_test.cpp | .cpp | 3,711 | 137 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Eva Lange $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/PROCESSING/SMOOTHING/SavitzkyGolayFilter.h>
#include <OpenMS/KERNEL/Peak2D.h>
///////////////////////////
START_TEST(SavitzkyGolayFilter<D>, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
SavitzkyGolayFilter* dsg_ptr = nullptr;
SavitzkyGolayFilter* dsg_nullPointer = nullptr;
START_SECTION((SavitzkyGolayFilter()))
dsg_ptr = new SavitzkyGolayFilter;
TEST_NOT_EQUAL(dsg_ptr, dsg_nullPointer)
END_SECTION
START_SECTION((virtual ~SavitzkyGolayFilter()))
delete dsg_ptr;
END_SECTION
Param param;
param.setValue("polynomial_order",2);
param.setValue("frame_length",3);
START_SECTION((template < typename PeakType > void filter(MSSpectrum &spectrum)))
MSSpectrum spectrum;
spectrum.resize(5);
MSSpectrum::Iterator it = spectrum.begin();
for (int i=0; i<5; ++i, ++it)
{
it->setIntensity(0.0f);
if (i==2)
{
it->setIntensity(1.0f);
}
}
SavitzkyGolayFilter sgolay;
sgolay.setParameters(param);
sgolay.filter(spectrum);
it=spectrum.begin();
TEST_REAL_SIMILAR(it->getIntensity(),0.0)
++it;
TEST_REAL_SIMILAR(it->getIntensity(),0.0)
++it;
TEST_REAL_SIMILAR(it->getIntensity(),1.0)
++it;
TEST_REAL_SIMILAR(it->getIntensity(),0.0)
++it;
TEST_REAL_SIMILAR(it->getIntensity(),0.0)
END_SECTION
START_SECTION((template <typename PeakType> void filterExperiment(MSExperiment<PeakType>& map)))
TOLERANCE_ABSOLUTE(0.01)
param.setValue("frame_length",4);
PeakMap exp;
exp.resize(4);
Peak1D p;
for (int i=0; i<9; ++i)
{
p.setIntensity(0.0f);
if (i==3)
{
p.setIntensity(1.0f);
}
if (i==4)
{
p.setIntensity(0.8f);
}
if (i==5)
{
p.setIntensity(1.2f);
}
exp[0].push_back(p);
exp[1].push_back(p);
}
exp[2].push_back(p);
SavitzkyGolayFilter sgolay;
sgolay.setParameters(param);
sgolay.filterExperiment(exp);
TEST_EQUAL(exp.size(),4)
TEST_EQUAL(exp[0].size(),9)
TEST_EQUAL(exp[1].size(),9)
TEST_EQUAL(exp[2].size(),1)
TEST_EQUAL(exp[3].size(),0)
TEST_REAL_SIMILAR(exp[0][0].getIntensity(),0.0)
TEST_REAL_SIMILAR(exp[0][1].getIntensity(),0.0571429)
TEST_REAL_SIMILAR(exp[0][2].getIntensity(),0.274286)
TEST_REAL_SIMILAR(exp[0][3].getIntensity(),0.657143)
TEST_REAL_SIMILAR(exp[0][4].getIntensity(),1.14286)
TEST_REAL_SIMILAR(exp[0][5].getIntensity(),0.771429)
TEST_REAL_SIMILAR(exp[0][6].getIntensity(),0.342857)
TEST_REAL_SIMILAR(exp[0][7].getIntensity(),0.0914286)
TEST_REAL_SIMILAR(exp[0][8].getIntensity(),0.0)
TEST_REAL_SIMILAR(exp[1][0].getIntensity(),0.0)
TEST_REAL_SIMILAR(exp[1][1].getIntensity(),0.0571429)
TEST_REAL_SIMILAR(exp[1][2].getIntensity(),0.274286)
TEST_REAL_SIMILAR(exp[1][3].getIntensity(),0.657143)
TEST_REAL_SIMILAR(exp[1][4].getIntensity(),1.14286)
TEST_REAL_SIMILAR(exp[1][5].getIntensity(),0.771429)
TEST_REAL_SIMILAR(exp[1][6].getIntensity(),0.342857)
TEST_REAL_SIMILAR(exp[1][7].getIntensity(),0.0914286)
TEST_REAL_SIMILAR(exp[1][8].getIntensity(),0.0)
TEST_REAL_SIMILAR(exp[2][0].getIntensity(),0.0)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ClusterFunctor_test.cpp | .cpp | 1,831 | 75 | // 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/ClusterFunctor.h>
#include <OpenMS/ML/CLUSTERING/SingleLinkage.h>
#include <OpenMS/ML/CLUSTERING/CompleteLinkage.h>
#include <OpenMS/ML/CLUSTERING/AverageLinkage.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(ClusterFunctor, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION(ClusterFunctor())
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(~ClusterFunctor())
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((ClusterFunctor(const ClusterFunctor &source)))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((ClusterFunctor& operator=(const ClusterFunctor &source)))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((virtual void operator()(DistanceMatrix< float > &original_distance, std::vector<BinaryTreeNode>& cluster_tree, const float threshold=1) const =0))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([ClusterFunctor::InsufficientInput] InsufficientInput(const char *file, int line, const char *function, const char *message="not enough data points to cluster anything")))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([ClusterFunctor::InsufficientInput] virtual ~InsufficientInput()))
{
NOT_TESTABLE
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/GridSearch_test.cpp | .cpp | 1,864 | 60 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/ML/GRIDSEARCH/GridSearch.h>
using namespace OpenMS;
using namespace std;
START_TEST(GridSearch, "$Id$")
START_SECTION(GridSearch lambda)
{
auto evaluator = [](double i, const std::string& j, double k, double l)
{
return i+j.length()+k+l;
};
GridSearch<double, std::string, double, double> gs({1,3,5,2},{"foo","barz"},{2},{3});
std::array<size_t, 4> bestParamIdx{{0u,0u,0u,0u}};
TEST_EQUAL(gs.getNrCombos(), 8)
gs.evaluate(evaluator, -1.0, bestParamIdx);
TEST_EQUAL(get<0>(bestParamIdx),2)
TEST_EQUAL(get<1>(bestParamIdx),1)
TEST_EQUAL(get<2>(bestParamIdx),0)
TEST_EQUAL(get<3>(bestParamIdx),0)
}
END_SECTION
START_SECTION(GridSearch Functor)
{
struct Evaluator
{
double operator()(double i, const std::string& j, double k, double l)
{
return i+j.length()+k+l;
};
};
GridSearch<double, std::string, double, double> gs({1,3,5,2},{"foo","barz"},{2},{3});
std::array<size_t, 4> bestParamIdx{{0u,0u,0u,0u}};
TEST_EQUAL(gs.getNrCombos(), 8)
gs.evaluate(Evaluator(), -1.0, bestParamIdx);
TEST_EQUAL(get<0>(bestParamIdx),2)
TEST_EQUAL(get<1>(bestParamIdx),1)
TEST_EQUAL(get<2>(bestParamIdx),0)
TEST_EQUAL(get<3>(bestParamIdx),0)
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MassDecomposition_test.cpp | .cpp | 6,088 | 224 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/MassDecomposition.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MassDecomposition, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MassDecomposition* ptr = nullptr;
MassDecomposition* nullPointer = nullptr;
START_SECTION(MassDecomposition())
{
ptr = new MassDecomposition();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~MassDecomposition())
{
delete ptr;
}
END_SECTION
START_SECTION((MassDecomposition(const MassDecomposition &deco)))
{
MassDecomposition md("C3 M4 S200");
TEST_EQUAL(md.getNumberOfMaxAA(), 200)
TEST_STRING_EQUAL(md.toString(), "C3 M4 S200")
MassDecomposition md2(md);
TEST_EQUAL(md2.getNumberOfMaxAA(), 200)
TEST_STRING_EQUAL(md2.toString(), "C3 M4 S200")
}
END_SECTION
START_SECTION((MassDecomposition(const String &deco)))
{
MassDecomposition md("C3 M4 S200");
TEST_EQUAL(md.getNumberOfMaxAA(), 200)
TEST_STRING_EQUAL(md.toString(), "C3 M4 S200")
}
END_SECTION
START_SECTION((MassDecomposition& operator=(const MassDecomposition &rhs)))
{
MassDecomposition md("C3 M4 S200");
MassDecomposition md2;
md2 = md;
TEST_EQUAL(md2.getNumberOfMaxAA(), 200)
TEST_STRING_EQUAL(md2.toString(), "C3 M4 S200")
}
END_SECTION
START_SECTION((MassDecomposition& operator+=(const MassDecomposition &d)))
{
MassDecomposition md;
MassDecomposition md1("C3");
MassDecomposition md2("M4");
MassDecomposition md3("S200");
md += md1;
TEST_EQUAL(md.getNumberOfMaxAA(), 3)
TEST_STRING_EQUAL(md.toString(), "C3")
md += md2;
TEST_EQUAL(md.getNumberOfMaxAA(), 4)
TEST_STRING_EQUAL(md.toString(), "C3 M4")
md += md3;
TEST_EQUAL(md.getNumberOfMaxAA(), 200)
TEST_STRING_EQUAL(md.toString(), "C3 M4 S200")
}
END_SECTION
START_SECTION((String toString() const ))
{
MassDecomposition md1("C3");
MassDecomposition md2("C3 M4");
MassDecomposition md3("C3 M4 S200");
TEST_EQUAL(md1.getNumberOfMaxAA(), 3)
TEST_STRING_EQUAL(md1.toString(), "C3")
TEST_EQUAL(md2.getNumberOfMaxAA(), 4)
TEST_STRING_EQUAL(md2.toString(), "C3 M4")
TEST_EQUAL(md3.getNumberOfMaxAA(), 200)
TEST_STRING_EQUAL(md3.toString(), "C3 M4 S200")
}
END_SECTION
START_SECTION((String toExpandedString() const ))
{
MassDecomposition md1("C3");
MassDecomposition md2("C3 M4");
TEST_STRING_EQUAL(md1.toExpandedString(), "CCC")
TEST_STRING_EQUAL(md2.toExpandedString(), "CCCMMMM")
}
END_SECTION
START_SECTION((MassDecomposition operator+(const MassDecomposition &rhs) const ))
{
MassDecomposition md;
MassDecomposition md1("C3");
MassDecomposition md2("M4");
MassDecomposition md3("S200");
MassDecomposition md5 = md + md1;
TEST_EQUAL(md5.getNumberOfMaxAA(), 3)
TEST_STRING_EQUAL(md5.toString(), "C3")
MassDecomposition md6 = md1 + md2;
TEST_EQUAL(md6.getNumberOfMaxAA(), 4)
TEST_STRING_EQUAL(md6.toString(), "C3 M4")
MassDecomposition md7 = md1 + md2 + md3;
TEST_EQUAL(md7.getNumberOfMaxAA(), 200)
TEST_STRING_EQUAL(md7.toString(), "C3 M4 S200")
}
END_SECTION
START_SECTION((Size getNumberOfMaxAA() const ))
{
MassDecomposition md;
MassDecomposition md1("C3");
MassDecomposition md2("M4");
MassDecomposition md3("S200");
md += md1;
TEST_EQUAL(md.getNumberOfMaxAA(), 3)
TEST_STRING_EQUAL(md.toString(), "C3")
md += md2;
TEST_EQUAL(md.getNumberOfMaxAA(), 4)
TEST_STRING_EQUAL(md.toString(), "C3 M4")
md += md3;
TEST_EQUAL(md.getNumberOfMaxAA(), 200)
TEST_STRING_EQUAL(md.toString(), "C3 M4 S200")
}
END_SECTION
START_SECTION((bool operator<(const MassDecomposition &rhs) const ))
{
MassDecomposition md;
MassDecomposition md1("C3");
MassDecomposition md2("M4");
md += md1;
TEST_EQUAL(md2 < md1, false)
TEST_EQUAL(md < md2, true)
md += md2;
TEST_EQUAL(md < md2, true)
}
END_SECTION
START_SECTION((bool operator==(const String &deco) const ))
{
MassDecomposition md;
MassDecomposition md1("C3");
TEST_EQUAL(md == md1.toString(), false)
MassDecomposition md2("M4");
md = md2;
TEST_STRING_EQUAL(md2.toString(), "M4")
TEST_EQUAL(md == md2.toString(), true)
MassDecomposition md3("S200");
md = md2 + md3;
TEST_EQUAL(md == md3.toString(), false)
}
END_SECTION
START_SECTION((bool containsTag(const String &tag) const ))
{
MassDecomposition md;
MassDecomposition md1("C3");
MassDecomposition md2("C3 M4");
MassDecomposition md3("C3 M4 S200");
TEST_EQUAL(md.containsTag("C"), false)
TEST_EQUAL(md.containsTag("CCC"), false)
TEST_EQUAL(md1.containsTag("CCC"), true)
TEST_EQUAL(md1.containsTag("CCCC"), false)
TEST_EQUAL(md2.containsTag("CMC"), true)
TEST_EQUAL(md3.containsTag("CCCSSMSSSSSSSSSSSSSSM"), true)
}
END_SECTION
START_SECTION((bool compatible(const MassDecomposition &deco) const ))
{
MassDecomposition md;
MassDecomposition md1("C3");
MassDecomposition md2("C3 M4");
MassDecomposition md3("C3 M4 S200");
MassDecomposition md4("M4 S200");
MassDecomposition md5("C3 S200");
MassDecomposition md6("S2");
TEST_EQUAL(md.compatible(MassDecomposition("")), true)
TEST_EQUAL(md.compatible(MassDecomposition("C1")), false)
TEST_EQUAL(md1.compatible(MassDecomposition("C1")), true)
TEST_EQUAL(md2.compatible(MassDecomposition("C2 M4")), true)
TEST_EQUAL(md2.compatible(MassDecomposition("C2 M5")), false)
TEST_EQUAL(md3.compatible(md5), true)
TEST_EQUAL(md3.compatible(md2), true)
TEST_EQUAL(md3.compatible(md6), true)
TEST_EQUAL(md3.compatible(md4), true)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MultiplexFilteringProfile_test.cpp | .cpp | 4,490 | 94 | // 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/MultiplexFilteringProfile.h>
#include <OpenMS/FEATUREFINDER/MultiplexFilteredMSExperiment.h>
#include <OpenMS/FORMAT/MzMLFile.h>
using namespace OpenMS;
START_TEST(MultiplexFilteringProfile, "$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<std::vector<PeakPickerHiRes::PeakBoundary> > boundaries_exp_s;
std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > boundaries_exp_c;
MSExperiment exp_picked;
picker.pickExperiment(exp, exp_picked, boundaries_exp_s, boundaries_exp_c);
// set parameters
int charge_min = 1;
int charge_max = 4;
int isotopes_per_peptide_min = 3;
int isotopes_per_peptide_max = 6;
double intensity_cutoff = 10.0;
double rt_band = 3;
double mz_tolerance = 40;
bool mz_tolerance_unit = true; // ppm (true), Da (false)
double peptide_similarity = 0.8;
double averagine_similarity = 0.75;
double averagine_similarity_scaling = 0.75;
String averagine_type="peptide";
// construct list of peak patterns
MultiplexDeltaMasses shifts1;
shifts1.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(0, "no_label"));
shifts1.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(8.0443702794, "Arg8"));
MultiplexDeltaMasses shifts2;
shifts2.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(0, "no_label"));
MultiplexDeltaMasses::LabelSet label_set;
label_set.insert("Arg8");
label_set.insert("Arg8");
shifts2.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(2*8.0443702794, label_set));
std::vector<MultiplexIsotopicPeakPattern> patterns;
for (int c = charge_max; c >= charge_min; --c)
{
MultiplexIsotopicPeakPattern pattern1(c, isotopes_per_peptide_max, shifts1, 0);
patterns.push_back(pattern1);
MultiplexIsotopicPeakPattern pattern2(c, isotopes_per_peptide_max, shifts2, 1);
patterns.push_back(pattern2);
}
MultiplexFilteringProfile* nullPointer = nullptr;
MultiplexFilteringProfile* ptr;
START_SECTION(MultiplexFilteringProfile(MSExperiment& exp_profile, const MSExperiment& exp_picked, const std::vector<std::vector<PeakPickerHiRes::PeakBoundary> >& boundaries, 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"))
MultiplexFilteringProfile filtering(exp, exp_picked, boundaries_exp_s, patterns, isotopes_per_peptide_min, isotopes_per_peptide_max, intensity_cutoff, rt_band, mz_tolerance, mz_tolerance_unit, peptide_similarity, averagine_similarity, averagine_similarity_scaling, averagine_type);
ptr = new MultiplexFilteringProfile(exp, exp_picked, boundaries_exp_s, patterns, isotopes_per_peptide_min, isotopes_per_peptide_max, intensity_cutoff, rt_band, mz_tolerance, mz_tolerance_unit, peptide_similarity, averagine_similarity, averagine_similarity_scaling, averagine_type);
TEST_NOT_EQUAL(ptr, nullPointer);
delete ptr;
END_SECTION
MultiplexFilteringProfile filtering(exp, exp_picked, boundaries_exp_s, patterns, isotopes_per_peptide_min, isotopes_per_peptide_max, intensity_cutoff, rt_band, mz_tolerance, mz_tolerance_unit, peptide_similarity, averagine_similarity, averagine_similarity_scaling, averagine_type);
START_SECTION(std::vector<MultiplexFilterResult> filter())
std::vector<MultiplexFilteredMSExperiment> results = filtering.filter();
TEST_EQUAL(results[0].size(), 0);
TEST_EQUAL(results[1].size(), 0);
TEST_EQUAL(results[2].size(), 0);
TEST_EQUAL(results[3].size(), 0);
TEST_EQUAL(results[4].size(), 4);
TEST_EQUAL(results[5].size(), 5);
TEST_EQUAL(results[6].size(), 4);
TEST_EQUAL(results[7].size(), 0);
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IndexedMzMLDecoder_test.cpp | .cpp | 2,486 | 73 | // 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/IndexedMzMLDecoder.h>
///////////////////////////
#define MULTI_LINE_STRING(...) #__VA_ARGS__
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(IndexedMzMLDecoder, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IndexedMzMLDecoder* ptr = nullptr;
IndexedMzMLDecoder* nullPointer = nullptr;
START_SECTION((IndexedMzMLDecoder()))
ptr = new IndexedMzMLDecoder;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~IndexedMzMLDecoder()))
delete ptr;
END_SECTION
START_SECTION((int parseOffsets(String filename, std::streampos indexoffset, OffsetVector & spectra_offsets, OffsetVector& chromatograms_offsets)))
// see also IndexedMzMLFile_test.cpp
std::streampos res = IndexedMzMLDecoder().findIndexListOffset(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
TEST_NOT_EQUAL(res, -1)
IndexedMzMLDecoder::OffsetVector spectra_offsets;
IndexedMzMLDecoder::OffsetVector chromatograms_offsets;
int off = IndexedMzMLDecoder().parseOffsets(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), res, spectra_offsets, chromatograms_offsets);
TEST_EQUAL(off, 0)
TEST_EQUAL(spectra_offsets.size(), 2)
TEST_EQUAL(chromatograms_offsets.size(), 1)
END_SECTION
START_SECTION((std::streampos findIndexListOffset(String filename, int buffersize = 1023)))
// see also IndexedMzMLFile_test.cpp
//
std::streampos res = IndexedMzMLDecoder().findIndexListOffset(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"));
TEST_NOT_EQUAL(res, -1)
// A std::streamoff value of -1 is also used to represent error conditions by some of the I/O library functions.
std::streampos nonindex = IndexedMzMLDecoder().findIndexListOffset(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"));
TEST_EQUAL(nonindex, -1)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/TOPPBase_test.cpp | .cpp | 30,595 | 857 | // 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, Stephan Aiche $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/DATASTRUCTURES/ListUtilsIO.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <cstdlib>
#include <QStringList>
///////////////////////////
using namespace OpenMS;
using namespace std;
//test class with optional parameters
class TOPPBaseTest
: public TOPPBase
{
public:
TOPPBaseTest()
: TOPPBase("TOPPBaseTest", "A test class", false, {}, false)
{
char* var = (char*)("OPENMS_DISABLE_UPDATE_CHECK=ON");
#ifdef OPENMS_WINDOWSPLATFORM
_putenv(var);
#else
putenv(var);
#endif
main(0,nullptr);
}
TOPPBaseTest(int argc ,const char** argv)
: TOPPBase("TOPPBaseTest", "A test class", false, {}, false)
{
char* var = (char*)("OPENMS_DISABLE_UPDATE_CHECK=ON");
#ifdef OPENMS_WINDOWSPLATFORM
_putenv(var);
#else
putenv(var);
#endif
main(argc,argv);
}
void registerOptionsAndFlags_() override
{
registerStringOption_("stringoption","<string>","string default","string description",false);
registerIntOption_("intoption","<int>",4711,"int description",false);
registerDoubleOption_("doubleoption","<double>",0.4711,"double description",false);
registerIntList_("intlist","<intlist>",ListUtils::create<Int>("1,2,3,4"),"intlist description",false);
registerDoubleList_("doublelist","<doublelist>", ListUtils::create<double>("0.4711,1.022,4.0"),"doubelist description",false);
registerStringList_("stringlist","<stringlist>", ListUtils::create<String>("abc,def,ghi,jkl"),"stringlist description",false);
registerFlag_("flag","flag description");
//for testing write_ini parameter (and with it setDefaults)
registerStringList_("stringlist2","<stringlist>", ListUtils::create<String>("hopla,dude"),"stringlist with restrictions",false);
vector<String> rest;
rest.push_back("hopla");
rest.push_back("dude");
setValidStrings_("stringlist2",rest);
registerIntList_("intlist2","<int>",ListUtils::create<Int>("3,4,5"),"intlist with restrictions",false);
setMinInt_("intlist2",2);
setMaxInt_("intlist2",6);
registerDoubleList_("doublelist2","<double>", ListUtils::create<double>("1.2,2.33"),"doublelist with restrictions",false);
setMinFloat_("doublelist2",0.2);
setMaxFloat_("doublelist2",5.4);
}
String getStringOption(const String& name) const
{
return getStringOption_(name);
}
double getDoubleOption(const String& name) const
{
return getDoubleOption_(name);
}
Int getIntOption(const String& name) const
{
return getIntOption_(name);
}
StringList getStringList(const String& name) const
{
return getStringList_(name);
}
IntList getIntList(const String& name) const
{
return getIntList_(name);
}
DoubleList getDoubleList(const String& name) const
{
return getDoubleList_(name);
}
Param const& getParam() const
{
return getParam_();
}
bool getFlag(const String& name) const
{
return getFlag_(name);
}
ExitCodes main_(int /*argc*/ , const char** /*argv*/) override
{
return EXECUTION_OK;
}
String const& getIniLocation() const
{
return getIniLocation_();
}
void inputFileReadable(const String& filename, const String& param_name) const
{
inputFileReadable_(filename, param_name);
}
void outputFileWritable(const String& filename, const String& param_name) const
{
outputFileWritable_(filename, param_name);
}
void addDataProcessing(PeakMap& map, DataProcessing::ProcessingAction action)
{
DataProcessing dp = getProcessingInfo_(action);
addDataProcessing_(map, dp);
//additionally test FeatureMap and ConsensusMap
FeatureMap f_map;
addDataProcessing_(f_map, dp);
ConsensusMap c_map;
addDataProcessing_(c_map, dp);
}
bool parseRange(const String& text, double& low, double& high) const
{
return parseRange_(text, low, high);
}
TOPPBase::ExitCodes runExternalProcess(const QString& executable, const QStringList& arguments, const QString& workdir) const
{
return runExternalProcess_(executable, arguments, workdir);
}
};
// Test class for no-optional parameters
class TOPPBaseTestNOP
: public TOPPBase
{
public:
TOPPBaseTestNOP()
: TOPPBase("TOPPBaseTestNOP", "A test class with non-optional parameters", false, {}, false)
{
char* var = (char*)("OPENMS_DISABLE_UPDATE_CHECK=ON");
#ifdef OPENMS_WINDOWSPLATFORM
_putenv(var);
#else
putenv(var);
#endif
main(0,nullptr);
}
TOPPBaseTestNOP(int argc , const char** argv)
: TOPPBase("TOPPBaseTestNOP", "A test class with non-optional parameters", false, {}, false)
{
char* var = (char*)("OPENMS_DISABLE_UPDATE_CHECK=ON");
#ifdef OPENMS_WINDOWSPLATFORM
_putenv(var);
#else
putenv(var);
#endif
main(argc,argv);
}
void registerOptionsAndFlags_() override
{
registerStringOption_("stringoption","<string>","","string description");
registerIntOption_("intoption","<int>",0,"int description",false);
registerDoubleOption_("doubleoption","<double>", -1.0,"double description", false);
registerFlag_("flag","flag description");
registerStringList_("stringlist","<stringlist>", ListUtils::create<String>(""),"stringlist description");
registerIntList_("intlist","<intlist>",ListUtils::create<Int>(""),"intlist description");
registerDoubleList_("doublelist","<doublelist>", ListUtils::create<double>(""),"doubelist description");
}
String getStringOption(const String& name) const
{
return getStringOption_(name);
}
double getDoubleOption(const String& name) const
{
return getDoubleOption_(name);
}
Int getIntOption(const String& name) const
{
return getIntOption_(name);
}
StringList getStringList(const String& name) const
{
return getStringList_(name);
}
IntList getIntList(const String& name) const
{
return getIntList_(name);
}
DoubleList getDoubleList(const String& name) const
{
return getDoubleList_(name);
}
ExitCodes main_(int /*argc*/ , const char** /*argv*/) override
{
return EXECUTION_OK;
}
};
// Test class for parameters derived from a Param object
class TOPPBaseTestParam: public TOPPBase
{
public:
TOPPBaseTestParam(const Param& param):
TOPPBase("TOPPBaseTestParam", "A test class with parameters derived from Param", false, {}, false), test_param_(param)
{
static char* var = (char *)("OPENMS_DISABLE_UPDATE_CHECK=ON");
#ifdef OPENMS_WINDOWSPLATFORM
_putenv(var);
#else
putenv(var);
#endif
main(0, nullptr);
}
void registerOptionsAndFlags_() override
{
registerFullParam_(test_param_);
}
ExitCodes main_(int /*argc*/ , const char** /*argv*/) override
{
return EXECUTION_OK;
}
const Param& getParam() const
{
return getParam_();
}
private:
Param test_param_;
};
//test class with optional parameters
class TOPPBaseCmdParseTest
: public TOPPBase
{
public:
TOPPBaseCmdParseTest()
: TOPPBase("TOPPBaseCmdParseTest", "A test class to test parts of the cmd parser functionality", false, {}, false)
{}
void registerOptionsAndFlags_() override
{
}
ExitCodes run(int argc , const char** argv)
{
static char* var = (char *)("OPENMS_DISABLE_UPDATE_CHECK=ON");
#ifdef OPENMS_WINDOWSPLATFORM
_putenv(var);
#else
putenv(var);
#endif
return main(argc, argv);
}
ExitCodes main_(int /*argc*/ , const char** /*argv*/) override
{
static char* var = (char *)("OPENMS_DISABLE_UPDATE_CHECK=ON");
#ifdef OPENMS_WINDOWSPLATFORM
_putenv(var);
#else
putenv(var);
#endif
return EXECUTION_OK;
}
};
//test class with optional parameters
class TOPPBaseCmdParseSubsectionsTest
: public TOPPBase
{
public:
TOPPBaseCmdParseSubsectionsTest()
: TOPPBase("TOPPBaseCmdParseSubsectionsTest", "A test class to test parts of the cmd parser functionality", false, {}, false)
{}
void registerOptionsAndFlags_() override
{
registerStringOption_("stringoption","<string>","","string description");
registerSubsection_("algorithm", "Algorithm parameters section");
registerSubsection_("other", "Other parameters section");
}
Param getSubsectionDefaults_(const String & section) const override
{
Param p;
if (section == "algorithm")
{
p.setValue("param1", "param1_value", "param1_description");
p.setValue("param2", "param2_value", "param2_description");
}
else // "other"
{
p.setValue("param3", "param3_value", "param3_description");
p.setValue("param4", "param4_value", "param4_description");
p.setValue("flagparam", "false", "this will be a flag");
p.setValidStrings("flagparam", {"true","false"});
p.setValue("nonflagparam", "true", "this will be a string param with true/false");
p.setValidStrings("nonflagparam", {"true","false"});
}
return p;
}
ExitCodes run(int argc , const char** argv)
{
static char* var = (char *)("OPENMS_DISABLE_UPDATE_CHECK=ON");
#ifdef OPENMS_WINDOWSPLATFORM
_putenv(var);
#else
putenv(var);
#endif
return main(argc, argv);
}
ExitCodes main_(int /*argc*/ , const char** /*argv*/) override
{
return EXECUTION_OK;
}
String getStringOption(String name)
{
return getStringOption_(name);
}
Param getParam()
{
return getParam_();
}
};
/////////////////////////////////////////////////////////////
START_TEST(TOPPBase, "$Id$");
/////////////////////////////////////////////////////////////
TOPPBaseTest* ptr = nullptr;
TOPPBaseTest* nullPointer = nullptr;
START_SECTION(TOPPBase(const String& name, const String& description, bool official = true, const std::vector<Citation>& citations = {}, bool toolhandler_test = true))
ptr = new TOPPBaseTest();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~TOPPBase()))
delete ptr;
END_SECTION
START_SECTION((ExitCodes main(int argc, const char**argv)))
NOT_TESTABLE
// is tested implicitly in all tests
END_SECTION
//parts to build command lines
const char* a1 ="TOPPBaseTest";
const char* a3 ="-ini";
const char* a5 ="-instance";
const char* a6 ="6";
// needed to get the correct pathes
char* a7;
std::string temp_a7(OPENMS_GET_TEST_DATA_PATH("TOPPBase_toolcommon.ini"));
a7 = new char[temp_a7.size() + 1];
strcpy(a7, temp_a7.c_str());
//
char* a8;
std::string temp_a8(OPENMS_GET_TEST_DATA_PATH("TOPPBase_common.ini"));
a8 = new char[temp_a8.size() + 1];
strcpy(a8, temp_a8.c_str());
//
const char* a9 ="5";
const char* a10 ="-stringoption";
const char* a11 ="-flag";
const char* a12 ="commandline";
const char* a13 ="4.5";
const char* a14 ="-intoption";
const char* a15 ="-doubleoption";
const char* a16 ="4711";
const char* a17 ="-stringlist";
const char* a18 ="-intlist";
const char* a19 ="-doublelist";
const char* a20 ="0.411";
const char* a21 = "-write_ini";
const char* test = "-test";
START_SECTION(([EXTRA]String const& getIniLocation_() const))
//default
TOPPBaseTest tmp;
TEST_EQUAL(tmp.getIniLocation(),"TOPPBaseTest:1:")
//command line
const char* instance_cl[3] = {a1, a5, a9}; //command line: "TOPPBaseTest -instance 5"
TOPPBaseTest tmp2(3,instance_cl);
TEST_EQUAL(tmp2.getIniLocation(),"TOPPBaseTest:5:")
END_SECTION
START_SECTION(([EXTRA]String getStringOption_(const String& name) const))
//default
TOPPBaseTest tmp;
TEST_EQUAL(tmp.getStringOption("stringoption"),"string default");
//command line
const char* string_cl[3] = {a1, a10, a12}; //command line: "TOPPBaseTest -stringoption commandline"
TOPPBaseTest tmp2(3,string_cl);
TEST_EQUAL(tmp2.getStringOption("stringoption"),"commandline");
//command line (when there is a ini file value too)
const char* both_cl[5] = {a1, a10, a12, a3, a7}; //command line: "TOPPBaseTest -stringoption commandline -ini data/TOPPBase_toolcommon.ini"
TOPPBaseTest tmp3(5,both_cl);
TEST_EQUAL(tmp3.getStringOption("stringoption"),DataValue("commandline"));
//ini file: instance section
const char* common_cl[3] = {a1, a3, a7}; //command line: "TOPPBaseTest -ini data/TOPPBase_toolcommon.ini"
TOPPBaseTest tmp4(3,common_cl);
TEST_EQUAL(tmp4.getStringOption("stringoption"),DataValue("instance1"));
const char* common5_cl[5] = {a1, a3, a7, a5, a9}; //command line: "TOPPBaseTest -ini data/TOPPBase_toolcommon.ini -instance 5"
TOPPBaseTest tmp5(5,common5_cl);
TEST_EQUAL(tmp5.getStringOption("stringoption"),DataValue("instance5"));
//ini file: tool common section
const char* common6_cl[5] = {a1, a3, a7, a5, a6}; //command line: "TOPPBaseTest -ini data/TOPPBase_toolcommon.ini -instance 6"
TOPPBaseTest tmp6(5,common6_cl);
TEST_EQUAL(tmp6.getStringOption("stringoption"),DataValue("toolcommon"));
//ini file: common section
const char* common7_cl[5] = {a1, a3, a8, a5, a6}; //command line: "TOPPBaseTest -ini data/TOPPBase_common.ini -instance 6"
TOPPBaseTest tmp7(5,common7_cl);
TEST_EQUAL(tmp7.getStringOption("stringoption"),DataValue("common"));
TEST_EXCEPTION(Exception::WrongParameterType,tmp2.getStringOption("doubleoption"));
TEST_EXCEPTION(Exception::UnregisteredParameter,tmp2.getStringOption("imleeewenit"));
//missing required parameters
const char* string_cl2[2] = {a1, a11}; // TOPPBaseTest -flag
TOPPBaseTestNOP tmp8(2,string_cl2);
TEST_EXCEPTION(Exception::RequiredParameterNotGiven,tmp8.getStringOption("stringoption"));
//test option write_ini
String filename;
NEW_TMP_FILE(filename);
const char* f_name = filename.c_str();
const char* write_ini[3]={a1, a21, f_name};
TOPPBaseTest tmp9(3, write_ini);
Param p1, p2;
ParamXMLFile paramFile;
paramFile.load(filename, p1);
//remove id pool (the path is dependent on the installation path)
p1.remove("TOPPBaseTest:1:id_pool");
//every parameter except for help,ini.instance, write_ini and write_wsdl
//toolname : TOPPBaseTest
p2.setValue("TOPPBaseTest:version",VersionInfo::getVersion());
p2.setValue("TOPPBaseTest:1:stringoption","string default","string description");
p2.setValue("TOPPBaseTest:1:intoption",4711,"int description");
p2.setValue("TOPPBaseTest:1:doubleoption",0.4711,"double description");
p2.setValue("TOPPBaseTest:1:intlist",ListUtils::create<Int>("1,2,3,4"),"intlist description");
p2.setValue("TOPPBaseTest:1:doublelist", ListUtils::create<double>("0.4711,1.022,4.0"),"doubelist description");
p2.setValue("TOPPBaseTest:1:stringlist", std::vector<std::string>{"abc","def","ghi","jkl"},"stringlist description");
p2.setValue("TOPPBaseTest:1:flag","false","flag description");
p2.setValue("TOPPBaseTest:1:log","","Name of log file (created only when specified)");
p2.setValue("TOPPBaseTest:1:debug",0,"Sets the debug level");
p2.setValue("TOPPBaseTest:1:threads",1, "Sets the number of threads allowed to be used by the TOPP tool");
p2.setValue("TOPPBaseTest:1:no_progress","false","Disables progress logging to command line");
p2.setValue("TOPPBaseTest:1:force","false","Overwrite tool specific checks.");
p2.setValue("TOPPBaseTest:1:test","false","Enables the test mode (needed for software testing only)");
//with restriction
p2.setValue("TOPPBaseTest:1:stringlist2", std::vector<std::string>{"hopla","dude"},"stringlist with restrictions");
vector<std::string> rest = {"hopla","dude"};
String stringlist2 = "TOPPBaseTest:1:stringlist2";
p2.setValidStrings(stringlist2,rest);
String intlist2 = "TOPPBaseTest:1:intlist2";
String doublelist2 = "TOPPBaseTest:1:doublelist2";
p2.setValue(intlist2,ListUtils::create<Int>("3,4,5"),"intlist with restriction");
p2.setMinInt(intlist2,2);
p2.setMaxInt(intlist2,6);
p2.setValue(doublelist2, ListUtils::create<double>("1.2,2.33"),"doubelist with restrictions");
p2.setMinFloat(doublelist2,0.2);
p2.setMaxFloat(doublelist2,5.4);
TEST_EQUAL(p1,p2)
WHITELIST("version")
TEST_FILE_SIMILAR(filename, OPENMS_GET_TEST_DATA_PATH("TOPPBase_test_write_ini_out.ini"))
String filename2;
NEW_TMP_FILE(filename2);
const char* f_name2 = filename2.c_str();
const char* b = "TOPPBaseCmdParseSubsectionsTest";
const char* write_ini2[3]={b, a21, f_name2};
TOPPBaseCmdParseSubsectionsTest tmp10{};
tmp10.run(3, write_ini2);
TEST_FILE_SIMILAR(filename2, OPENMS_GET_TEST_DATA_PATH("TOPPBase_test_write_ini_subsec_out.ini"))
END_SECTION
START_SECTION(([EXTRA]String getIntOption_(const String& name) const))
//default
TOPPBaseTest tmp;
TEST_EQUAL(tmp.getIntOption("intoption"),4711);
//command line
const char* string_cl[3] = {a1, a14, a6}; //command line: "TOPPBaseTest -intoption 6"
TOPPBaseTest tmp2(3,string_cl);
TEST_EQUAL(tmp2.getIntOption("intoption"),6);
TEST_EXCEPTION(Exception::WrongParameterType,tmp2.getIntOption("doubleoption"));
TEST_EXCEPTION(Exception::UnregisteredParameter,tmp2.getIntOption("imleeewenit"));
//missing required parameters
//-> not testable, as ints cannot be made 'required' (no NAN supported)
END_SECTION
START_SECTION(([EXTRA]String getDoubleOption_(const String& name) const))
//default
TOPPBaseTest tmp;
TEST_REAL_SIMILAR(tmp.getDoubleOption("doubleoption"),0.4711);
//command line
const char* string_cl[3] = {a1, a15, a13}; //command line: "TOPPBaseTest -doubleoption 4.5"
TOPPBaseTest tmp2(3,string_cl);
TEST_REAL_SIMILAR(tmp2.getDoubleOption("doubleoption"),4.5);
TEST_EXCEPTION(Exception::WrongParameterType,tmp2.getDoubleOption("intoption"));
TEST_EXCEPTION(Exception::UnregisteredParameter,tmp2.getDoubleOption("imleeewenit"));
END_SECTION
START_SECTION(([EXTRA] String getIntList_(const String& name) const))
//default
TOPPBaseTest tmp;
TEST_EQUAL(tmp.getIntList("intlist") == ListUtils::create<Int>("1,2,3,4"), true)
//command line
const char* string_cl[5]={a1, a18, a6 ,a9 ,a16}; //commandline: "TOPPBaseTest -intlist 6 5 4711"
TOPPBaseTest tmp2(5, string_cl);
TEST_EQUAL(tmp2.getIntList("intlist") == ListUtils::create<Int>("6,5,4711"), true)
const char* string_cl1[3]={a1, a18, a6}; //commandline: "TOPPBaseTest -intlist 6"
TOPPBaseTest tmp3(3, string_cl1);
TEST_EQUAL(tmp3.getIntList("intlist") == ListUtils::create<Int>("6"), true)
TEST_EXCEPTION(Exception::WrongParameterType,tmp2.getIntList("intoption"));
TEST_EXCEPTION(Exception::UnregisteredParameter,tmp2.getIntList("imleeewenit"));
//missing required parameters
const char* string_cl2[2] = {a1, a11};
TOPPBaseTestNOP tmp4(2,string_cl2);
TEST_EXCEPTION(Exception::RequiredParameterNotGiven,tmp4.getIntList("intlist"));
END_SECTION
START_SECTION(([EXTRA] String getDoubleList_(const String& name) const))
//default
TOPPBaseTest tmp;
TEST_EQUAL(tmp.getDoubleList("doublelist") == ListUtils::create<double>("0.4711,1.022,4.0"), true)
//command line
const char* string_cl[3]={a1, a19, a20}; //commandline:"TOPPBaseTest -doublelist 0.411"
TOPPBaseTest tmp2(3, string_cl);
TEST_EQUAL(tmp2.getDoubleList("doublelist") == ListUtils::create<double>("0.411"), true)
const char* a210 = "4.0";
const char* string_cl2[5]={a1, a19, a20, a13, a210};//commandline :"TOPPBaseTest -doublelist 0.411 4.5 4.0
TOPPBaseTest tmp3(5,string_cl2);
TEST_EQUAL(tmp3.getDoubleList("doublelist") == ListUtils::create<double>("0.411,4.5,4.0"), true)
const char* string_cl21[4]={a1,a19,a20,a13};//commandline :"TOPPBaseTest -doublelist 0.411 4.5
TOPPBaseTest tmp31(4,string_cl21);
TEST_EQUAL(tmp31.getDoubleList("doublelist") == ListUtils::create<double>("0.411,4.5"), true)
TEST_EXCEPTION(Exception::WrongParameterType,tmp2.getDoubleList("intoption"));
TEST_EXCEPTION(Exception::UnregisteredParameter,tmp2.getDoubleList("imleeewenit"));
//missing required parameters
const char* string_cl3[2] = {a1, a11};
TOPPBaseTestNOP tmp4(2,string_cl3);
TEST_EXCEPTION(Exception::RequiredParameterNotGiven,tmp4.getDoubleList("doublelist"));
END_SECTION
START_SECTION(([EXTRA] String getStringList_(const String& name) const))
//default
TOPPBaseTest tmp;
TEST_EQUAL(tmp.getStringList("stringlist") == ListUtils::create<String>("abc,def,ghi,jkl"), true)
//command line
const char* string_cl[3]={a1,a17,a12}; //commandline: "TOPPBaseTest -stringlist conmandline"
TOPPBaseTest tmp2(3, string_cl);
TEST_EQUAL(tmp2.getStringList("stringlist") == ListUtils::create<String>("commandline"), true)
const char* string_cl2[5]={a1,a17,a12,a7, a8}; //commandline: "TOPPBaseTest -stringlist conmandline data/TOPPBase_toolcommon.ini data/TOPPBase_common.ini"
TOPPBaseTest tmp3(5, string_cl2);
StringList tmp_stringlist;
tmp_stringlist << "commandline";
tmp_stringlist << OPENMS_GET_TEST_DATA_PATH("TOPPBase_toolcommon.ini");
tmp_stringlist << OPENMS_GET_TEST_DATA_PATH("TOPPBase_common.ini");
TEST_EQUAL(tmp3.getStringList("stringlist"),tmp_stringlist);
TEST_EXCEPTION(Exception::WrongParameterType,tmp2.getStringList("intoption"));
TEST_EXCEPTION(Exception::UnregisteredParameter,tmp2.getStringList("imleeewenit"));
//missing required parameters
const char* string_cl3[2] = {a1, a11};
TOPPBaseTestNOP tmp4(2,string_cl3);
TEST_EXCEPTION(Exception::RequiredParameterNotGiven,tmp4.getStringList("stringlist"));
END_SECTION
START_SECTION(([EXTRA]bool getFlag_(const String& name) const))
//default
TOPPBaseTest tmp;
TEST_EQUAL(tmp.getFlag("flag"),false);
//command line
const char* flag_cl[2] = {a1, a11}; //command line: "TOPPBaseTest -flag"
TOPPBaseTest tmp2(2,flag_cl);
TEST_EQUAL(tmp2.getFlag("flag"),true);
TEST_EXCEPTION(Exception::WrongParameterType,tmp2.getFlag("doubleoption"));
TEST_EXCEPTION(Exception::UnregisteredParameter,tmp2.getFlag("imleeewenit"));
END_SECTION
START_SECTION(([EXTRA]void inputFileReadable_(const String& filename, const String& param_name) const))
TOPPBaseTest tmp;
TEST_EXCEPTION(Exception::FileNotFound, tmp.inputFileReadable("/this/file/does/not/exist.txt", "someparam"));
TEST_EXCEPTION(Exception::FileEmpty, tmp.inputFileReadable(OPENMS_GET_TEST_DATA_PATH("TOPPBase_empty.txt"), "someparam"));
tmp.inputFileReadable(OPENMS_GET_TEST_DATA_PATH("TOPPBase_common.ini"), "ini");
END_SECTION
START_SECTION(([EXTRA]void outputFileWritable_(const String& filename, const String& param_name) const))
TEST_EXCEPTION(Exception::UnableToCreateFile,TOPPBaseTest().outputFileWritable("/this/file/cannot/be/written/does_not_exists.txt","someparam"));
String filename;
NEW_TMP_FILE(filename);
TOPPBaseTest().outputFileWritable(filename, "");
//Actually writing something to the file is not necessary, but on Mac all tmp files are called 'source_<line>.tmp'.
//So we have to make sure the file is empty. Otherwise the test might fail...
TextFile dummy;
dummy.addLine("");dummy.addLine("");dummy.addLine("");dummy.addLine("");dummy.addLine("");
dummy.store(filename);
END_SECTION
START_SECTION(([EXTRA]void parseRange_(const String& text, double& low, double& high) const))
{
TOPPBaseTest topp;
double a = -1.0;
double b = -1.0;
String s = ":";
bool result = topp.parseRange(s, a, b);
TEST_REAL_SIMILAR(a, -1.0);
TEST_REAL_SIMILAR(b, -1.0);
TEST_EQUAL(result, false);
s = "4.5:";
result = topp.parseRange(s, a, b);
TEST_REAL_SIMILAR(a, 4.5);
TEST_REAL_SIMILAR(b, -1.0);
TEST_EQUAL(result, true);
s = ":5.5";
result = topp.parseRange(s, a, b);
TEST_REAL_SIMILAR(a, 4.5);
TEST_REAL_SIMILAR(b, 5.5);
TEST_EQUAL(result, true);
s = "6.5:7.5";
result = topp.parseRange(s, a, b);
TEST_REAL_SIMILAR(a, 6.5);
TEST_REAL_SIMILAR(b, 7.5);
TEST_EQUAL(result, true);
}
END_SECTION
START_SECTION(([EXTRA] TOPPBase::ExitCodes TOPPBase::runExternalProcess_(const QString& executable, const QStringList& arguments, const QString& workdir) const))
{
// we just need ANY commandline tool available on (hopefully) all boxes.
// note that commands like "dir" or "type" are only known within cmd.exe and are not actual executables (unlike on Linux)
#ifdef OPENMS_WINDOWSPLATFORM
const QString exe = "cmd";
const QStringList args = QStringList() << "/C" << "echo hi";
const QStringList args_broken = QStringList() << "/C" << "doesnotexist";
#else
const QString exe = "ls";
const QStringList args("-l");
const QStringList args_broken = QStringList() << "-0";
#endif //
TOPPBaseTest topp;
auto result = topp.runExternalProcess("/path/does/not/exists.exe", QStringList(), "");
TEST_EQUAL(result, TOPPBase::EXTERNAL_PROGRAM_NOTFOUND);
result = topp.runExternalProcess(exe, args_broken, "");
TEST_EQUAL(result, TOPPBase::EXTERNAL_PROGRAM_ERROR);
result = topp.runExternalProcess(exe, args, "");
TEST_EQUAL(result, TOPPBase::EXECUTION_OK);
}
END_SECTION
START_SECTION(([EXTRA] data processing methods))
PeakMap exp;
exp.resize(2);
TOPPBaseTest topp;
topp.addDataProcessing(exp, DataProcessing::ALIGNMENT);
for (Size i=0; i<exp.size(); ++i)
{
TEST_EQUAL(exp[i].getDataProcessing().size(),1)
TEST_EQUAL(exp[i].getDataProcessing()[0]->getSoftware().getName(),"TOPPBaseTest")
TEST_NOT_EQUAL(exp[i].getDataProcessing()[0]->getSoftware().getVersion(),"1.1")
TEST_EQUAL(exp[i].getDataProcessing()[0]->getCompletionTime().isValid(),true)
TEST_EQUAL(exp[i].getDataProcessing()[0]->getProcessingActions().size(),1)
TEST_EQUAL(*(exp[i].getDataProcessing()[0]->getProcessingActions().begin()),DataProcessing::ALIGNMENT)
}
END_SECTION
START_SECTION(([EXTRA] const Param& getParam_()))
{
Param test_param;
test_param.setValue("param_int", 123, "param int description");
test_param.setValue("param_double", -4.56, "param double description");
test_param.setValue("param_string", "test", "param string description");
test_param.setValue("param_stringlist", std::vector<std::string>{"this","is","a","test"}, "param stringlist description");
test_param.setValue("param_intlist", ListUtils::create<Int>("7,-8,9"), "param intlist description");
test_param.setValue("param_doublelist", ListUtils::create<double>("123,-4.56,0.789"), "param doublelist description");
test_param.setValue("param_flag", "true", "param flag description");
test_param.setValidStrings("param_flag", {"true","false"});
TOPPBaseTestParam temp(test_param);
Param result = temp.getParam(); // contains "test_param" + some default stuff
for (Param::ParamIterator it = test_param.begin(); it != test_param.end(); ++it)
{
TEST_EQUAL(*it == result.getEntry(it.getName()), true);
}
}
END_SECTION
START_SECTION((static void setMaxNumberOfThreads(int num_threads)))
{
// this is a helper function that is only working if openmp is active
// due to bugs in the different OpenMP implementations it is not realy
// testable
NOT_TESTABLE
}
END_SECTION
START_SECTION(([EXTRA] misc options on command line))
{
// misc text option
const char* string_cl[3] = {a1, a12, test}; //command line: "TOPPBaseTest commandline"
TOPPBaseCmdParseTest tmp1;
TOPPBase::ExitCodes ec1 = tmp1.run(3,string_cl);
TEST_EQUAL(ec1, TOPPBase::ILLEGAL_PARAMETERS)
// unknown option
TOPPBaseCmdParseTest tmp2;
const char* string_cl_2[4] = {a1, a10, a12, test}; //command line: "TOPPBaseTest -stringoption commandline"
TOPPBase::ExitCodes ec2 = tmp1.run(4,string_cl_2);
TEST_EQUAL(ec2, TOPPBase::ILLEGAL_PARAMETERS)
}
END_SECTION
const char* a22 = "-algorithm:param1";
const char* a23 = "-algorithm:param2";
const char* a24 = "-other:param3";
const char* a25 = "-other:param4";
const char* a26 = "val1";
const char* a27 = "val2";
const char* a28 = "val3";
const char* a29 = "val4";
std::string temp_a30(OPENMS_GET_TEST_DATA_PATH("TOPPBaseCmdParseSubsectionsTest.ini"));
const char* a30 = temp_a30.c_str();
START_SECTION(([EXTRA] test subsection parameters))
{
const char* string_cl_1[4] = {a1, a10, a12, test}; //command line: "TOPPBaseTest -stringoption commandline"
TOPPBaseCmdParseSubsectionsTest tmp1;
TOPPBase::ExitCodes ec1 = tmp1.run(4, string_cl_1);
TEST_EQUAL(ec1, TOPPBase::EXECUTION_OK)
TEST_EQUAL(tmp1.getStringOption("stringoption"), "commandline");
TEST_EQUAL(tmp1.getParam().getValue("algorithm:param1"), "param1_value");
TEST_EQUAL(tmp1.getParam().getValue("algorithm:param2"), "param2_value");
TEST_EQUAL(tmp1.getParam().getValue("other:param3"), "param3_value");
TEST_EQUAL(tmp1.getParam().getValue("other:param4"), "param4_value");
// overwrite from cmd
const char* string_cl_2[12] = {a1, a10, a12, a22, a26, a23, a27, a24, a28, a25, a29, test}; //command line: "TOPPBaseTest -algorithm:param1 val1 -algorithm:param2 val2 -algorithm:param3 val3 -algorithm:param4 val4 -stringoption commandline"
TOPPBaseCmdParseSubsectionsTest tmp2;
TOPPBase::ExitCodes ec2 = tmp2.run(12, string_cl_2);
TEST_EQUAL(ec2, TOPPBase::EXECUTION_OK)
TEST_EQUAL(tmp2.getStringOption("stringoption"), "commandline");
TEST_EQUAL(tmp2.getParam().getValue("algorithm:param1"), "val1");
TEST_EQUAL(tmp2.getParam().getValue("algorithm:param2"), "val2");
TEST_EQUAL(tmp2.getParam().getValue("other:param3"), "val3");
TEST_EQUAL(tmp2.getParam().getValue("other:param4"), "val4");
// overwrite ini values from cmd
const char* string_cl_3[10] = {a1, a3, a30, a22, a26, a25, a29, a10, a12, test }; //command line: "TOPPBaseTest -ini TOPPBaseCmdParseSubsectionsTest.ini -algorithm:param1 val1 -algorithm:param4 val4"
TOPPBaseCmdParseSubsectionsTest tmp3;
TOPPBase::ExitCodes ec3 = tmp3.run(10, string_cl_3);
TEST_EQUAL(ec3, TOPPBase::EXECUTION_OK)
TEST_EQUAL(tmp3.getStringOption("stringoption"), "commandline");
TEST_EQUAL(tmp3.getParam().getValue("algorithm:param1"), "val1");
TEST_EQUAL(tmp3.getParam().getValue("algorithm:param2"), "param2_ini_value");
TEST_EQUAL(tmp3.getParam().getValue("other:param3"), "param3_ini_value");
TEST_EQUAL(tmp3.getParam().getValue("other:param4"), "val4");
}
END_SECTION
delete [] a7;
delete [] a8;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SearchEngineBase_test.cpp | .cpp | 4,609 | 153 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/APPLICATIONS/SearchEngineBase.h>
///////////////////////////
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <string>
using namespace OpenMS;
using namespace std;
//test class with optional parameters
class SearchEngineBaseTest
: public SearchEngineBase
{
public:
SearchEngineBaseTest()
: SearchEngineBase("SearchEngineBaseTest", "A test class", false, {}, false)
{
char* var = (char*)("OPENMS_DISABLE_UPDATE_CHECK=ON");
#ifdef OPENMS_WINDOWSPLATFORM
_putenv(var);
#else
putenv(var);
#endif
//main(0,nullptr);
}
void registerOptionsAndFlags_() override
{
// these flags are currently used in public functions of SEB
// used in: getRawfileName()
registerInputFile_("in", "<file>", "", "Input file");
setValidFormats_("in", { "mzML" } );
// used in: getDBFilename()
registerInputFile_("database", "<file>", "", "FASTA file", true, false, {"skipexists"});
setValidFormats_("database", { "FASTA" } );
}
ExitCodes main_(int /*argc*/ , const char** /*argv*/) override
{
// check raw file (must contain centroided MS2 spectra)
String in = getRawfileName();
// check if DB is found (no PATH lookup possible here, since we do not control the OpenMS.ini; so usefulness is limited)
String db = getDBFilename();
return EXECUTION_OK;
}
};
std::vector<const char*> toArgV(const StringList& args)
{
std::vector<const char*> args_p;
for (auto& a : args) args_p.push_back(a.c_str());
return args_p;
}
/////////////////////////////////////////////////////////////
START_TEST(SearchEngineBase, "$Id$");
/////////////////////////////////////////////////////////////
SearchEngineBaseTest* ptr = nullptr;
SearchEngineBaseTest* nullPointer = nullptr;
START_SECTION(SearchEngineBase(const String& name, const String& description, bool official = true, const std::vector<Citation>& citations = {}, bool toolhandler_test = true))
ptr = new SearchEngineBaseTest();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~SearchEngineBase()))
delete ptr;
END_SECTION
START_SECTION(String getRawfileName(int ms_level = 2) const;)
// collect arguments to TOPP/SEB
String db(OPENMS_GET_TEST_DATA_PATH("degenerate_cases/empty.fasta"));
String infile_empty(OPENMS_GET_TEST_DATA_PATH("degenerate_cases/empty_spec.mzML"));
String infile_profile(OPENMS_GET_TEST_DATA_PATH("Single_MS2_profileMode.mzML"));
StringList args;
// need local scopes; calling TOPPBase::main() twice leads to error
//
// TEST UNKNOWN-only DATA (via an empty spectrum):
//
{
SearchEngineBaseTest instance;
args = { { "main.exe", "-in", infile_empty, "-database", db } };
// run it
// --> fails, since the experiment does not contain centroided spectra (only one 'UNKNOWN')
TEST_EQUAL(TOPPBase::ExitCodes::UNKNOWN_ERROR == instance.main(args.size(), toArgV(args).data()), true);
}
{
SearchEngineBaseTest instance;
args = { { "main.exe", "-in", infile_empty, "-database", db, "-force" } };
// run it
// --> ok, due to -force
TEST_EQUAL(TOPPBase::ExitCodes::EXECUTION_OK == instance.main(args.size(), toArgV(args).data()), true);
}
//
// TEST PROFILE-only DATA:
//
{
SearchEngineBaseTest instance;
args = { { "main.exe", "-in", infile_profile, "-database", db } };
// run it
// --> fails, since the experiment contains a spectrum of type 'PROFILE'
TEST_EQUAL(TOPPBase::ExitCodes::UNKNOWN_ERROR == instance.main(args.size(), toArgV(args).data()), true);
}
{
SearchEngineBaseTest instance;
args = { { "main.exe", "-in", infile_profile, "-database", db, "-force" } };
// run it
// --> ok, due to -force
TEST_EQUAL(TOPPBase::ExitCodes::EXECUTION_OK == instance.main(args.size(), toArgV(args).data()), true);
}
END_SECTION
START_SECTION(String getDBFilename(String db = "") const)
NOT_TESTABLE // tested above
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/BaseModel_test.cpp | .cpp | 4,441 | 192 | // 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/BaseModel.h>
#include <OpenMS/FEATUREFINDER/BaseModel_impl.h>
#include <OpenMS/CONCEPT/Exception.h>
///////////////////////////
using namespace OpenMS;
using std::stringstream;
START_TEST(BaseModel, "$Id$")
class TestModel : public BaseModel
{
public:
TestModel()
: BaseModel()
{
setName("TestModel");
check_defaults_ = false;
defaultsToParam_();
}
TestModel(const TestModel& source)
: BaseModel(source)
{
updateMembers_();
}
~TestModel() override {}
virtual TestModel& operator = (const TestModel& source)
{
if (&source == this) return *this;
BaseModel::operator = (source);
updateMembers_();
return *this;
}
void updateMembers_() override
{
BaseModel::updateMembers_();
}
IntensityType getIntensity(const PositionType& pos) const override
{
return pos[0];
}
bool isContained(const PositionType& pos) const override
{
return getIntensity(pos)>cut_off_;
}
void getSamples(SamplesType& /*cont*/) const override
{
}
};
// default ctor
TestModel* ptr = nullptr;
TestModel* nullPointer = nullptr;
START_SECTION((BaseModel()))
ptr = new TestModel();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
// destructor
START_SECTION((virtual ~BaseModel()))
delete ptr;
END_SECTION
// assignment operator
START_SECTION((virtual BaseModel& operator=(const BaseModel &source)))
TestModel tm1;
TestModel tm2;
tm1.setCutOff(3.3);
tm2 = tm1;
TEST_REAL_SIMILAR(tm1.getCutOff(),tm2.getCutOff())
END_SECTION
// copy constructor
START_SECTION((BaseModel(const BaseModel &source)))
TestModel tm1;
tm1.setCutOff(0.1);
TestModel tm2(tm1);
TEST_REAL_SIMILAR(tm1.getCutOff(),tm2.getCutOff())
END_SECTION
START_SECTION(([EXTRA]IntensityType getCutOff() const))
const TestModel s;
TEST_REAL_SIMILAR(s.getCutOff(), TestModel::IntensityType(0))
END_SECTION
START_SECTION((virtual void setCutOff(IntensityType cut_off)))
TestModel s;
s.setCutOff(4.4);
TEST_REAL_SIMILAR(s.getCutOff(), 4.4)
END_SECTION
START_SECTION(([EXTRA]const String& getName() const))
TestModel s;
TEST_EQUAL(s.getName(), "TestModel")
END_SECTION
START_SECTION((virtual IntensityType getIntensity(const PositionType &pos) const =0))
{
const TestModel s;
TestModel::PositionType pos;
pos[0]=0.1;
TEST_REAL_SIMILAR(s.getIntensity(pos), 0.1);
}
END_SECTION
START_SECTION((virtual bool isContained(const PositionType &pos) const))
TestModel s;
s.setCutOff(0.9);
TestModel::PositionType pos;
pos[0]=0.1;
const TestModel& t = s;
TEST_EQUAL(t.isContained(pos), false)
END_SECTION
START_SECTION((template <typename PeakType> void fillIntensity(PeakType &peak) const))
const TestModel t;
TestModel::PeakType p;
p.getPosition()[0]=0.1;
p.setIntensity(0.1f);
t.fillIntensity(p);
TEST_REAL_SIMILAR(p.getIntensity(), 0.1)
END_SECTION
START_SECTION((template <class PeakIterator> void fillIntensities(PeakIterator begin, PeakIterator end) const))
const TestModel t;
std::vector< TestModel::PeakType > vec(4);
for (Size i=0; i<4; ++i)
{
vec[i].setIntensity(-0.5);
vec[i].getPosition()[0] = i;
}
t.fillIntensities(vec.begin()+1, vec.end()-1);
TEST_EQUAL(vec[0].getIntensity(), -0.5)
TEST_EQUAL(vec[1].getIntensity(), 1.0)
TEST_EQUAL(vec[2].getIntensity(), 2.0)
TEST_EQUAL(vec[3].getIntensity(), -0.5)
END_SECTION
START_SECTION([EXTRA] DefaultParmHandler::setParameters(...))
Param p;
p.setValue("cutoff",17.0);
TestModel m;
m.setParameters(p);
TEST_REAL_SIMILAR(m.getParameters().getValue("cutoff"), 17.0)
END_SECTION
START_SECTION((virtual IntensityType getCutOff() const))
TestModel s;
s.setCutOff(4.4);
TEST_REAL_SIMILAR(s.getCutOff(), 4.4)
END_SECTION
START_SECTION((virtual void getSamples(SamplesType &cont) const =0))
NOT_TESTABLE;
END_SECTION
START_SECTION((virtual void getSamples(std::ostream &os)))
NOT_TESTABLE;
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SqMassFile_test.cpp | .cpp | 20,140 | 469 | // 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/SqMassFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <QFile>
using namespace OpenMS;
using namespace std;
///////////////////////////
void cmpDataIntensity(const MSExperiment& exp1, const MSExperiment& exp2, double abs_tol = 1e-5, double rel_tol = 1+1e-5)
{
// Logic of comparison: if the absolute difference criterion is fulfilled,
// the relative one does not matter. If the absolute difference is larger
// than allowed, the test does not fail if the relative difference is less
// than allowed.
// Note that the sample spectrum intensity has a very large range, from
// 0.00013 to 183 838 intensity and encoding both values with high accuracy
// is difficult.
TOLERANCE_ABSOLUTE(abs_tol)
TOLERANCE_RELATIVE(rel_tol)
for (Size i = 0; i < exp1.getNrSpectra(); i++)
{
TEST_EQUAL(exp1.getSpectra()[i].size(), exp2.getSpectra()[i].size())
for (Size k = 0; k < exp1.getSpectra()[i].size(); k++)
{
// slof is no good for values smaller than 5
// if (exp.getSpectrum(i)[k].getIntensity() < 1.0) {continue;}
auto a = exp1.getSpectra()[i][k].getIntensity();
auto b = exp2.getSpectra()[i][k].getIntensity();
// avoid the console clutter if nothing interesing happens
if (!TEST::isRealSimilar(a, b)) TEST_REAL_SIMILAR(a, b)
}
}
for (Size i = 0; i < exp1.getNrChromatograms(); i++)
{
TEST_EQUAL(exp1.getChromatograms()[i].size() == exp2.getChromatograms()[i].size(), true)
for (Size k = 0; k < exp1.getChromatograms()[i].size(); k++)
{
auto a = exp1.getChromatograms()[i][k].getIntensity();
auto b = exp2.getChromatograms()[i][k].getIntensity();
// avoid the console clutter if nothing interesing happens
if (!TEST::isRealSimilar(a, b)) TEST_REAL_SIMILAR(a, b)
}
}
}
void cmpDataMZ(const MSExperiment& exp1, const MSExperiment& exp2, double abs_tol = 1e-5, double rel_tol = 1+1e-5)
{
// Logic of comparison: if the absolute difference criterion is fulfilled,
// the relative one does not matter. If the absolute difference is larger
// than allowed, the test does not fail if the relative difference is less
// than allowed.
// Note that the sample spectrum intensity has a very large range, from
// 0.00013 to 183 838 intensity and encoding both values with high accuracy
// is difficult.
TOLERANCE_ABSOLUTE(abs_tol)
TOLERANCE_RELATIVE(rel_tol)
for (Size i = 0; i < exp1.getNrSpectra(); i++)
{
TEST_EQUAL(exp1.getSpectra()[i].size(), exp2.getSpectra()[i].size())
for (Size k = 0; k < exp1.getSpectra()[i].size(); k++)
{
// slof is no good for values smaller than 5
// if (exp.getSpectrum(i)[k].getIntensity() < 1.0) {continue;}
auto a = exp1.getSpectra()[i][k].getMZ();
auto b = exp2.getSpectra()[i][k].getMZ();
// avoid the console clutter if nothing interesing happens
if (!TEST::isRealSimilar(a, b)) TEST_REAL_SIMILAR(a, b)
}
}
}
void cmpDataRT(const MSExperiment& exp1, const MSExperiment& exp2, double abs_tol = 1e-5, double rel_tol = 1+1e-5)
{
// Logic of comparison: if the absolute difference criterion is fulfilled,
// the relative one does not matter. If the absolute difference is larger
// than allowed, the test does not fail if the relative difference is less
// than allowed.
// Note that the sample spectrum intensity has a very large range, from
// 0.00013 to 183 838 intensity and encoding both values with high accuracy
// is difficult.
TOLERANCE_ABSOLUTE(abs_tol)
TOLERANCE_RELATIVE(rel_tol)
for (Size i = 0; i < exp1.getNrChromatograms(); i++)
{
TEST_EQUAL(exp1.getChromatograms()[i].size() == exp2.getChromatograms()[i].size(), true)
for (Size k = 0; k < exp1.getChromatograms()[i].size(); k++)
{
auto a = exp1.getChromatograms()[i][k].getRT();
auto b = exp2.getChromatograms()[i][k].getRT();
// avoid the console clutter if nothing interesing happens
if (!TEST::isRealSimilar(a, b)) TEST_REAL_SIMILAR(a, b)
}
}
}
START_TEST(SqMassFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
SqMassFile* ptr = nullptr;
SqMassFile* nullPointer = nullptr;
START_SECTION((SqMassFile()))
ptr = new SqMassFile;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~SqMassFile()))
delete ptr;
END_SECTION
TOLERANCE_RELATIVE(1.0005)
START_SECTION(void load(const String& filename, MapType& map))
{
MSExperiment exp;
SqMassFile().load(OPENMS_GET_TEST_DATA_PATH("SqliteMassFile_1.sqMass"), exp);
MSExperiment exp2;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"),exp2);
TEST_EQUAL(exp.getNrSpectra(), exp2.getSpectra().size())
TEST_EQUAL(exp.getNrChromatograms(), exp2.getChromatograms().size())
TEST_EQUAL(exp.getNrSpectra(), 2)
TEST_EQUAL(exp.getNrChromatograms(), 1)
TEST_EQUAL(exp.getSpectrum(0) == exp2.getSpectra()[0], false) // no exact duplicate
cout.precision(17);
// Logic of comparison: if the absolute difference criterion is fulfilled,
// the relative one does not matter. If the absolute difference is larger
// than allowed, the test does not fail if the relative difference is less
// than allowed.
// Note that the sample spectrum intensity has a very large range, from
// 0.00013 to 183 838 intensity and encoding both values with high accuracy
// is difficult.
cmpDataIntensity(exp, exp2, 1e-4, 1.001);
cmpDataMZ(exp, exp2, 1e-5, 1.000001); // less than 1ppm error for m/z
cmpDataRT(exp, exp2, 0.05, 1.000001); // max 0.05 seconds error in RT
// mapping of experimental settings ...
TEST_EQUAL(exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp2, true)
TEST_EQUAL(exp.getSqlRunID(), exp2.getSqlRunID())
}
END_SECTION
// reset error tolerances to default values
TOLERANCE_ABSOLUTE(1e-5)
TOLERANCE_RELATIVE(1+1e-5)
START_SECTION(void store(const String& filename, MapType& map))
{
MSExperiment exp_orig;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), exp_orig);
SqMassFile::SqMassConfig config;
config.use_lossy_numpress = false;
config.linear_fp_mass_acc = -1;
config.write_full_meta = false;
SqMassFile file;
file.setConfig(config);
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
std::cout << "Storing in file " << tmp_filename << std::endl;
file.store(tmp_filename, exp_orig);
MSExperiment exp;
file.load(tmp_filename, exp);
TEST_EQUAL(exp.getNrSpectra(), exp_orig.getSpectra().size())
TEST_EQUAL(exp.getNrChromatograms(), exp_orig.getChromatograms().size())
TEST_EQUAL(exp.getNrSpectra(), 2)
TEST_EQUAL(exp.getNrChromatograms(), 1)
TEST_EQUAL(exp.getSpectrum(0) == exp_orig.getSpectra()[0], false) // no exact duplicate
MSExperiment exp2 = exp_orig;
// Logic of comparison: if the absolute difference criterion is fulfilled,
// the relative one does not matter. If the absolute difference is larger
// than allowed, the test does not fail if the relative difference is less
// than allowed.
// Note that the sample spectrum intensity has a very large range, from
// 0.00013 to 183 838 intensity and encoding both values with high accuracy
// is difficult.
TOLERANCE_ABSOLUTE(1e-4)
TOLERANCE_RELATIVE(1.001) // 0.1 % error for intensity
// reset error tolerances to default values
TOLERANCE_ABSOLUTE(1e-5)
TOLERANCE_RELATIVE(1+1e-5)
// since we specified no lossy compression, we expect high accuracy
TOLERANCE_ABSOLUTE(1e-8)
TOLERANCE_RELATIVE(1.00000001)
cmpDataIntensity(exp, exp2, 1e-8, 1.00000001);
cmpDataMZ(exp, exp2, 1e-8, 1.00000001);
cmpDataRT(exp, exp2, 1e-8, 1.00000001);
// no 1:1 mapping of experimental settings ...
TEST_EQUAL(exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp2, false)
}
END_SECTION
START_SECTION([EXTRA_LOSSY] void store(const String& filename, MapType& map))
{
MSExperiment exp_orig;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), exp_orig);
SqMassFile::SqMassConfig config;
config.use_lossy_numpress = true;
config.linear_fp_mass_acc = 0.0001;
config.write_full_meta = false;
{
Precursor p;
std::set<Precursor::ActivationMethod> tmp = {Precursor::ActivationMethod::BIRD};
p.setActivationMethods(tmp);
p.setActivationEnergy(500);
p.setCharge(4);
p.setMZ(600);
p.setIsolationWindowUpperOffset(7);
p.setIsolationWindowLowerOffset(14);
p.setDriftTime(0.5);
p.setDriftTimeUnit(DriftTimeUnit::MILLISECOND);
p.setMetaValue("peptide_sequence", "PEPTIDEK");
std::vector<Precursor> prec;
prec.push_back(p);
exp_orig.getSpectrum(0).setPrecursors(prec);
exp_orig.getChromatogram(0).setPrecursor(p);
Product pr;
// pr.setCharge(6);
pr.setMZ(300);
pr.setIsolationWindowUpperOffset(10);
pr.setIsolationWindowLowerOffset(15);
std::vector<Product> prod;
prod.push_back(pr);
exp_orig.getSpectrum(0).setProducts(prod);
exp_orig.getChromatogram(0).setProduct(pr);
TEST_REAL_SIMILAR(exp_orig.getSpectrum(0).getPrecursors()[0].getActivationEnergy(), 500.0);
}
SqMassFile file;
file.setConfig(config);
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
std::cout << "Storing in file " << tmp_filename << std::endl;
file.store(tmp_filename, exp_orig);
MSExperiment exp;
file.load(tmp_filename, exp);
TEST_EQUAL(exp.getNrSpectra(), exp_orig.getSpectra().size())
TEST_EQUAL(exp.getNrChromatograms(), exp_orig.getChromatograms().size())
TEST_EQUAL(exp.getNrSpectra(), 2)
TEST_EQUAL(exp.getNrChromatograms(), 1)
TEST_EQUAL(exp.getSpectrum(0) == exp_orig.getSpectra()[0], false) // no exact duplicate
{
TEST_REAL_SIMILAR(exp.getSpectrum(0).getRT(), exp_orig.getSpectrum(0).getRT())
TEST_EQUAL(exp.getSpectrum(0).getNativeID(), exp_orig.getSpectrum(0).getNativeID())
TEST_EQUAL(exp.getSpectrum(0).getMSLevel(), exp_orig.getSpectrum(0).getMSLevel())
TEST_EQUAL(exp.getSpectrum(0).getInstrumentSettings().getPolarity(), exp_orig.getSpectrum(0).getInstrumentSettings().getPolarity())
TEST_EQUAL(exp.getSpectrum(0).getProducts().size(), 1)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getProducts()[0].getMZ(), 300)
// TEST_EQUAL(exp.getSpectrum(0).getProducts()[0].getCharge(), 6)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getProducts()[0].getIsolationWindowUpperOffset(), 10)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getProducts()[0].getIsolationWindowLowerOffset(), 15)
TEST_EQUAL(exp.getSpectrum(0).getPrecursors().size(), 1)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getActivationEnergy(), 500)
TEST_EQUAL(exp.getSpectrum(0).getPrecursors()[0].getCharge(), 4)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getDriftTime(), 0.5)
// TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getDriftTimeUnit(), 0.5) // not implemented
TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getMZ(), 600)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getIsolationWindowUpperOffset(), 7)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getIsolationWindowLowerOffset(), 14)
TEST_EQUAL(exp.getSpectrum(0).getPrecursors()[0].metaValueExists("peptide_sequence"), true)
TEST_EQUAL(exp.getSpectrum(0).getPrecursors()[0].getMetaValue("peptide_sequence"), "PEPTIDEK")
}
{
TEST_EQUAL(exp.getChromatogram(0).getNativeID(), exp_orig.getChromatogram(0).getNativeID())
TEST_REAL_SIMILAR(exp.getChromatogram(0).getProduct().getMZ(), 300)
// TEST_EQUAL(exp.getChromatogram(0).getProduct().getCharge(), 6)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getProduct().getIsolationWindowUpperOffset(), 10)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getProduct().getIsolationWindowLowerOffset(), 15)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getActivationEnergy(), 500)
TEST_EQUAL(exp.getChromatogram(0).getPrecursor().getCharge(), 4)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getDriftTime(), 0.5)
// TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getDriftTimeUnit(), 0.5) // not implemented
TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getMZ(), 600)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getIsolationWindowUpperOffset(), 7)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getIsolationWindowLowerOffset(), 14)
TEST_EQUAL(exp.getChromatogram(0).getPrecursor().metaValueExists("peptide_sequence"), true)
TEST_EQUAL(exp.getChromatogram(0).getPrecursor().getMetaValue("peptide_sequence"), "PEPTIDEK")
}
MSExperiment exp2 = exp_orig;
// should not give 1:1 mapping of experimental settings ...
TEST_EQUAL(exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp2, false)
// Logic of comparison: if the absolute difference criterion is fulfilled,
// the relative one does not matter. If the absolute difference is larger
// than allowed, the test does not fail if the relative difference is less
// than allowed.
// Note that the sample spectrum intensity has a very large range, from
// 0.00013 to 183 838 intensity and encoding both values with high accuracy
// is difficult.
TOLERANCE_ABSOLUTE(1e-4)
TOLERANCE_RELATIVE(1.001) // 0.1 % error for intensity
cmpDataIntensity(exp, exp2, 1e-4, 1.001); // 0.1 % error for intensity
cmpDataMZ(exp, exp2, 1e-5, 1.000001); // less than 1ppm error for m/z
cmpDataRT(exp, exp2, 0.05, 1.00000001); // max 0.05 seconds error in RT
}
END_SECTION
START_SECTION([EXTRA_FULL_META] void store(const String& filename, MapType& map))
{
MSExperiment exp_orig;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MzMLSqliteHandler_1.mzML"), exp_orig);
SqMassFile::SqMassConfig config;
config.use_lossy_numpress = true;
config.linear_fp_mass_acc = 0.0001;
config.write_full_meta = true;
{
Precursor p;
std::set<Precursor::ActivationMethod> tmp = {Precursor::ActivationMethod::BIRD};
p.setActivationMethods(tmp);
p.setActivationEnergy(500);
p.setCharge(4);
p.setMZ(600);
p.setIsolationWindowUpperOffset(7);
p.setIsolationWindowLowerOffset(14);
p.setDriftTime(0.5);
p.setDriftTimeUnit(DriftTimeUnit::MILLISECOND);
p.setMetaValue("peptide_sequence", "PEPTIDEK");
std::vector<Precursor> prec;
prec.push_back(p);
exp_orig.getSpectrum(0).setPrecursors(prec);
exp_orig.getChromatogram(0).setPrecursor(p);
Product pr;
// pr.setCharge(6);
pr.setMZ(300);
pr.setIsolationWindowUpperOffset(10);
pr.setIsolationWindowLowerOffset(15);
std::vector<Product> prod;
prod.push_back(pr);
exp_orig.getSpectrum(0).setProducts(prod);
exp_orig.getChromatogram(0).setProduct(pr);
TEST_REAL_SIMILAR(exp_orig.getSpectrum(0).getPrecursors()[0].getActivationEnergy(), 500.0);
}
SqMassFile file;
file.setConfig(config);
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
std::cout << "Storing in file " << tmp_filename << std::endl;
file.store(tmp_filename, exp_orig);
MSExperiment exp;
file.load(tmp_filename, exp);
TEST_EQUAL(exp.getNrSpectra(), exp_orig.getSpectra().size())
TEST_EQUAL(exp.getNrChromatograms(), exp_orig.getChromatograms().size())
TEST_EQUAL(exp.getNrSpectra(), 2)
TEST_EQUAL(exp.getNrChromatograms(), 1)
TEST_EQUAL(exp.getSpectrum(0) == exp_orig.getSpectra()[0], false) // no exact duplicate
{
TEST_REAL_SIMILAR(exp.getSpectrum(0).getRT(), exp_orig.getSpectrum(0).getRT())
TEST_EQUAL(exp.getSpectrum(0).getNativeID(), exp_orig.getSpectrum(0).getNativeID())
TEST_EQUAL(exp.getSpectrum(0).getMSLevel(), exp_orig.getSpectrum(0).getMSLevel())
TEST_EQUAL(exp.getSpectrum(0).getInstrumentSettings().getPolarity(), exp_orig.getSpectrum(0).getInstrumentSettings().getPolarity())
TEST_EQUAL(exp.getSpectrum(0).getProducts().size(), 1)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getProducts()[0].getMZ(), 300)
// TEST_EQUAL(exp.getSpectrum(0).getProducts()[0].getCharge(), 6)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getProducts()[0].getIsolationWindowUpperOffset(), 10)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getProducts()[0].getIsolationWindowLowerOffset(), 15)
TEST_EQUAL(exp.getSpectrum(0).getPrecursors().size(), 1)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getActivationEnergy(), 500)
TEST_EQUAL(exp.getSpectrum(0).getPrecursors()[0].getCharge(), 4)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getDriftTime(), 0.5)
// TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getDriftTimeUnit(), 0.5) // not implemented
TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getMZ(), 600)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getIsolationWindowUpperOffset(), 7)
TEST_REAL_SIMILAR(exp.getSpectrum(0).getPrecursors()[0].getIsolationWindowLowerOffset(), 14)
TEST_EQUAL(exp.getSpectrum(0).getPrecursors()[0].metaValueExists("peptide_sequence"), true)
TEST_EQUAL(exp.getSpectrum(0).getPrecursors()[0].getMetaValue("peptide_sequence"), "PEPTIDEK")
}
{
TEST_EQUAL(exp.getChromatogram(0).getNativeID(), exp_orig.getChromatogram(0).getNativeID())
TEST_REAL_SIMILAR(exp.getChromatogram(0).getProduct().getMZ(), 300)
// TEST_EQUAL(exp.getChromatogram(0).getProduct().getCharge(), 6)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getProduct().getIsolationWindowUpperOffset(), 10)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getProduct().getIsolationWindowLowerOffset(), 15)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getActivationEnergy(), 500)
TEST_EQUAL(exp.getChromatogram(0).getPrecursor().getCharge(), 4)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getDriftTime(), 0.5)
// TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getDriftTimeUnit(), 0.5) // not implemented
TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getMZ(), 600)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getIsolationWindowUpperOffset(), 7)
TEST_REAL_SIMILAR(exp.getChromatogram(0).getPrecursor().getIsolationWindowLowerOffset(), 14)
TEST_EQUAL(exp.getChromatogram(0).getPrecursor().metaValueExists("peptide_sequence"), true)
TEST_EQUAL(exp.getChromatogram(0).getPrecursor().getMetaValue("peptide_sequence"), "PEPTIDEK")
}
MSExperiment exp2 = exp_orig;
// using full meta should give 1:1 mapping of experimental settings ...
TEST_EQUAL(exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp2, true)
TEST_EQUAL(exp.getSqlRunID(), exp2.getSqlRunID())
// Logic of comparison: if the absolute difference criterion is fulfilled,
// the relative one does not matter. If the absolute difference is larger
// than allowed, the test does not fail if the relative difference is less
// than allowed.
// Note that the sample spectrum intensity has a very large range, from
// 0.00013 to 183 838 intensity and encoding both values with high accuracy
// is difficult.
TOLERANCE_ABSOLUTE(1e-4)
TOLERANCE_RELATIVE(1.001) // 0.1 % error for intensity
cmpDataIntensity(exp, exp2, 1e-4, 1.001); // 0.1 % error for intensity
cmpDataMZ(exp, exp2, 1e-5, 1.000001); // less than 1ppm error for m/z
cmpDataRT(exp, exp2, 0.05, 1.00000001); // max 0.05 seconds error in RT
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/RichPeak2D_test.cpp | .cpp | 4,735 | 171 | // 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/RichPeak2D.h>
///////////////////////////
START_TEST(RichPeak2D<D>, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
RichPeak2D* d10_ptr = nullptr;
RichPeak2D* d10_nullPointer = nullptr;
START_SECTION((RichPeak2D()))
d10_ptr = new RichPeak2D;
TEST_NOT_EQUAL(d10_ptr, d10_nullPointer)
END_SECTION
START_SECTION((~RichPeak2D()))
delete d10_ptr;
END_SECTION
START_SECTION((RichPeak2D(const RichPeak2D &p)))
RichPeak2D p;
p.setIntensity(123.456f);
p.setMetaValue("cluster_id",4711);
RichPeak2D copy_of_p(p);
TEST_REAL_SIMILAR(copy_of_p.getIntensity(), 123.456f)
TEST_EQUAL(copy_of_p.getMetaValue("cluster_id"),DataValue(4711));
END_SECTION
START_SECTION((RichPeak2D(RichPeak2D &&rhs)))
{
// Ensure that RichPeak2D has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(RichPeak2D(std::declval<RichPeak2D&&>())), true)
Peak2D::PositionType pos;
pos[0] = 21.21;
pos[1] = 22.22;
RichPeak2D p;
p.setIntensity(123.456f);
p.setMetaValue("cluster_id",4711);
p.setPosition(pos);
RichPeak2D copy_of_p(std::move(p));
TEST_REAL_SIMILAR(copy_of_p.getIntensity(), 123.456f)
TEST_EQUAL(copy_of_p.getMetaValue("cluster_id"),DataValue(4711));
auto i2 = copy_of_p.getIntensity();
auto 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((RichPeak2D(const Peak2D &p)))
Peak2D p;
p.setIntensity(123.456f);
RichPeak2D copy_of_p(p);
TEST_REAL_SIMILAR(copy_of_p.getIntensity(), 123.456f)
END_SECTION
START_SECTION((explicit RichPeak2D(const PositionType& pos, const IntensityType in)))
RichPeak2D p(RichPeak2D::PositionType(21.21, 22.22), 123.456f);
RichPeak2D 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((RichPeak2D& operator=(const RichPeak2D &rhs)))
RichPeak2D p;
p.setIntensity(123.456f);
p.setMetaValue("cluster_id",4711);
RichPeak2D copy_of_p;
copy_of_p = p;
TEST_REAL_SIMILAR(copy_of_p.getIntensity(), 123.456f)
TEST_EQUAL(copy_of_p.getMetaValue("cluster_id"),DataValue(4711));
END_SECTION
START_SECTION((RichPeak2D& operator=(const Peak2D &rhs)))
Peak2D p;
p.setIntensity(123.456f);
RichPeak2D copy_of_p;
copy_of_p.setMetaValue("cluster_id",4711);
copy_of_p = p;
TEST_REAL_SIMILAR(copy_of_p.getIntensity(), 123.456f)
TEST_EQUAL(copy_of_p.isMetaEmpty(), true);
END_SECTION
START_SECTION((bool operator == (const RichPeak2D& rhs) const))
RichPeak2D p1, p2;
TEST_TRUE(p1 == p2)
p1.setIntensity(5.0f);
TEST_EQUAL(p1==p2, false)
p2.setIntensity(5.0f);
TEST_TRUE(p1 == p2)
p1.setMetaValue("cluster_id",4711);
TEST_EQUAL(p1==p2, false)
p1.removeMetaValue("cluster_id");
TEST_TRUE(p1 == p2)
END_SECTION
START_SECTION((bool operator != (const RichPeak2D& rhs) const))
RichPeak2D p1, p2;
TEST_EQUAL(p1!=p2, false)
p1.setIntensity(5.0f);
TEST_FALSE(p1 == p2)
p2.setIntensity(5.0f);
TEST_EQUAL(p1!=p2, false)
p1.setMetaValue("cluster_id",4711);
TEST_FALSE(p1 == p2)
p1.removeMetaValue("cluster_id");
TEST_EQUAL(p1!=p2, false)
END_SECTION
START_SECTION(([EXTRA] meta info with copy constructor))
RichPeak2D p;
p.setMetaValue(2,String("bla"));
RichPeak2D p2(p);
TEST_EQUAL(p.getMetaValue(2), "bla")
TEST_EQUAL(p2.getMetaValue(2), "bla")
p.setMetaValue(2,String("bluff"));
TEST_EQUAL(p.getMetaValue(2), "bluff")
TEST_EQUAL(p2.getMetaValue(2), "bla")
END_SECTION
START_SECTION(([EXTRA] meta info with assignment))
RichPeak2D p;
p.setMetaValue(2,String("bla"));
RichPeak2D p2 = p;
TEST_EQUAL(p.getMetaValue(2), "bla")
TEST_EQUAL(p2.getMetaValue(2), "bla")
p.setMetaValue(2,String("bluff"));
TEST_EQUAL(p.getMetaValue(2), "bluff")
TEST_EQUAL(p2.getMetaValue(2), "bla")
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/InspectOutfile_test.cpp | .cpp | 27,627 | 492 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Martin Langwisch $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/FORMAT/InspectOutfile.h>
#include <OpenMS/FORMAT/TextFile.h>
using namespace OpenMS;
using namespace std;
/////////////////////////////////////////////////////////////
START_TEST(String, "$Id$")
/////////////////////////////////////////////////////////////
String spectrum_file1 = OPENMS_GET_TEST_DATA_PATH("InspectOutfile_test_1.mzXML");
String spectrum_file2 = OPENMS_GET_TEST_DATA_PATH("InspectOutfile_test_2.mzXML");
//create input file (they contain absolute paths...)
String input_file_name;
NEW_TMP_FILE(input_file_name);
TextFile outfile_content;
outfile_content.addLine("#SpectrumFile Scan# Annotation Protein Charge MQScore CutScore IntenseBY BYPresent Unused p-value DeltaScore DeltaScoreOther RecordNumber DBFilePos SpecFilePos");
outfile_content.addLine(spectrum_file1 + " 4 N.EER.N Q9CQV8|1433B_MOUSE 1 -6889 1150 200 500 0 0.95000 0 0 1 287 270451");
outfile_content.addLine(spectrum_file1 + " 4 R.EKIE.K P68509|1433F_BOVIN 1 -1456 3388 300 667 0 0.01000 -1199 -1199 0 87 276369");
outfile_content.addLine(spectrum_file1 + " 4 E.KKLE.K P68509|1433F_BOVIN 1 -257 3820 450 333 0 0.00001 1199 1199 0 78 276369");
outfile_content.addLine(spectrum_file1 + " 25 D.DAIAE.L P68509|1433F_BOVIN 1 -6526 354 250 375 0 0.97500 -6269 -6269 0 205 276369");
outfile_content.addLine(spectrum_file1 + " 37 D.EAIAEL.D Q9CQV8|1433B_MOUSE 1 -2807 2464 350 300 0 0.98536 0 0 1 446 387302");
outfile_content.addLine(spectrum_file1 + " 49 D.KFLIK.N P68509|1433F_BOVIN 1 -5308 1813 250 375 0 0.98758 0 0 0 106 473207");
outfile_content.addLine(spectrum_file1 + " 120 N.EKKLEKVKA.Y P68509|1433F_BOVIN 2 -9115 -1187 185 125 0 0.96296 0 0 0 77 1062539");
outfile_content.addLine(spectrum_file1 + " 217 N.EDRNLL.S P68509|1433F_BOVIN 1 -11835 140 100 0 0 0.97143 0 0 0 41 1720635");
outfile_content.addLine(spectrum_file1 + " 249 A.LLDKF.L P68509|1433F_BOVIN 1 -4503 2554 300 250 0 0.99043 0 0 0 103 1943362");
outfile_content.addLine(spectrum_file1 + " 501 F.DEAIAELDTLNEE.S Q9CQV8|1433B_MOUSE 2 -7874 -1829 231 0 0 0.95652 0 0 1 452 3860094");
outfile_content.addLine(spectrum_file1 + " 667 K.LAEQAERYDDMAA.A Q9CQV8|1433B_MOUSE 2 -9787 -1362 77 125 0 0.96552 0 0 1 266 5279013");
outfile_content.addLine(spectrum_file1 + " 685 N.LTLWTSENQGDEGDAG.E Q9CQV8|1433B_MOUSE 2 -9056 -2174 125 0 0 0.96296 0 0 1 479 5448607");
outfile_content.addLine(spectrum_file1 + " 736 Y.QEAFEIS.K Q9CQV8|1433B_MOUSE 1 -11507 478 0 250 0 0.98789 17 17 1 399 6018155");
outfile_content.addLine(spectrum_file1 + " 736 Y.KEAFEIS.K P68509|1433F_BOVIN 1 -11524 457 0 250 0 0.97059 -17 0 0 156 6018155");
outfile_content.addLine(spectrum_file1 + " 758 S.NEDRNLLSVAYKN.V P68509|1433F_BOVIN 2 -4841 -481 256 208 0 0.98948 0 0 0 43 6167475");
outfile_content.addLine(spectrum_file1 + " 764 L.LAKQAFDDAIAELDTLNED.S P68509|1433F_BOVIN 2 -4474 -560 140 250 0 0.99043 0 0 0 201 6208454");
outfile_content.addLine(spectrum_file1 + " 786 T.MDKSELV.Q Q9CQV8|1433B_MOUSE 1 -12849 -1629 48 167 0 0.97368 0 0 1 253 6399323");
outfile_content.addLine(spectrum_file1 + " 1045 S.VFYYEI.Q P68509|1433F_BOVIN 1 -15475 -2579 0 100 0 0.97500 0 0 0 184 9842931");
outfile_content.addLine(spectrum_file1 + " 1962 E.AFEIS.K P68509|1433F_BOVIN 1 -10496 -742 100 375 0 0.96774 0 0 0 159 19098337");
outfile_content.store(input_file_name);
String input_file_name2;
NEW_TMP_FILE(input_file_name2);
TextFile outfile_content2;
outfile_content2.addLine("#SpectrumFile Scan# Annotation Protein Charge MQScore CutScore IntenseBY BYPresent Unused p-value DeltaScore DeltaScoreOther RecordNumber DBFilePos SpecFilePos");
outfile_content2.addLine(spectrum_file1 + " N.EER.N Q9CQV8|1433B_MOUSE 1 -6889 1150 200 500 0 0.95000 0 0 1 287 270451");
outfile_content2.store(input_file_name2);
InspectOutfile* ptr = nullptr;
InspectOutfile* nullPointer = nullptr;
START_SECTION(InspectOutfile())
ptr = new InspectOutfile();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~InspectOutfile())
delete ptr;
END_SECTION
START_SECTION((InspectOutfile& operator=(const InspectOutfile &inspect_outfile)))
InspectOutfile inspect_outfile1;
InspectOutfile inspect_outfile2;
inspect_outfile2 = inspect_outfile1;
InspectOutfile inspect_outfile3;
inspect_outfile1 = InspectOutfile();
TEST_EQUAL( (inspect_outfile2 == inspect_outfile3 ), true)
END_SECTION
START_SECTION((InspectOutfile(const InspectOutfile &inspect_outfile)))
InspectOutfile inspect_outfile1;
InspectOutfile inspect_outfile2(inspect_outfile1);
InspectOutfile inspect_outfile3;
inspect_outfile1 = InspectOutfile();
TEST_EQUAL( (inspect_outfile2 == inspect_outfile3 ), true)
END_SECTION
START_SECTION((bool operator==(const InspectOutfile &inspect_outfile) const))
InspectOutfile inspect_outfile1;
InspectOutfile inspect_outfile2;
TEST_EQUAL(( inspect_outfile1 == inspect_outfile2 ), true)
END_SECTION
InspectOutfile file;
START_SECTION(std::vector< Size > load(const String& result_filename, std::vector< PeptideIdentification >& peptide_identifications, ProteinIdentification& protein_identification, const double p_value_threshold, const String& database_filename = ""))
PeptideIdentificationList peptide_identifications;
ProteinIdentification protein_identification;
// test exceptions
TEST_EXCEPTION(Exception::IllegalArgument, file.load("", peptide_identifications, protein_identification, 2.0))
TEST_EXCEPTION(Exception::IllegalArgument, file.load("", peptide_identifications, protein_identification, -1.0))
TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.load("a", peptide_identifications, protein_identification, 0.01), "the file 'a' could not be found")
TEST_EXCEPTION_WITH_MESSAGE(Exception::FileEmpty, file.load(OPENMS_GET_TEST_DATA_PATH("Inspect_empty_file.txt"), peptide_identifications, protein_identification, 0.01), OPENMS_GET_TEST_DATA_PATH_MESSAGE("the file '","Inspect_empty_file.txt","' is empty"))
peptide_identifications.clear();
protein_identification.setHits(vector< ProteinHit >());
file.load(input_file_name, peptide_identifications, protein_identification, 0.001);
TEST_EQUAL(peptide_identifications.size(), 1)
if ( peptide_identifications.size() == 1 )
{
TEST_EQUAL(peptide_identifications[0].getHits().size(), 1)
TEST_STRING_EQUAL(peptide_identifications[0].getScoreType(), "Inspect")
TEST_REAL_SIMILAR(peptide_identifications[0].getSignificanceThreshold(), 0.001)
if( peptide_identifications[0].getHits().size() == 1)
{
TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[0].getScore(), -257)
TEST_STRING_EQUAL(peptide_identifications[0].getHits()[0].getSequence().toString(), "KKLE")
vector<PeptideEvidence> pes = peptide_identifications[0].getHits()[0].getPeptideEvidences();
TEST_EQUAL(pes[0].getAABefore(), 'E')
TEST_EQUAL(pes[0].getAAAfter(), 'K')
TEST_EQUAL(peptide_identifications[0].getHits()[0].getCharge(), 1)
TEST_EQUAL(pes.size(), 1)
TEST_STRING_EQUAL(pes[0].getProteinAccession(), "P68509")
}
}
peptide_identifications.clear();
file.load(input_file_name, peptide_identifications, protein_identification, 0.01);
TEST_EQUAL(peptide_identifications.size(), 1)
if ( peptide_identifications.size() == 1 )
{
TEST_EQUAL(peptide_identifications[0].getHits().size(), 2)
TEST_STRING_EQUAL(peptide_identifications[0].getScoreType(), "Inspect")
TEST_REAL_SIMILAR(peptide_identifications[0].getSignificanceThreshold(), 0.01)
if( peptide_identifications[0].getHits().size() == 2 )
{
TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[0].getScore(), -257)
TEST_STRING_EQUAL(peptide_identifications[0].getHits()[0].getSequence().toString(), "KKLE")
vector<PeptideEvidence> pes = peptide_identifications[0].getHits()[0].getPeptideEvidences();
TEST_EQUAL(pes[0].getAABefore(), 'E')
TEST_EQUAL(pes[0].getAAAfter(), 'K')
TEST_EQUAL(peptide_identifications[0].getHits()[0].getCharge(), 1)
TEST_EQUAL(pes.size(), 1)
TEST_STRING_EQUAL(pes[0].getProteinAccession(), "P68509")
TEST_REAL_SIMILAR(peptide_identifications[0].getHits()[1].getScore(), -1456)
TEST_STRING_EQUAL(peptide_identifications[0].getHits()[1].getSequence().toString(), "EKIE")
vector<PeptideEvidence> pes1 = peptide_identifications[0].getHits()[1].getPeptideEvidences();
TEST_EQUAL(pes1[0].getAABefore(), 'R')
TEST_EQUAL(pes1[0].getAAAfter(), 'K')
TEST_EQUAL(peptide_identifications[0].getHits()[1].getCharge(), 1)
TEST_EQUAL(pes1.size(), 1)
TEST_STRING_EQUAL(pes1[0].getProteinAccession(), "P68509")
}
}
peptide_identifications.clear();
protein_identification.setHits(vector< ProteinHit >());
TEST_EQUAL(file.load(input_file_name2, peptide_identifications, protein_identification, 0.01).size(), 1)
if ( file.load(input_file_name2, peptide_identifications, protein_identification, 0.01).size() == 1 )
{
TEST_EQUAL(file.load(input_file_name2, peptide_identifications, protein_identification, 0.01)[0], 2)
}
END_SECTION
START_SECTION(void generateTrieDB(const std::String& source_database_filename, const std::String& database_filename, const std::String& index_filename, bool append = false, const std::String species = ""))
// test exceptions
// test file not found for input file
TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.generateTrieDB("a", "", ""), "the file 'a' could not be found")
// test unable to create file
TEST_EXCEPTION(Exception::UnableToCreateFile, file.generateTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test.fasta"), OPENMS_GET_TEST_DATA_PATH("Inspect_unreadable_unwriteable.txt"), ""))
remove("InspectOutfile_test.trie");
remove("InspectOutfile_test.index");
// test the actual program
file.generateTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test.fasta"), "InspectOutfile_test.trie", "InspectOutfile_test.index");
TEST_FILE_EQUAL("InspectOutfile_test.trie", OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"))
TEST_FILE_EQUAL("InspectOutfile_test.index", OPENMS_GET_TEST_DATA_PATH("Inspect_test.index"))
remove("InspectOutfile_test.trie");
remove("InspectOutfile_test.index");
file.generateTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test2.fasta"), "InspectOutfile_test.trie", "InspectOutfile_test.index");
TEST_FILE_EQUAL("InspectOutfile_test.trie", OPENMS_GET_TEST_DATA_PATH("Inspect_test2.trie"))
TEST_FILE_EQUAL("InspectOutfile_test.index", OPENMS_GET_TEST_DATA_PATH("Inspect_test2.index"))
remove("InspectOutfile_test.trie");
remove("InspectOutfile_test.index");
END_SECTION
START_SECTION(void compressTrieDB(const String& database_filename, const String& index_filename, std::vector< Size >& wanted_records, const String& snd_database_filename, const String& snd_index_filename, bool append = false))
vector< Size > wanted_records(1, 0);
// test exceptions
remove("InspectOutfile_test.trie");
remove("InspectOutfile_test.index");
remove("InspectOutfile_test2.trie");
remove("InspectOutfile_test2.index");
// test for equal filenames
TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.compressTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"), OPENMS_GET_TEST_DATA_PATH("Inspect_test.index"), wanted_records, OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"), ""), OPENMS_GET_TEST_DATA_PATH_MESSAGE("","Inspect_test.trie"," in: Same filename can not be used for original and second database!"))
TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.compressTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"), OPENMS_GET_TEST_DATA_PATH("Inspect_test.index"), wanted_records, "", OPENMS_GET_TEST_DATA_PATH("Inspect_test.index")), OPENMS_GET_TEST_DATA_PATH_MESSAGE("","Inspect_test.index"," in: Same filename can not be used for original and second database!"))
// test file not found for input files (using empty filenames)
TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.compressTrieDB("a", "", wanted_records, "InspectOutfile_test.trie", "InspectOutfile_test.index"), "the file 'a' could not be found")
TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.compressTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"), "b", wanted_records, "InspectOutfile_test.trie", "InspectOutfile_test.index"), "the file 'b' could not be found")
// test for unable to create file
TEST_EXCEPTION(Exception::UnableToCreateFile, file.compressTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"), OPENMS_GET_TEST_DATA_PATH("Inspect_test.index"), wanted_records, OPENMS_GET_TEST_DATA_PATH("Inspect_unreadable_unwriteable.txt"), "", true))
// test for parse error
TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.compressTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"), OPENMS_GET_TEST_DATA_PATH("Inspect_empty_file.txt"), wanted_records, "InspectOutfile_test.trie", "InspectOutfile_test.index", true),OPENMS_GET_TEST_DATA_PATH_MESSAGE("", "Inspect_empty_file.txt"," in: index file is too short!"))
remove("InspectOutfile_test.trie");
remove("InspectOutfile_test.index");
wanted_records.clear();
// test the actual program
bool append = true;
wanted_records.push_back(0);
file.compressTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"), OPENMS_GET_TEST_DATA_PATH("Inspect_test.index"), wanted_records, "InspectOutfile_test.trie", "InspectOutfile_test.index", append);
wanted_records.clear();
file.compressTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test2.trie"), OPENMS_GET_TEST_DATA_PATH("Inspect_test2.index"), wanted_records, "InspectOutfile_test.trie", "InspectOutfile_test.index", append);
wanted_records.clear();
wanted_records.push_back(1);
file.compressTrieDB(OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"), OPENMS_GET_TEST_DATA_PATH("Inspect_test.index"), wanted_records, "InspectOutfile_test.trie", "InspectOutfile_test.index", append);
wanted_records.clear();
wanted_records.push_back(0);
wanted_records.push_back(3);
file.compressTrieDB("InspectOutfile_test.trie", "InspectOutfile_test.index", wanted_records, "InspectOutfile_test2.trie", "InspectOutfile_test2.index");
remove("InspectOutfile_test.trie");
remove("InspectOutfile_test.index");
TEST_FILE_EQUAL("InspectOutfile_test2.trie", OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"))
TEST_FILE_EQUAL("InspectOutfile_test2.index", OPENMS_GET_TEST_DATA_PATH("Inspect_test.index"))
remove("InspectOutfile_test2.trie");
remove("InspectOutfile_test2.index");
END_SECTION
START_SECTION(std::vector< Size > getSequences(const String& database_filename, const std::map< Size, Size >& wanted_records, std::vector< String >& sequences))
map< Size, Size > rn_position_map;
rn_position_map[0] = 0;
rn_position_map[1] = 1;
vector< String > sequences, found_sequences;
// test exceptions
TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.getSequences("a", rn_position_map, found_sequences), "the file 'a' could not be found")
found_sequences.clear();
// test actual program
sequences.push_back("GDREQLLQRARLAEQAERYDDMASAMKAVTELNEPLSNEDRNLLSVAYKNVVGARRSSWRVISSIEQKTMADGNEKKLEKVKAYREKIEKELETVCNDVLALLDKFLIKNCNDFQYESKVFYLKMKGDYYRYLAEVASGEKKNSVVEASEAAYKEAFEISKEHMQPTHPIRLGLALNFSVFYYEIQNAPEQACLLAKQAFDDAIAELDTLNEDSYKDSTLIMQLLRDNLTLWTSDQQDEEAGEGN");
sequences.push_back("SAPPSLLVLYFGKKELRAMKVLILACLVALALARELEELNVPGEIVESLSSSEESITRINKKIEKFQSEEQQQTEDELQDKIHPFAQTQSLVYPFPGPIPNSLPQNIPPLTQTPVVVPP");
file.getSequences(OPENMS_GET_TEST_DATA_PATH("Inspect_test.trie"), rn_position_map, found_sequences);
if ( found_sequences.size() == 1 )
{
TEST_STRING_EQUAL(found_sequences.front(), sequences.front())
file.getSequences(OPENMS_GET_TEST_DATA_PATH("Inspect_test2.trie"), rn_position_map, found_sequences);
TEST_EQUAL((sequences == found_sequences), true)
}
rn_position_map.clear();
sequences.clear();
found_sequences.clear();
END_SECTION
START_SECTION(void getACAndACType(String line, String& accession, String& accession_type))
String accession, accession_type;
file.getACAndACType(">sp|P02666|CASB_BOVIN Beta-casein precursor - Bos taurus (Bovine).", accession, accession_type);
TEST_STRING_EQUAL(accession, "P02666")
TEST_STRING_EQUAL(accession_type, "SwissProt")
file.getACAndACType(">tr|Q5EEQ7|Q5EEQ7_BOVIN Beta-casein (Fragment) - Bos taurus (Bovine).", accession, accession_type);
TEST_STRING_EQUAL(accession, "Q5EEQ7")
TEST_STRING_EQUAL(accession_type, "SwissProt")
file.getACAndACType("gi|110174602|gb|DQ660451.1|", accession, accession_type);
TEST_STRING_EQUAL("DQ660451.1", accession)
TEST_STRING_EQUAL("GenBank", accession_type)
file.getACAndACType("gi|1655698|emb|Y07752|VCPHEROPH", accession, accession_type);
TEST_STRING_EQUAL(accession, "Y07752")
TEST_STRING_EQUAL(accession_type, "EMBL")
file.getACAndACType("gi|10038695|dbj|BAB12730|", accession, accession_type);
TEST_STRING_EQUAL(accession, "BAB12730")
TEST_STRING_EQUAL(accession_type, "DDBJ")
file.getACAndACType("gi|9628804|ref|NP_043835|", accession, accession_type);
TEST_STRING_EQUAL(accession, "NP_043835")
TEST_STRING_EQUAL(accession_type, "NCBI")
file.getACAndACType("gi|21362794|sp|P58858.0|", accession, accession_type);
TEST_STRING_EQUAL(accession, "P58858.0")
TEST_STRING_EQUAL(accession_type, "SwissProt")
file.getACAndACType("gi|21362794|tr|P58858.0|", accession, accession_type);
TEST_STRING_EQUAL(accession, "P58858.0")
TEST_STRING_EQUAL(accession_type, "SwissProt")
file.getACAndACType("gi|1619818|gnl|PID|d1013471|", accession, accession_type);
TEST_STRING_EQUAL(accession, "d1013471")
TEST_STRING_EQUAL(accession_type, "PID")
file.getACAndACType("Q30DX2 Gamma-gliadin/LMW-glutenin chimera Ch7 (Fragment).", accession, accession_type);
TEST_STRING_EQUAL(accession, "Q30DX2")
TEST_STRING_EQUAL(accession_type, "SwissProt")
file.getACAndACType(">P68509|1433F_BOVIN", accession, accession_type);
TEST_STRING_EQUAL(accession, "P68509")
TEST_STRING_EQUAL(accession_type, "SwissProt")
file.getACAndACType(">ACBLA (P68509) F_BOVIN", accession, accession_type);
TEST_STRING_EQUAL(accession, "P68509")
TEST_STRING_EQUAL(accession_type, "SwissProt")
END_SECTION
START_SECTION(void getPrecursorRTandMZ(const vector< pair< String, vector< pair < Size, Size > > > >& files_and_peptide_identification_with_scan_number, std::vector< PeptideIdentification >& ids))
vector< pair< String, vector< pair< Size, Size > > > > files_and_peptide_identification_with_scan_number;
PeptideIdentificationList ids, ids_found;
// test exceptions
files_and_peptide_identification_with_scan_number.push_back(make_pair(spectrum_file1, vector< pair< Size, Size > >(1, make_pair(0, 10))));
TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.getPrecursorRTandMZ(files_and_peptide_identification_with_scan_number, ids_found), OPENMS_GET_TEST_DATA_PATH_MESSAGE("","InspectOutfile_test_1.mzXML"," in: Not enough scans in file! (4 available, should be at least 10)"))
files_and_peptide_identification_with_scan_number.clear();
ids.clear();
ids_found.clear();
files_and_peptide_identification_with_scan_number.push_back(make_pair(spectrum_file1, vector< pair < Size, Size > >(1, make_pair(0, 4))));
files_and_peptide_identification_with_scan_number.push_back(make_pair(spectrum_file2, vector< pair < Size, Size > >(1, make_pair(1, 4))));
ids_found.push_back(PeptideIdentification());
ids_found.push_back(PeptideIdentification());
ids.push_back(PeptideIdentification());
ids.back().setRT(-1);
ids.back().setMZ(123.456);
ids.push_back(PeptideIdentification());
ids.back().setRT(180);
ids.back().setMZ(123.456);
file.getPrecursorRTandMZ(files_and_peptide_identification_with_scan_number, ids_found);
TEST_REAL_SIMILAR(ids_found.front().getRT(), ids.front().getRT());
TEST_REAL_SIMILAR(ids_found.front().getMZ(), ids.front().getMZ());
TEST_REAL_SIMILAR(ids_found.back().getRT(), ids.back().getRT());
TEST_REAL_SIMILAR(ids_found.back().getMZ(), ids.back().getMZ());
END_SECTION
START_SECTION(void getLabels(const String& source_database_filename, String& ac_label, String& sequence_start_label, String& sequence_end_label, String& comment_label, String& species_label))
String ac_label, sequence_start_label, sequence_end_label, comment_label, species_label;
// test exceptions
TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.getLabels("a", ac_label, sequence_start_label, sequence_end_label, comment_label, species_label), "the file 'a' could not be found")
TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.getLabels(OPENMS_GET_TEST_DATA_PATH("Inspect_test1.fasta"), ac_label, sequence_start_label, sequence_end_label, comment_label, species_label), OPENMS_GET_TEST_DATA_PATH_MESSAGE("","Inspect_test1.fasta"," in: database has unknown file format (neither trie nor FASTA nor swissprot)"))
// test the actual program
file.getLabels(OPENMS_GET_TEST_DATA_PATH("Inspect_test.fasta"), ac_label, sequence_start_label, sequence_end_label, comment_label, species_label);
TEST_STRING_EQUAL(ac_label, ">")
TEST_STRING_EQUAL(sequence_start_label, ">")
TEST_STRING_EQUAL(sequence_end_label, ">")
TEST_STRING_EQUAL(comment_label, ";")
TEST_STRING_EQUAL(species_label, ">")
END_SECTION
START_SECTION(vector< Size > getWantedRecords(const String& result_filename, double p_value_threshold))
// test exceptions
TEST_EXCEPTION(Exception::IllegalArgument, file.getWantedRecords("", 2.0))
TEST_EXCEPTION(Exception::IllegalArgument, file.getWantedRecords("", -1.0))
TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.getWantedRecords("a", 0.01), "the file 'a' could not be found")
TEST_EXCEPTION_WITH_MESSAGE(Exception::FileEmpty, file.getWantedRecords(OPENMS_GET_TEST_DATA_PATH("Inspect_empty_file.txt"), 0.01), OPENMS_GET_TEST_DATA_PATH_MESSAGE("the file '","Inspect_empty_file.txt","' is empty"))
// test the actual program
vector< Size > wanted_records = file.getWantedRecords(input_file_name, 0.01);
TEST_EQUAL (wanted_records.size(), 1)
if ( !wanted_records.empty() ) TEST_EQUAL (wanted_records.front(), 0)
END_SECTION
START_SECTION(template< typename PeakT > void getExperiment(MSExperiment< PeakT >& exp, String& type, const String& in_filename))
PeakMap exp;
String type;
// test the actual program
file.getExperiment(exp, type, OPENMS_GET_TEST_DATA_PATH("Inspect.mzXML"));
TEST_STRING_EQUAL(type, "mzXML")
file.getExperiment(exp, type, OPENMS_GET_TEST_DATA_PATH("Inspect.mzData"));
TEST_STRING_EQUAL(type, "mzData")
END_SECTION
START_SECTION(bool getSearchEngineAndVersion(const String& cmd_output, ProteinIdentification& protein_identification) )
ProteinIdentification protein_identification;
protein_identification.setHits(vector< ProteinHit >());
String output = "\
InsPecT vesrion 20060907\
Interpretation of Peptides with Post-translational Modifications.\
Copyright 2006, The Regents of the University of California\
[See Docs directory for usage manual and copyright information]\
\
\
Sample command-line:\
Inspect.exe -i Foo.in -o Foo.txt -e ErrorsFoo.txt\
Command-line arguments:\
-i InputFileName: Path to a config file specifying search parameters.\
-o OutputFileName: Output file for match results. If not\
specified, output goes to stdout.\
-e ErrorFileName: Output file for errors and warnings, if any. If not\
specified, any errors go to Inspect.err; if there are no errors.\
or warnings reported, this file will be erased at end of run.\
-r ResourceDir: Directory for resource files (such \
as AminoAcidMasses.txt). Defaults to current directory. \
Consult the documentation (Inspect.html) for further details.\
";
// test the actual program
TEST_EQUAL(file.getSearchEngineAndVersion(output, protein_identification), true);
TEST_STRING_EQUAL(protein_identification.getSearchEngine(), "InsPecT");
TEST_STRING_EQUAL(protein_identification.getSearchEngineVersion(), "20060907");
output = "\
InsPecT version 20100331\
Interpretation of Peptides with Post-translational Modifications.\
Copyright 2007,2008,2009 The Regents of the University of California\
[See Docs directory for usage manual and copyright information]\
\
\
Sample command-line:\
Inspect.exe -i Foo.in -o Foo.txt -e ErrorsFoo.txt\
Command-line arguments:\
-i InputFileName: Path to a config file specifying search parameters.\
-o OutputFileName: Output file for match results. If not\
specified, output goes to stdout.\
-e ErrorFileName: Output file for errors and warnings, if any. If not\
specified, any errors go to Inspect.err; if there are no errors.\
or warnings reported, this file will be erased at end of run.\
-r ResourceDir: Directory for resource files (such\
as AminoAcidMasses.txt). Defaults to current directory.\
-a AminoAcidMassesFile: Specify a file containing non-standard amino acid masses.\
Consult the documentation (Inspect.html) for further details.";
// test the actual program
TEST_EQUAL(file.getSearchEngineAndVersion(output, protein_identification), true);
TEST_STRING_EQUAL(protein_identification.getSearchEngine(), "InsPecT");
TEST_STRING_EQUAL(protein_identification.getSearchEngineVersion(), "20100331");
END_SECTION
START_SECTION(void readOutHeader(const String& filename, const String& header_line, Int& spectrum_file_column, Int& scan_column, Int& peptide_column, Int& protein_column, Int& charge_column, Int& MQ_score_column, Int& p_value_column, Int& record_number_column, Int& DB_file_pos_column, Int& spec_file_pos_column, Size &number_of_columns))
String header_line = "#SpectrumFile Scan# Annotation Protein Charge MQScore Length TotalPRMScore MedianPRMScore FractionY FractionB Intensity NTT p-value F-Score DeltaScore DeltaScoreOther RecordNumber DBFilePos ";
Int spectrum_file_column, scan_column, peptide_column, protein_column, charge_column, MQ_score_column, p_value_column, record_number_column, DB_file_pos_column, spec_file_pos_column;
Size number_of_columns;
// test exceptions
TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.readOutHeader("dummy_testfile", header_line, spectrum_file_column, scan_column, peptide_column, protein_column, charge_column, MQ_score_column, p_value_column, record_number_column, DB_file_pos_column, spec_file_pos_column, number_of_columns), "dummy_testfile in: at least one of the columns '#SpectrumFile', 'Scan#', 'Annotation', 'Protein', 'Charge', 'MQScore', 'p-value', 'RecordNumber', 'DBFilePos' or 'SpecFilePos' is missing!")
// test the actual program
header_line = "#SpectrumFile Scan# Annotation Protein Charge MQScore Length TotalPRMScore MedianPRMScore FractionY FractionB Intensity NTT p-value F-Score DeltaScore DeltaScoreOther RecordNumber DBFilePos SpecFilePos";
file.readOutHeader("dummy_testfile", header_line, spectrum_file_column, scan_column, peptide_column, protein_column, charge_column, MQ_score_column, p_value_column, record_number_column, DB_file_pos_column, spec_file_pos_column, number_of_columns);
TEST_EQUAL(spectrum_file_column, 0)
TEST_EQUAL(scan_column, 1)
TEST_EQUAL(peptide_column, 2)
TEST_EQUAL(protein_column, 3)
TEST_EQUAL(charge_column, 4)
TEST_EQUAL(MQ_score_column, 5)
TEST_EQUAL(p_value_column, 13)
TEST_EQUAL(record_number_column, 17)
TEST_EQUAL(DB_file_pos_column, 18)
TEST_EQUAL(spec_file_pos_column, 19)
TEST_EQUAL(number_of_columns, 20)
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MSNumpressCoder_test.cpp | .cpp | 10,582 | 379 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
///////////////////////////
#include <OpenMS/FORMAT/MSNumpressCoder.h>
///////////////////////////
#include <OpenMS/CONCEPT/Types.h>
#include <cmath> /* pow */
using namespace std;
std::vector< double > setup_test_vec1()
{
std::vector< double > in;
in.push_back(100.0);
in.push_back(200.0);
in.push_back(300.00005);
in.push_back(400.00010);
return in;
}
std::vector< double > setup_test_vec2()
{
// Compute a series of values which adds small values up to 1e-9 to an
// integer value, giving raise to differences to the integer value of up to
// 2e-12 - for example:
//
// 400 10^-1
// 401.01 10^-2
// 402.002 10^-3
// 403.0003 10^-4
// 404.00004 10^-5
// 405.000005 10^-6
// 406.0000006 10^-7
// 407.00000007 10^-8
// 408.000000008 10^-9
// 409.0000000009 10^-10
// 411 10^-1
// 411.11 10^-2
// 412.012 10^-3
// 413.0013 10^-4
// 414.00014 10^-5
// 415.000015 10^-6
// 416.0000016 10^-7
// 417.00000017 10^-8
// 418.000000018 10^-9
// 419.0000000019 10^-10
//
// [ ... ]
//
// 499 10^-1
// 491.91 10^-2
// 492.092 10^-3
// 493.0093 10^-4
// 494.00094 10^-5
// 495.000095 10^-6
// 496.0000096 10^-7
// 497.00000097 10^-8
// 498.000000098 10^-9
// 499.0000000099 10^-10
//
std::vector< double > in;
for (int i = 0; i < 100; i++)
{
// compute a value 100 + i + i * exp(10, -i%10 -1)
double val = 400 + i + i * pow(10.0, -i%10 -1);
in.push_back(val);
// std::cout << val << "\t\t\t10^" << -i%10 -1 <<std::endl;
}
return in;
}
bool check_vec2_abs(std::vector<double> vec, double eps)
{
if (vec.size() != 100) return false;
for (int i = 0; i < 100; i++)
{
double val = 400 + i + i * pow(10.0, -i%10 -1);
//std::cout << val << "\t\t\tvs " << vec[i] << " diff " << fabs(val-vec[i])<<std::endl;
if (fabs(val - vec[i]) > eps) return false;
}
return true;
}
bool check_vec2_rel(std::vector<double> vec, double eps)
{
if (vec.size() != 100) return false;
for (int i = 0; i < 100; i++)
{
double val = 400 + i + i * pow(10.0, -i%10 -1);
double ratio = val / vec[i];
if (ratio < 1.0) ratio = vec[i] / val;
//std::cout << val << "\t\t\tvs " << vec[i] << " ratio " << val/vec[i]<<std::endl;
if (fabs(ratio - 1) > eps) return false;
}
return true;
}
START_TEST(MSNumpressCoder, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
// default ctor
MSNumpressCoder* ptr = nullptr;
MSNumpressCoder* nullPointer = nullptr;
START_SECTION((MSNumpressCoder()))
ptr = new MSNumpressCoder;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
// destructor
START_SECTION((virtual ~MSNumpressCoder()))
delete ptr;
END_SECTION
START_SECTION(( void encodeNP(const std::vector<double> & in, String & result, bool zlib_compression, const NumpressConfig & config)))
{
std::vector< double > in = setup_test_vec1();
String out;
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::PIC;
bool zlib_compression = false;
MSNumpressCoder().encodeNP(in, out, zlib_compression, config);
TEST_EQUAL(out.size(), 12)
}
END_SECTION
START_SECTION(( void encodeNP(const std::vector<float> & in, String & result, bool zlib_compression, const NumpressConfig & config)))
{
// tested using the encodeNP double function
NOT_TESTABLE
}
END_SECTION
START_SECTION(( void decodeNP(const String & in, std::vector<double> & out, bool zlib_compression, const NumpressConfig & config) ))
{
String in = "ZGaMXCFQkQ==";
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::PIC;
std::vector<double> out;
bool zlib_compression = false;
MSNumpressCoder().decodeNP(in, out, zlib_compression, config);
TEST_EQUAL(out.size(), 4)
TOLERANCE_ABSOLUTE(0.001)
TEST_REAL_SIMILAR(out[0], 100.0)
TEST_REAL_SIMILAR(out[0], 100.0)
TEST_REAL_SIMILAR(out[1], 200.0)
TEST_REAL_SIMILAR(out[2], 300.00005)
TEST_REAL_SIMILAR(out[3], 400.00010)
}
END_SECTION
START_SECTION(([MSNumpressCoder::NumpressConfig] NumpressConfig()))
{
MSNumpressCoder::NumpressConfig * config = new MSNumpressCoder::NumpressConfig();
MSNumpressCoder::NumpressConfig * nullConfigPtr = nullptr;
TEST_NOT_EQUAL(config, nullConfigPtr)
delete config;
}
END_SECTION
///////////////////////////////////////////////////////////////////////////
// Encode / Decode a small vector
///////////////////////////////////////////////////////////////////////////
START_SECTION([EXTRA] encodeNP_LINEAR)
{
std::vector< double > in = setup_test_vec1();
String out;
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::LINEAR;
config.estimate_fixed_point = true; // critical
bool zlib_compression = false;
MSNumpressCoder().encodeNP(in, out, zlib_compression, config);
TEST_EQUAL(out.size(), 28)
TEST_EQUAL(out, "QWR64UAAAADo//8/0P//f1kSgA==")
}
END_SECTION
START_SECTION([EXTRA] decodeNP_LINEAR)
{
String in = "QWR64UAAAADo//8/0P//f1kSgA==";
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::LINEAR;
std::vector<double> out;
bool zlib_compression = false;
MSNumpressCoder().decodeNP(in, out, zlib_compression, config);
TEST_EQUAL(out.size(), 4)
TOLERANCE_ABSOLUTE(0.001)
TEST_REAL_SIMILAR(out[0], 100.0)
TEST_REAL_SIMILAR(out[0], 100.0)
TEST_REAL_SIMILAR(out[1], 200.0)
TEST_REAL_SIMILAR(out[2], 300.00005)
TEST_REAL_SIMILAR(out[3], 400.00010)
}
END_SECTION
START_SECTION([EXTRA] encodeNP_PIC)
{
std::vector< double > in = setup_test_vec1();
String out;
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::PIC;
bool zlib_compression = false;
MSNumpressCoder().encodeNP(in, out, zlib_compression, config);
TEST_EQUAL(out.size(), 12)
TEST_EQUAL(out, "ZGaMXCFQkQ==")
}
END_SECTION
START_SECTION([EXTRA] decodeNP_PIC)
{
String in = "ZGaMXCFQkQ==";
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::PIC;
std::vector<double> out;
bool zlib_compression = false;
MSNumpressCoder().decodeNP(in, out, zlib_compression, config);
TEST_EQUAL(out.size(), 4)
TOLERANCE_ABSOLUTE(0.001)
TEST_REAL_SIMILAR(out[0], 100.0)
TEST_REAL_SIMILAR(out[0], 100.0)
TEST_REAL_SIMILAR(out[1], 200.0)
TEST_REAL_SIMILAR(out[2], 300.00005)
TEST_REAL_SIMILAR(out[3], 400.00010)
}
END_SECTION
START_SECTION([EXTRA] encodeNP_SLOF)
{
std::vector< double > in = setup_test_vec1();
String out;
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::SLOF;
config.estimate_fixed_point = true; // critical
bool zlib_compression = false;
MSNumpressCoder().encodeNP(in, out, zlib_compression, config);
TEST_EQUAL(out.size(), 24)
TEST_EQUAL(out, "QMVagAAAAAAZxX3ivPP8/w==")
}
END_SECTION
START_SECTION([EXTRA] decodeNP_SLOF)
{
String in = "QMVagAAAAAAZxX3ivPP8/w==";
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::SLOF;
std::vector<double> out;
bool zlib_compression = false;
MSNumpressCoder().decodeNP(in, out, zlib_compression, config);
TEST_EQUAL(out.size(), 4)
TOLERANCE_RELATIVE(1+ 1e-4)
TEST_REAL_SIMILAR(out[0], 100.0)
TEST_REAL_SIMILAR(out[0], 100.0)
TEST_REAL_SIMILAR(out[1], 200.0)
TEST_REAL_SIMILAR(out[2], 300.00005)
TEST_REAL_SIMILAR(out[3], 400.00010)
//MSNumpressCoder().encodeNP(in, out, zlib_compression, config);
}
END_SECTION
///////////////////////////////////////////////////////////////////////////
// Large test
///////////////////////////////////////////////////////////////////////////
START_SECTION([EXTRA] test_large_LINEAR)
{
std::vector< double > in = setup_test_vec2();
String base64_string;
std::vector<double> result;
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::LINEAR;
config.estimate_fixed_point = true; // critical
bool zlib_compression = false;
MSNumpressCoder().encodeNP(in, base64_string, zlib_compression, config);
TEST_EQUAL(base64_string.size(), 360)
MSNumpressCoder().decodeNP(base64_string, result, zlib_compression, config);
TEST_EQUAL(result.size(), 100)
TEST_EQUAL(check_vec2_abs(result, 1e-5), true)
TEST_EQUAL(check_vec2_rel(result, 0.1e-6), true) // accurate to 0.1 ppm
}
END_SECTION
START_SECTION([EXTRA] test_large_PIC)
{
std::vector< double > in = setup_test_vec2();
String base64_string;
std::vector<double> result;
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::PIC;
bool zlib_compression = false;
MSNumpressCoder().encodeNP(in, base64_string, zlib_compression, config);
TEST_EQUAL(base64_string.size(), 268)
MSNumpressCoder().decodeNP(base64_string, result, zlib_compression, config);
TEST_EQUAL(result.size(), 100)
TEST_EQUAL(check_vec2_abs(result, 0.99), true)
TEST_EQUAL(check_vec2_rel(result, 10000e-6), true) // accurate to 10 000 ppm
}
END_SECTION
START_SECTION([EXTRA] test_large_SLOF)
{
std::vector< double > in = setup_test_vec2();
String base64_string;
std::vector<double> result;
MSNumpressCoder::NumpressConfig config;
config.np_compression = MSNumpressCoder::SLOF;
config.estimate_fixed_point = true; // critical
bool zlib_compression = false;
MSNumpressCoder().encodeNP(in, base64_string, zlib_compression, config);
TEST_EQUAL(base64_string.size(), 280)
MSNumpressCoder().decodeNP(base64_string, result, zlib_compression, config);
TEST_EQUAL(result.size(), 100)
TEST_EQUAL(check_vec2_abs(result, 0.05), true)
TEST_EQUAL(check_vec2_rel(result, 100e-6), true) // accurate to 100 ppm
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ISpectrumAccess_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/ISpectrumAccess.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(ISpectrumAccess, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
ISpectrumAccess* ptr = 0;
ISpectrumAccess* null_ptr = 0;
START_SECTION(ISpectrumAccess())
{
ptr = new ISpectrumAccess();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~ISpectrumAccess())
{
delete ptr;
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IndexedMzMLFileLoader_test.cpp | .cpp | 5,755 | 184 | // 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/IndexedMzMLFileLoader.h>
#include <OpenMS/KERNEL/OnDiscMSExperiment.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(IndexedMzMLFileLoader, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IndexedMzMLFileLoader* ptr = nullptr;
IndexedMzMLFileLoader* nullPointer = nullptr;
START_SECTION((IndexedMzMLFileLoader()))
ptr = new IndexedMzMLFileLoader;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~IndexedMzMLFileLoader()))
delete ptr;
END_SECTION
START_SECTION(const PeakFileOptions& getOptions() const)
IndexedMzMLFileLoader file;
const PeakFileOptions& options = file.getOptions();
TEST_EQUAL(options.hasMSLevels(),false)
END_SECTION
START_SECTION(PeakFileOptions& getOptions())
IndexedMzMLFileLoader file;
file.getOptions().addMSLevel(1);
TEST_EQUAL(file.getOptions().hasMSLevels(),true);
END_SECTION
START_SECTION(void setOptions(const PeakFileOptions &))
IndexedMzMLFileLoader file;
const PeakFileOptions& options = file.getOptions();
TEST_EQUAL(options.hasMSLevels(),false)
TEST_EQUAL(file.getOptions().hasMSLevels(),false);
PeakFileOptions new_options(options);
new_options.addMSLevel(1);
file.setOptions(new_options);
TEST_EQUAL(file.getOptions().hasMSLevels(),true);
END_SECTION
TOLERANCE_ABSOLUTE(0.01)
START_SECTION(bool load(const String& filename, OnDiscPeakMap& exp))
{
IndexedMzMLFileLoader file;
OnDiscPeakMap exp;
file.load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp);
PeakMap exp2;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp2);
TEST_EQUAL(exp.getNrSpectra(), exp2.getSpectra().size())
TEST_EQUAL(exp.getNrChromatograms(), exp2.getChromatograms().size())
TEST_EQUAL(exp.getNrSpectra(), 2)
TEST_EQUAL(exp.getNrChromatograms(), 1)
TEST_EQUAL(exp.getSpectrum(0) == exp2.getSpectra()[0], true)
for (Size i = 0; i < exp.getNrSpectra(); i++)
{
TEST_EQUAL(exp.getSpectrum(i) == exp2.getSpectra()[i], true)
}
for (Size i = 0; i < exp.getNrChromatograms(); i++)
{
TEST_EQUAL(exp.getChromatogram(i) == exp2.getChromatograms()[i], true)
}
TEST_EQUAL(*exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp2, true)
}
END_SECTION
START_SECTION([EXTRA]CheckParsing)
{
// Check return value of load
IndexedMzMLFileLoader file;
OnDiscPeakMap exp;
bool success;
success = file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp);
TEST_EQUAL(success, false)
success = file.load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp);
TEST_EQUAL(success, true)
}
END_SECTION
START_SECTION(void store(const String& filename, OnDiscPeakMap& exp))
{
IndexedMzMLFileLoader file;
OnDiscPeakMap exp, exp_;
file.load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp_);
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
std::cout << "Storing in file " << tmp_filename << std::endl;
file.store(tmp_filename,exp_);
bool success = file.load(tmp_filename,exp);
TEST_EQUAL(success, true)
PeakMap exp2;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp2);
TEST_EQUAL(exp.getNrSpectra(), exp2.getSpectra().size())
TEST_EQUAL(exp.getNrChromatograms(), exp2.getChromatograms().size())
TEST_EQUAL(exp.getNrSpectra(), 2)
TEST_EQUAL(exp.getNrChromatograms(), 1)
TEST_EQUAL(exp.getSpectrum(0) == exp2.getSpectra()[0], true)
for (Size i = 0; i < exp.getNrSpectra(); i++)
{
TEST_EQUAL(exp.getSpectrum(i) == exp2.getSpectra()[i], true)
}
for (Size i = 0; i < exp.getNrChromatograms(); i++)
{
TEST_EQUAL(exp.getChromatogram(i) == exp2.getChromatograms()[i], true)
}
TEST_EQUAL(*exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp2, true)
}
END_SECTION
START_SECTION(void store(const String& filename, PeakMap& exp))
{
IndexedMzMLFileLoader file;
OnDiscPeakMap exp;
PeakMap exp2;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"),exp2);
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
std::cout << "Storing in file " << tmp_filename << std::endl;
file.store(tmp_filename,exp2);
bool success = file.load(tmp_filename,exp);
TEST_EQUAL(success, true)
TEST_EQUAL(exp.getNrSpectra(), exp2.getSpectra().size())
TEST_EQUAL(exp.getNrChromatograms(), exp2.getChromatograms().size())
TEST_EQUAL(exp.getNrSpectra(), 2)
TEST_EQUAL(exp.getNrChromatograms(), 1)
TEST_EQUAL(exp.getSpectrum(0) == exp2.getSpectra()[0], true)
for (Size i = 0; i < exp.getNrSpectra(); i++)
{
TEST_EQUAL(exp.getSpectrum(i) == exp2.getSpectra()[i], true)
}
for (Size i = 0; i < exp.getNrChromatograms(); i++)
{
TEST_EQUAL(exp.getChromatogram(i) == exp2.getChromatograms()[i], true)
}
TEST_EQUAL(*exp.getExperimentalSettings() == (OpenMS::ExperimentalSettings)exp2, true)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MSNumpress_test.cpp | .cpp | 1,014 | 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/FORMAT/MSNUMPRESS/MSNumpress.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MSNumpress, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MSNumpress* ptr = 0;
MSNumpress* null_ptr = 0;
START_SECTION(MSNumpress())
{
ptr = new MSNumpress();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~MSNumpress())
{
delete ptr;
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/QTCluster_test.cpp | .cpp | 6,653 | 267 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/QTCluster.h>
///////////////////////////
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/DATASTRUCTURES/GridFeature.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/KERNEL/BaseFeature.h>
START_TEST(QTCluster, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
QTCluster* qtc_ptr = nullptr;
QTCluster* qtc_nullPointer = nullptr;
QTCluster::BulkData* qtc_data_ptr = nullptr;
BaseFeature bf;
bf.setRT(1.1);
bf.setMZ(2.2);
bf.setCharge(3);
bf.getPeptideIdentifications().resize(2);
PeptideHit hit;
hit.setSequence(AASequence::fromString("AAA"));
bf.getPeptideIdentifications()[0].insertHit(hit);
hit.setSequence(AASequence::fromString("CCC"));
bf.getPeptideIdentifications()[1].insertHit(hit);
GridFeature gf(bf, 123, 456);
START_SECTION((QTCluster::BulkData(const OpenMS::GridFeature* const center_point, Size num_maps, double max_distance, Int x_coord, Int y_coord, Size id)))
{
qtc_data_ptr = new QTCluster::BulkData(&gf, 2, 11.1, 0, 0, 0);
TEST_NOT_EQUAL(qtc_data_ptr, qtc_nullPointer);
}
END_SECTION
START_SECTION((QTCluster(BulkData* const data, bool use_IDs)))
{
qtc_ptr = new QTCluster(qtc_data_ptr, false);
TEST_NOT_EQUAL(qtc_ptr, qtc_nullPointer);
}
END_SECTION
START_SECTION((~QTCluster()))
{
delete qtc_ptr;
}
END_SECTION
START_SECTION((QTCluster::~BulkData()))
{
delete qtc_data_ptr;
}
END_SECTION
QTCluster::BulkData qtc_data(&gf, 2, 11.1, 7, 9, 1);
QTCluster cluster(&qtc_data, true);
START_SECTION((double getCenterRT() const))
{
TEST_EQUAL(cluster.getCenterRT(), 1.1);
}
END_SECTION
START_SECTION((double getCenterMZ() const))
{
TEST_EQUAL(cluster.getCenterMZ(), 2.2);
}
END_SECTION
START_SECTION((Int getXCoord() const))
{
TEST_EQUAL(cluster.getXCoord(), 7);
}
END_SECTION
START_SECTION((Int getYCoord() const))
{
TEST_EQUAL(cluster.getYCoord(), 9);
}
END_SECTION
START_SECTION((Size getId() const))
{
TEST_EQUAL(cluster.getId(), 1);
}
END_SECTION
START_SECTION((Size size() const))
{
TEST_EQUAL(cluster.size(), 1);
}
END_SECTION
GridFeature gf2(bf, 789, 1011);
START_SECTION((void add(const GridFeature* const element, double distance)))
{
cluster.initializeCluster();
cluster.add(&gf2, 3.3);
cluster.finalizeCluster();
TEST_EQUAL(cluster.size(), 2);
}
END_SECTION
START_SECTION((bool operator<(QTCluster& cluster)))
{
QTCluster::BulkData data(&gf, 2, 11.1, 0, 0, 2);
QTCluster cluster2(&data, false);
TEST_EQUAL(cluster2 < cluster, true);
}
END_SECTION
START_SECTION((QTCluster::Elements getElements() const))
{
QTCluster::Elements elements = cluster.getElements();
TEST_EQUAL(elements.size(), 2);
if (elements[0].feature != &gf)
{
TEST_EQUAL(elements[0].feature, &gf2);
TEST_EQUAL(elements[1].feature, &gf);
}
else
{
TEST_EQUAL(elements[0].feature, &gf);
TEST_EQUAL(elements[1].feature, &gf2);
}
}
END_SECTION
START_SECTION((QTCluster::Elements getAllNeighbors() const))
{
GridFeature gf3(bf, 789, 1012);
GridFeature gf4(bf, 222, 1011);
QTCluster::BulkData data(&gf, 2, 11.1, 0, 0, 2);
QTCluster cluster2(&data, false);
TEST_EQUAL(cluster2.getAllNeighbors().size(), 0)
cluster2.initializeCluster();
cluster2.add(&gf2, 3.3);
cluster2.finalizeCluster();
TEST_EQUAL(cluster2.getAllNeighbors().size(), 1)
TEST_EQUAL(cluster2.getAllNeighbors()[0].feature, &gf2)
// adding a better feature from the same map does not increase neighbor size
cluster2.initializeCluster();
cluster2.add(&gf3, 3.0);
cluster2.finalizeCluster();
TEST_EQUAL(cluster2.getAllNeighbors().size(), 1)
TEST_EQUAL(cluster2.getAllNeighbors()[0].feature, &gf3)
// adding features from a new map will increase neighbor size
cluster2.initializeCluster();
cluster2.add(&gf4, 3.9);
cluster2.add(&gf4, 3.2);
cluster2.add(&gf4, 3.1);
cluster2.add(&gf4, 3.8);
cluster2.finalizeCluster();
QTCluster::Elements neighbors = cluster2.getAllNeighbors();
TEST_EQUAL(neighbors.size(), 2)
if (neighbors[0].feature != &gf3)
{
TEST_EQUAL(neighbors[0].feature, &gf4);
TEST_EQUAL(neighbors[1].feature, &gf3);
}
else
{
TEST_EQUAL(neighbors[0].feature, &gf3);
TEST_EQUAL(neighbors[1].feature, &gf4);
}
}
END_SECTION
START_SECTION(bool update(const QTCluster::Elements& removed))
{
QTCluster::Elements removed;
removed.push_back({789, &gf2});
TEST_EQUAL(cluster.update(removed), true);
TEST_EQUAL(cluster.size(), 1);
removed.push_back({123, &gf});
// removing the center invalidates the cluster:
TEST_EQUAL(cluster.update(removed), false);
TEST_EQUAL(cluster.isInvalid(), true);
}
END_SECTION
QTCluster::BulkData qtc_data2(&gf, 2, 11.1, 7, 9, 3);
START_SECTION((double getQuality()))
{
// cluster is invalid, we shouldn't use it any more -> create a new one
TEST_EQUAL(cluster.isInvalid(), true);
cluster = QTCluster(&qtc_data2, true);
cluster.initializeCluster();
cluster.add(&gf2, 3.3);
cluster.finalizeCluster();
TEST_EQUAL(cluster.getQuality(), (11.1 - 3.3) / 11.1);
TEST_EQUAL(cluster.isInvalid(), false);
}
END_SECTION
START_SECTION(double getCurrentQuality() const)
{
TEST_EQUAL(cluster.getCurrentQuality(), cluster.getQuality());
}
END_SECTION
START_SECTION((const set<AASequence>& getAnnotations()))
{
TEST_EQUAL(cluster.getAnnotations().size(), 1);
TEST_EQUAL(*(cluster.getAnnotations().begin()), AASequence::fromString("AAA"));
QTCluster::BulkData data(&gf, 2, 11.1, 0, 0, 2);
QTCluster cluster2(&data, false);
TEST_EQUAL(cluster2.getAnnotations().empty(), true);
}
END_SECTION
START_SECTION((inline bool isInvalid() const))
{
TEST_EQUAL(cluster.isInvalid(), false);
}
END_SECTION
START_SECTION((void setInvalid()))
{
cluster.setInvalid();
TEST_EQUAL(cluster.isInvalid(), true);
}
END_SECTION
START_SECTION((void finalizeCluster() ))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((void initializeCluster() ))
{
NOT_TESTABLE // tested above
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MapAlignmentEvaluationAlgorithmRecall_test.cpp | .cpp | 2,068 | 60 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Katharina Albers $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentEvaluationAlgorithmRecall.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(MapAlignmentEvaluationAlgorithmRecall, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MapAlignmentEvaluationAlgorithmRecall* ptr = nullptr;
MapAlignmentEvaluationAlgorithmRecall* nullPointer = nullptr;
START_SECTION((MapAlignmentEvaluationAlgorithmRecall()))
ptr = new MapAlignmentEvaluationAlgorithmRecall();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~MapAlignmentEvaluationAlgorithmRecall()))
delete ptr;
END_SECTION
START_SECTION((virtual void evaluate(const ConsensusMap &consensus_map_in, const ConsensusMap &consensus_map_gt, const double &rt_dev, const double &mz_dev, const Peak2D::IntensityType &int_dev, const bool use_charge, double &out)))
MapAlignmentEvaluationAlgorithmRecall maea;
ConsensusMap in;
ConsensusMap gt;
double out;
ConsensusXMLFile consensus_xml_file_in;
consensus_xml_file_in.load( OPENMS_GET_TEST_DATA_PATH("MapAlignmentEvaluationAlgorithm_in.consensusXML"), in );
ConsensusXMLFile consensus_xml_file_gt;
consensus_xml_file_gt.load( OPENMS_GET_TEST_DATA_PATH("MapAlignmentEvaluationAlgorithm_gt.consensusXML"), gt );
maea.evaluate(in, gt, 0.1, 0.1, 100, true, out);
TEST_REAL_SIMILAR(out, 0.5)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MzMLSqliteSwathHandler_test.cpp | .cpp | 3,197 | 106 | // 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/MzMLSqliteSwathHandler.h>
///////////////////////////
#include <OpenMS/FORMAT/SqMassFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <QFile>
using namespace OpenMS;
using namespace OpenMS::Internal;
using namespace std;
///////////////////////////
START_TEST(SqMassFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MzMLSqliteSwathHandler* ptr = nullptr;
MzMLSqliteSwathHandler* nullPointer = nullptr;
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
MSExperiment exp_orig;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("SwathFile.mzML"), exp_orig);
SqMassFile file;
file.store(tmp_filename, exp_orig);
START_SECTION((MzMLSqliteSwathHandler()))
ptr = new MzMLSqliteSwathHandler(tmp_filename);
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~MzMLSqliteSwathHandler()))
delete ptr;
END_SECTION
TOLERANCE_RELATIVE(1.0005)
START_SECTION(std::vector<OpenSwath::SwathMap> readSwathWindows())
{
MzMLSqliteSwathHandler handler(tmp_filename);
std::vector<OpenSwath::SwathMap> maps = handler.readSwathWindows();
TEST_EQUAL(maps.size(), 5)
TEST_EQUAL(maps[0].ms1, false)
TEST_REAL_SIMILAR(maps[0].lower, 400.0)
TEST_REAL_SIMILAR(maps[0].center, 412.5)
TEST_REAL_SIMILAR(maps[0].upper, 425.0)
TEST_REAL_SIMILAR(maps[1].lower, 425.0)
TEST_REAL_SIMILAR(maps[1].upper, 450.0)
TEST_REAL_SIMILAR(maps[4].lower, 500.0)
TEST_REAL_SIMILAR(maps[4].upper, 525.0)
}
END_SECTION
START_SECTION(std::vector<int> readMS1Spectra())
{
MzMLSqliteSwathHandler handler(tmp_filename);
TEST_EQUAL(handler.readMS1Spectra().size(), 19)
TEST_EQUAL(handler.readMS1Spectra()[0], 0)
TEST_EQUAL(handler.readMS1Spectra()[18], 108)
}
END_SECTION
START_SECTION(std::vector<int> readSpectraForWindow(const OpenSwath::SwathMap& swath_map))
{
MzMLSqliteSwathHandler handler(tmp_filename);
std::vector<OpenSwath::SwathMap> maps = handler.readSwathWindows();
TEST_EQUAL(maps.size(), 5)
TEST_EQUAL(handler.readSpectraForWindow(maps[0]).size(), 19)
TEST_EQUAL(handler.readSpectraForWindow(maps[0])[0], 1)
TEST_EQUAL(handler.readSpectraForWindow(maps[0])[18], 109)
TEST_EQUAL(handler.readSpectraForWindow(maps[1]).size(), 19)
TEST_EQUAL(handler.readSpectraForWindow(maps[1])[0], 2)
TEST_EQUAL(handler.readSpectraForWindow(maps[1])[18], 110)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SpectrumAccessQuadMZTransforming_test.cpp | .cpp | 6,090 | 155 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h>
///////////////////////////
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessQuadMZTransforming.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
std::shared_ptr<PeakMap > getData()
{
std::shared_ptr<PeakMap > exp2(new PeakMap);
MSSpectrum spec;
Peak1D p;
p.setMZ(100);
p.setIntensity(50);
spec.push_back(p);
p.setMZ(500);
p.setIntensity(150);
spec.push_back(p);
exp2->addSpectrum(spec);
return exp2;
}
START_TEST(SpectrumAccessQuadMZTransforming, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
SpectrumAccessQuadMZTransforming* ptr = nullptr;
SpectrumAccessQuadMZTransforming* nullPointer = nullptr;
std::shared_ptr<PeakMap > exp(new PeakMap);
OpenSwath::SpectrumAccessPtr expptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp);
START_SECTION(SpectrumAccessQuadMZTransforming())
{
ptr = new SpectrumAccessQuadMZTransforming(expptr, 0, 0, 0, false);
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~SpectrumAccessQuadMZTransforming())
{
delete ptr;
}
END_SECTION
START_SECTION(size_t getNrSpectra() const)
{
std::shared_ptr<SpectrumAccessQuadMZTransforming> ptr(new SpectrumAccessQuadMZTransforming(expptr, 0, 0, 0, false));
TEST_EQUAL(ptr->getNrSpectra(), 0)
std::shared_ptr<PeakMap > exp2 = getData();
OpenSwath::SpectrumAccessPtr expptr2 = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp2);
std::shared_ptr<SpectrumAccessQuadMZTransforming> ptr2(new SpectrumAccessQuadMZTransforming(expptr2, 0, 0, 0, false));
TEST_EQUAL(ptr2->getNrSpectra(), 1)
}
END_SECTION
START_SECTION(OpenSwath::SpectrumPtr getSpectrumById(int id))
{
{
std::shared_ptr<PeakMap > exp2 = getData();
OpenSwath::SpectrumAccessPtr expptr2 = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp2);
std::shared_ptr<SpectrumAccessQuadMZTransforming> ptr2(new SpectrumAccessQuadMZTransforming(expptr2, 0, 0, 0, false));
OpenSwath::SpectrumPtr spec1 = ptr2->getSpectrumById(0);
TEST_NOT_EQUAL(spec1.get(), nullPointer) // pointer is present
TEST_EQUAL(bool(spec1), true) // pointer is not null
TEST_EQUAL(spec1->getMZArray()->data.size(), 2)
TEST_EQUAL(spec1->getIntensityArray()->data.size(), 2)
TEST_REAL_SIMILAR(spec1->getIntensityArray()->data[0], 50)
TEST_REAL_SIMILAR(spec1->getIntensityArray()->data[1], 150)
TEST_REAL_SIMILAR(spec1->getMZArray()->data[0], 0)
TEST_REAL_SIMILAR(spec1->getMZArray()->data[1], 0)
}
{
std::shared_ptr<PeakMap > exp2 = getData();
OpenSwath::SpectrumAccessPtr expptr2 = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp2);
std::shared_ptr<SpectrumAccessQuadMZTransforming> ptr2(new SpectrumAccessQuadMZTransforming(expptr2, 10, 5, 2, false));
OpenSwath::SpectrumPtr spec1 = ptr2->getSpectrumById(0);
TEST_NOT_EQUAL(spec1.get(), nullPointer) // pointer is present
TEST_EQUAL(bool(spec1), true) // pointer is not null
TEST_EQUAL(spec1->getMZArray()->data.size(), 2)
TEST_EQUAL(spec1->getIntensityArray()->data.size(), 2)
TEST_REAL_SIMILAR(spec1->getIntensityArray()->data[0], 50)
TEST_REAL_SIMILAR(spec1->getIntensityArray()->data[1], 150)
TEST_REAL_SIMILAR(spec1->getMZArray()->data[0], 10 + 100*5 + 100*100* 2)
TEST_REAL_SIMILAR(spec1->getMZArray()->data[1], 10 + 500*5 + 500*500* 2)
}
}
END_SECTION
START_SECTION(std::shared_ptr<OpenSwath::ISpectrumAccess> lightClone() const)
{
std::shared_ptr<SpectrumAccessQuadMZTransforming> ptr(new SpectrumAccessQuadMZTransforming(expptr, 0, 0, 0, false));
std::shared_ptr<OpenSwath::ISpectrumAccess> clone_ptr_empty = ptr->lightClone();
TEST_EQUAL(ptr->getNrSpectra(), clone_ptr_empty->getNrSpectra())
{
std::shared_ptr<PeakMap > exp2 = getData();
OpenSwath::SpectrumAccessPtr expptr2 = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp2);
std::shared_ptr<SpectrumAccessQuadMZTransforming> ptr2(new SpectrumAccessQuadMZTransforming(expptr2, 10, 5, 2, false));
OpenSwath::SpectrumPtr spec1 = ptr2->getSpectrumById(0);
TEST_NOT_EQUAL(spec1.get(), nullPointer) // pointer is present
TEST_EQUAL(bool(spec1), true) // pointer is not null
TEST_EQUAL(spec1->getMZArray()->data.size(), 2)
TEST_EQUAL(spec1->getIntensityArray()->data.size(), 2)
TEST_REAL_SIMILAR(spec1->getIntensityArray()->data[0], 50)
TEST_REAL_SIMILAR(spec1->getIntensityArray()->data[1], 150)
TEST_REAL_SIMILAR(spec1->getMZArray()->data[0], 10 + 100*5 + 100*100* 2)
TEST_REAL_SIMILAR(spec1->getMZArray()->data[1], 10 + 500*5 + 500*500* 2)
std::shared_ptr<OpenSwath::ISpectrumAccess> clone_ptr = ptr2->lightClone();
TEST_EQUAL(ptr2->getNrSpectra(), clone_ptr->getNrSpectra())
OpenSwath::SpectrumPtr spec_clone = ptr2->getSpectrumById(0);
TEST_NOT_EQUAL(spec_clone.get(), nullPointer) // pointer is present
TEST_EQUAL(bool(spec_clone), true) // pointer is not null
TEST_EQUAL(spec_clone->getMZArray()->data.size(), 2)
TEST_EQUAL(spec_clone->getIntensityArray()->data.size(), 2)
TEST_REAL_SIMILAR(spec_clone->getIntensityArray()->data[0], 50)
TEST_REAL_SIMILAR(spec_clone->getIntensityArray()->data[1], 150)
TEST_REAL_SIMILAR(spec_clone->getMZArray()->data[0], 10 + 100*5 + 100*100* 2)
TEST_REAL_SIMILAR(spec_clone->getMZArray()->data[1], 10 + 500*5 + 500*500* 2)
}
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/XMLFile_test.cpp | .cpp | 3,844 | 89 | // 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/XMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
///////////////////////////
START_TEST(XMLFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace OpenMS::Internal;
using namespace std;
XMLFile* ptr = nullptr;
XMLFile* nullPointer = nullptr;
START_SECTION(XMLFile())
ptr = new XMLFile();
TEST_NOT_EQUAL(ptr,nullPointer)
END_SECTION
START_SECTION(~XMLFile())
delete ptr;
END_SECTION
START_SECTION(XMLFile(const String &schema_location, const String &version))
NOT_TESTABLE
END_SECTION
START_SECTION(bool isValid(const String &filename, std::ostream& os = std::cerr) )
XMLFile f("","");
TEST_EXCEPTION(Exception::NotImplemented, f.isValid("", std::cerr))
END_SECTION
START_SECTION(const String& getVersion() const)
XMLFile f("","1.567");
TEST_EQUAL( f.getVersion(),"1.567")
END_SECTION
START_SECTION(([EXTRA] String writeXMLEscape(const String& to_escape)))
String s1("nothing_to_escape. Just a regular string...");
String s2("This string contains an ampersand, &, which must be escaped.");
String s3("This string also contains characters which is not allowed, and must be escaped; the characters are '>' and \"<\"");
TEST_STRING_EQUAL(XMLHandler::writeXMLEscape(s1), "nothing_to_escape. Just a regular string...")
TEST_STRING_EQUAL(XMLHandler::writeXMLEscape(s2), "This string contains an ampersand, &, which must be escaped.")
TEST_STRING_EQUAL(XMLHandler::writeXMLEscape(s3), "This string also contains characters which is not allowed, and must be escaped; the characters are '>' and "<"");
END_SECTION
START_SECTION(static DataValue fromXSDString(const String& type, const String& value))
{
TEST_EQUAL((Int64)XMLHandler::fromXSDString("xsd:int", "2147483647"), 2147483647)
TEST_EQUAL((Int64)XMLHandler::fromXSDString("xsd:long", "9223372036854775807"), 9223372036854775807)
TEST_EQUAL((double)XMLHandler::fromXSDString("xsd:decimal", "123.45"), 123.45)
TEST_EQUAL((Int64)XMLHandler::fromXSDString("xsd:unsignedLong", "9223372036854775807"), 9223372036854775807)
// input exceeds valid range
TEST_EXCEPTION(Exception::ConversionError, XMLHandler::fromXSDString("xsd:int", "2147483648")) // +1 larger than 2^31-1
TEST_EXCEPTION(Exception::ConversionError, XMLHandler::fromXSDString("xsd:long", "9223372036854775808")) // +1 larger than 2^63-1
// things we SHOULD support, but don't, due to using a signed 64bit type in DataValue
TEST_EXCEPTION(Exception::ConversionError, XMLHandler::fromXSDString("xsd:unsignedLong", "9223372036854775808")) // +1 larger than 2^63-1; 'xsd:unsignedLong' up to 2^64-1
// things which are really hard to support (arbitrarily large numbers)
TEST_EXCEPTION(Exception::ConversionError, XMLHandler::fromXSDString("xsd:integer", "9223372036854775808")) // +1 larger than 2^63-1; 'xsd:integer' can be any number... hard to support :)
TEST_EXCEPTION(Exception::ConversionError,
XMLHandler::fromXSDString("xsd:negativeInteger", "-9223372036854775809")) // -1 smaller than 2^63; 'xsd:negativeInteger' can be any negative number... hard to support :)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/DeconvolvedSpectrum_test.cpp | .cpp | 6,503 | 213 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Jihyung Kim$
// $Authors: Jihyung Kim$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h>
#include <OpenMS/ANALYSIS/TOPDOWN/SpectralDeconvolution.h>
#include <OpenMS/FORMAT/MzMLFile.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(DeconvolvedSpectrum, "$Id$")
// load test data
PeakMap input;
MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("FLASHDeconv_sample_input1.mzML"), input);
MSSpectrum test_spec = input[0];
SpectralDeconvolution fd_algo = SpectralDeconvolution();
Param fd_param;
fd_param.setValue("min_charge", 5);
fd_param.setValue("max_charge", 20);
fd_algo.setParameters(fd_param);
fd_algo.calculateAveragine(false);
fd_algo.performSpectrumDeconvolution(input[1], 2, PeakGroup());
DeconvolvedSpectrum prec_deconv_spec_1 = fd_algo.getDeconvolvedSpectrum();
fd_algo.performSpectrumDeconvolution(input[3], 4, PeakGroup());
DeconvolvedSpectrum prec_deconv_spec_2 = fd_algo.getDeconvolvedSpectrum();
fd_algo.performSpectrumDeconvolution(input[5], 6, PeakGroup());
DeconvolvedSpectrum ms2_deconv_spec = fd_algo.getDeconvolvedSpectrum();
DeconvolvedSpectrum test_deconv_spec = DeconvolvedSpectrum(1);
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
DeconvolvedSpectrum* ptr = 0;
DeconvolvedSpectrum* null_ptr = 0;
START_SECTION(DeconvolvedSpectrum())
ptr = new DeconvolvedSpectrum();
TEST_NOT_EQUAL(ptr, null_ptr)
END_SECTION
START_SECTION(~DeconvolvedSpectrum())
delete ptr;
END_SECTION
START_SECTION(DeconvolvedSpectrum(const DeconvolvedSpectrum&))
DeconvolvedSpectrum original_spec(1);
original_spec.setOriginalSpectrum(test_spec);
DeconvolvedSpectrum copied_spec(original_spec);
TEST_EQUAL(copied_spec.getScanNumber(), original_spec.getScanNumber());
TEST_EQUAL(copied_spec.getOriginalSpectrum().size(), original_spec.getOriginalSpectrum().size());
END_SECTION
START_SECTION(DeconvolvedSpectrum&& other)
DeconvolvedSpectrum original_spec(1);
original_spec.setOriginalSpectrum(test_spec);
DeconvolvedSpectrum moved_spec(std::move(original_spec));
TEST_EQUAL(moved_spec.getScanNumber(), 1);
TEST_EQUAL(moved_spec.getOriginalSpectrum().size(), test_spec.size());
END_SECTION
START_SECTION(=(const DeconvolvedSpectrum& deconvolved_spectrum))
DeconvolvedSpectrum spec1(1);
spec1.setOriginalSpectrum(test_spec);
DeconvolvedSpectrum spec2;
spec2 = spec1;
TEST_EQUAL(spec2.getScanNumber(), spec1.getScanNumber());
TEST_EQUAL(spec2.getOriginalSpectrum().size(), spec1.getOriginalSpectrum().size());
END_SECTION
START_SECTION((MSSpectrum toSpectrum(const int mass_charge)))
{
MSSpectrum peakgroup_spec = prec_deconv_spec_1.toSpectrum(9, 1);
TEST_EQUAL(peakgroup_spec.size(), 1);
TEST_REAL_SIMILAR(peakgroup_spec.getRT(), 251.72280736002);
}
END_SECTION
START_SECTION((const MSSpectrum& getOriginalSpectrum() const))
{
MSSpectrum tmp_s = test_deconv_spec.getOriginalSpectrum();
TEST_EQUAL(tmp_s.size(), test_spec.size());
}
END_SECTION
/// detailed constructor
START_SECTION((DeconvolvedSpectrum(const MSSpectrum &spectrum, const int scan_number)))
{
DeconvolvedSpectrum tmp_spec = DeconvolvedSpectrum(1);
tmp_spec.setOriginalSpectrum(test_spec);
TEST_EQUAL(tmp_spec.getScanNumber(), 1);
TEST_EQUAL(tmp_spec.getOriginalSpectrum().size(), test_spec.size());
}
END_SECTION
////////
START_SECTION((int getScanNumber() const))
{
test_deconv_spec.setOriginalSpectrum(test_spec);
int tmp_num = test_deconv_spec.getScanNumber();
TEST_EQUAL(tmp_num, 1);
}
END_SECTION
START_SECTION((double getCurrentMaxMass(const double max_mass) const))
{
double ms1_max_mass = test_deconv_spec.getCurrentMaxMass(1000.);
double ms2_max_mass = ms2_deconv_spec.getCurrentMaxMass(13673.239337872);
TOLERANCE_ABSOLUTE(1);
TEST_REAL_SIMILAR(ms1_max_mass, 1000.);
TEST_REAL_SIMILAR(ms2_max_mass, 13674.);
}
END_SECTION
START_SECTION((double getCurrentMinMass(const double min_mass) const))
{
double ms1_min_mass = test_deconv_spec.getCurrentMinMass(1000.);
double ms2_min_mass = ms2_deconv_spec.getCurrentMinMass(1000.);
TEST_REAL_SIMILAR(ms1_min_mass, 1000.);
TEST_REAL_SIMILAR(ms2_min_mass, 50.);
}
END_SECTION
START_SECTION((PeakGroup getPrecursorPeakGroup() const))
{
PeakGroup tmp_precursor_pgs = ms2_deconv_spec.getPrecursorPeakGroup();
TEST_EQUAL(tmp_precursor_pgs.size(), 0);
TOLERANCE_ABSOLUTE(5);
TEST_REAL_SIMILAR(tmp_precursor_pgs.getMonoMass(), -1);
TEST_REAL_SIMILAR(tmp_precursor_pgs.getIntensity(), 0);
TEST_EQUAL(tmp_precursor_pgs.getScanNumber(), 0);
}
END_SECTION
START_SECTION((const Precursor getPrecursor() const))
{
Precursor tmp_precursor = ms2_deconv_spec.getPrecursor();
TEST_EQUAL(tmp_precursor.getCharge(), 9);
TOLERANCE_ABSOLUTE(10);
TEST_REAL_SIMILAR(tmp_precursor.getUnchargedMass(), 13682.3053614085);
TEST_REAL_SIMILAR(tmp_precursor.getIntensity(), 12293.4);
}
END_SECTION
START_SECTION((int getPrecursorCharge() const))
{
int prec_cs = ms2_deconv_spec.getPrecursorCharge();
TEST_EQUAL(prec_cs, 9);
}
END_SECTION
START_SECTION((int getPrecursorScanNumber() const))
{
int p_scan_num = ms2_deconv_spec.getPrecursorScanNumber();
TEST_EQUAL(p_scan_num, 0);
}
END_SECTION
START_SECTION((int getCurrentMaxAbsCharge(const int max_abs_charge) const))
{
int tmp_cs_ms1 = test_deconv_spec.getCurrentMaxAbsCharge(5);
int tmp_cs_ms2 = ms2_deconv_spec.getCurrentMaxAbsCharge(5);
TEST_EQUAL(tmp_cs_ms1, 5);
TEST_EQUAL(tmp_cs_ms2, 5);
}
END_SECTION
START_SECTION(String& getActivationMethod() const)
{
Precursor::ActivationMethod act_method = ms2_deconv_spec.getActivationMethod();
TEST_EQUAL(Precursor::ActivationMethod::ETD, act_method); // TODO: why ETD?
}
END_SECTION
////////
/// < public methods without tests > : TODOs
/// - default constructors and operators are not used (copy, move, assignment)
/// - setters (setPrecursor, etc.)
/// - updatePeakGroupQvalues
/// - nested stuff
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SpectrumAnnotator_test.cpp | .cpp | 7,590 | 213 | // 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/CHEMISTRY/SpectrumAnnotator.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <algorithm>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(SpectrumAnnotator, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
SpectrumAnnotator* ptr = nullptr;
SpectrumAnnotator* null_ptr = nullptr;
START_SECTION(SpectrumAnnotator())
{
ptr = new SpectrumAnnotator();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~SpectrumAnnotator())
{
delete ptr;
}
END_SECTION
TheoreticalSpectrumGenerator tg = TheoreticalSpectrumGenerator();
Param tgp(tg.getDefaults());
tgp.setValue("add_metainfo", "true");
tgp.setValue("add_y_ions", "true");
tgp.setValue("add_b_ions", "true");
tg.setParameters(tgp);
SpectrumAlignment sa;
Param sap = sa.getDefaults();
sap.setValue("tolerance", 0.1, "...");
sa.setParameters(sap);
SpectrumAnnotator annot;
AASequence peptide = AASequence::fromString("IFSQVGK");
PeptideHit hit;
hit.setSequence(peptide);
hit.setCharge(2);
PeakSpectrum spec;
spec.setMSLevel(2);
Peak1D p;
double peaklist[] = {147.113, 204.135, 303.203, 431.262, 518.294, 665.362, 261.16, 348.192, 476.251, 575.319, 632.341};
size_t pls = 11; // peaklist size
for (Size i = 0; i != pls; ++i)
{
p.setIntensity(1.1f);
p.setMZ(peaklist[i]);
spec.push_back(p);
}
PeptideIdentification pi;
pi.setHits(std::vector<PeptideHit>(1,hit));
START_SECTION((void SpectrumAnnotator::annotateMatches(PeakSpectrum& spec, const PeptideHit& ph, const TheoreticalSpectrumGenerator& tg, const SpectrumAlignment& sa) const))
annot.annotateMatches(spec, hit, tg, sa);
string annotlist[] = {"y1+", "y2+", "b2+", "y3+", "b3+", "y4+", "b4+", "y5+", "b5+", "b6+", "y6+"};
PeakSpectrum::StringDataArray types = spec.getStringDataArrays().front();
ABORT_IF(spec.size() != types.size() || types.size() != pls)
for (size_t i = 0; i < spec.size(); ++i)
{
TEST_STRING_EQUAL(types[i], annotlist[i])
}
TEST_REAL_SIMILAR(spec.getMetaValue("fragment_mass_tolerance"),0.1)
END_SECTION
START_SECTION((void SpectrumAnnotator::addIonMatchStatistics(PeptideIdentification& pi, const MSSpectrum& spec, const TheoreticalSpectrumGenerator& tg, const SpectrumAlignment& sa) const))
annot.addIonMatchStatistics(pi,spec,tg,sa);
for (size_t i = 0; i < pi.getHits().size(); ++i)
{
TEST_EQUAL(pi.getHits()[i].getMetaValue("peak_number"),11)
TEST_EQUAL(pi.getHits()[i].getMetaValue("sum_intensity"),12.1)
TEST_EQUAL(pi.getHits()[i].getMetaValue("matched_ion_number"),11)
TEST_EQUAL(pi.getHits()[i].getMetaValue("matched_intensity"),12.1)
TEST_STRING_EQUAL(pi.getHits()[i].getMetaValue("matched_ions"),"y1+,y2+,b2+,y3+,b3+,y4+,b4+,y5+,b5+,b6+,y6+")
TEST_STRING_EQUAL(pi.getHits()[i].getMetaValue("max_series_type"),"y")
TEST_EQUAL(pi.getHits()[i].getMetaValue("max_series_size"),6)
TEST_REAL_SIMILAR(pi.getHits()[i].getMetaValue("sn_by_matched_intensity"),0)
TEST_REAL_SIMILAR(pi.getHits()[i].getMetaValue("sn_by_median_intensity"),0)
TEST_EQUAL(pi.getHits()[i].getMetaValue("precursor_in_ms2"), false)
TEST_REAL_SIMILAR(pi.getHits()[i].getMetaValue("topN_meanfragmenterror"),0.00051117)
TEST_REAL_SIMILAR(pi.getHits()[i].getMetaValue("topN_MSEfragmenterror"),0)
TEST_REAL_SIMILAR(pi.getHits()[i].getMetaValue("topN_stddevfragmenterror"),0.0002534)
TEST_REAL_SIMILAR(pi.getHits()[i].getMetaValue("median_fragment_error"),0.0003167)
TEST_REAL_SIMILAR(pi.getHits()[i].getMetaValue("IQR_fragment_error"),0.000486)
TEST_REAL_SIMILAR(pi.getHits()[i].getMetaValue("NTermIonCurrentRatio"),0.454545)
TEST_REAL_SIMILAR(pi.getHits()[i].getMetaValue("CTermIonCurrentRatio"),0.545454)
}
END_SECTION
START_SECTION((void SpectrumAnnotator::addPeakAnnotationsToPeptideHit(PeptideHit& ph, const PeakSpectrum& spec, const TheoreticalSpectrumGenerator& tg, const SpectrumAlignment& sa, bool include_unmatched_peaks) const))
// Create a fresh PeptideHit for testing
PeptideHit test_hit;
test_hit.setSequence(peptide);
test_hit.setCharge(2);
// Create a fresh spectrum (copy of the test data)
PeakSpectrum test_spec;
test_spec.setMSLevel(2);
Peak1D test_p;
for (Size i = 0; i != pls; ++i)
{
test_p.setIntensity(1.1f);
test_p.setMZ(peaklist[i]);
test_spec.push_back(test_p);
}
// Test with include_unmatched_peaks = false (default behavior)
annot.addPeakAnnotationsToPeptideHit(test_hit, test_spec, tg, sa, false);
// Verify the PeakAnnotations were set correctly
const std::vector<PeptideHit::PeakAnnotation>& pas = test_hit.getPeakAnnotations();
// We expect 11 annotations (same as the number of matched peaks)
TEST_EQUAL(pas.size(), 11)
// Verify the annotations contain the expected ion names
StringList expected_ions = ListUtils::create<String>("y1+,y2+,b2+,y3+,b3+,y4+,b4+,y5+,b5+,b6+,y6+");
StringList found_ions;
for (const auto& pa : pas)
{
found_ions.push_back(pa.annotation);
// Verify that mz and intensity are set
TEST_NOT_EQUAL(pa.mz, -1.0)
TEST_REAL_SIMILAR(pa.intensity, 1.1f)
}
// Sort both lists for comparison (since order may vary based on spectrum alignment)
std::sort(expected_ions.begin(), expected_ions.end());
std::sort(found_ions.begin(), found_ions.end());
TEST_EQUAL(found_ions.size(), expected_ions.size())
for (size_t i = 0; i < found_ions.size(); ++i)
{
TEST_STRING_EQUAL(found_ions[i], expected_ions[i])
}
// Test with include_unmatched_peaks = true
// Add some unmatched peaks to the spectrum
PeakSpectrum test_spec_with_unmatched;
test_spec_with_unmatched.setMSLevel(2);
// Add some peaks that will NOT match
Peak1D unmatched_p;
unmatched_p.setIntensity(0.5f);
unmatched_p.setMZ(100.0); // This m/z won't match any theoretical ion
test_spec_with_unmatched.push_back(unmatched_p);
unmatched_p.setMZ(1000.0); // This m/z also won't match
test_spec_with_unmatched.push_back(unmatched_p);
// Add the original matched peaks
for (Size i = 0; i != pls; ++i)
{
test_p.setIntensity(1.1f);
test_p.setMZ(peaklist[i]);
test_spec_with_unmatched.push_back(test_p);
}
PeptideHit test_hit2;
test_hit2.setSequence(peptide);
test_hit2.setCharge(2);
annot.addPeakAnnotationsToPeptideHit(test_hit2, test_spec_with_unmatched, tg, sa, true);
const std::vector<PeptideHit::PeakAnnotation>& pas2 = test_hit2.getPeakAnnotations();
// We expect 13 annotations (11 matched + 2 unmatched)
TEST_EQUAL(pas2.size(), 13)
// Count annotated and unannotated peaks
size_t annotated_count = 0;
size_t unannotated_count = 0;
for (const auto& pa : pas2)
{
if (pa.annotation.empty())
{
unannotated_count++;
}
else
{
annotated_count++;
}
// All peaks should have mz and intensity set
TEST_NOT_EQUAL(pa.mz, -1.0)
}
TEST_EQUAL(annotated_count, 11) // 11 matched peaks
TEST_EQUAL(unannotated_count, 2) // 2 unmatched peaks
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MzMLFile_test.cpp | .cpp | 55,573 | 1,270 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Chris Bielow, Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/MzMLFile.h>
///////////////////////////
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/FORMAT/HANDLERS/MzMLHandler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
DRange<1> makeRange(double a, double b)
{
DPosition<1> pa(a), pb(b);
return DRange<1>(pa, pb);
}
///////////////////////////
START_TEST(MzMLFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
class TICConsumer :
public Interfaces::IMSDataConsumer
{
typedef PeakMap MapType;
typedef MapType::SpectrumType SpectrumType;
typedef MapType::ChromatogramType ChromatogramType;
public:
double TIC;
int nr_spectra;
long int nr_peaks;
// Create new consumer, set TIC to zero
TICConsumer() :
TIC(0.0),
nr_spectra(0.0),
nr_peaks(0)
{}
void consumeSpectrum(SpectrumType & s) override
{
for (Size i = 0; i < s.size(); i++)
{
TIC += s[i].getIntensity();
}
nr_peaks += s.size();
nr_spectra++;
}
void consumeChromatogram(ChromatogramType& /* c */) override {}
void setExpectedSize(Size /* expectedSpectra */, Size /* expectedChromatograms */) override {}
void setExperimentalSettings(const ExperimentalSettings& /* exp */) override {}
};
//Note: This code generates the test files for meta data arrays of different types. Do not delete it!
#if 0
{
//template spectrum with 100 peaks
MSSpectrum template_spec;
for (Size i=0; i<100; ++i)
{
Peak1D p;
p.setIntensity(i);
p.setMZ(i);
template_spec.push_back(p);
}
MSSpectrum spec;
PeakMap exp;
Size spectrum_number = 0;
Size array_number = 1;
//spectrum 1 - 3 float arrays of size 50,100,200
spec = template_spec; ++spectrum_number; array_number = 1;
spec.setNativeID(String("index=") + spectrum_number);
spec.setRT(1.0 * spectrum_number);
spec.setName(String("spectum number=") + spectrum_number);
Size array_size=50;
for (Size i=0; i<3; ++i)
{
spec.getFloatDataArrays().resize(i+1);
for (Size j=0; j<array_size; ++j)
{
spec.getFloatDataArrays()[i].push_back(100*(i+1) + j);
}
spec.getFloatDataArrays()[i].setName(String("array number=") + array_number);
array_size *=2;
array_number +=1;
}
exp.push_back(spec);
//spectrum 2 - 3 string arrays of size 50,100,200
spec = template_spec; ++spectrum_number; array_number = 1;
spec.setNativeID(String("index=") + spectrum_number);
spec.setRT(1.0 * spectrum_number);
spec.setName(String("spectum number=") + spectrum_number);
array_size=50;
for (Size i=0; i<3; ++i)
{
spec.getStringDataArrays().resize(i+1);
for (Size j=0; j<array_size; ++j)
{
spec.getStringDataArrays()[i].push_back(String(100*(i+1) + j));
}
spec.getStringDataArrays()[i].setName(String("array number=") + array_number);
array_size *=2;
array_number +=1;
}
exp.push_back(spec);
//spectrum 3 - 3 integer arrays of size 50,100,200
spec = template_spec; ++spectrum_number; array_number = 1;
spec.setNativeID(String("index=") + spectrum_number);
spec.setRT(1.0 * spectrum_number);
spec.setName(String("spectum number=") + spectrum_number);
array_size=50;
for (Size i=0; i<3; ++i)
{
spec.getIntegerDataArrays().resize(i+1);
for (Size j=0; j<array_size; ++j)
{
spec.getIntegerDataArrays()[i].push_back(100*(i+1) + j);
}
spec.getIntegerDataArrays()[i].setName(String("array number=") + array_number);
array_size *=2;
array_number +=1;
}
exp.push_back(spec);
//spectrum 4 - 2 float arrays of size 50,100 + 1 string arrays of size 200 + 3 integer arrays of size 50,100,200
spec = template_spec; ++spectrum_number; array_number = 1;
spec.setNativeID(String("index=") + spectrum_number);
spec.setRT(1.0 * spectrum_number);
spec.setName(String("spectum number=") + spectrum_number);
array_size=50;
for (Size i=0; i<2; ++i)
{
spec.getFloatDataArrays().resize(i+1);
for (Size j=0; j<array_size; ++j)
{
spec.getFloatDataArrays()[i].push_back(100*(i+1) + j);
}
spec.getFloatDataArrays()[i].setName(String("array number=") + array_number);
array_size *=2;
array_number +=1;
}
array_size=200;
for (Size i=0; i<1; ++i)
{
spec.getStringDataArrays().resize(i+1);
for (Size j=0; j<array_size; ++j)
{
spec.getStringDataArrays()[i].push_back(String(100*(i+1) + j));
}
spec.getStringDataArrays()[i].setName(String("array number=") + array_number);
array_size *=2;
array_number +=1;
}
array_size=50;
for (Size i=0; i<3; ++i)
{
spec.getIntegerDataArrays().resize(i+1);
for (Size j=0; j<array_size; ++j)
{
spec.getIntegerDataArrays()[i].push_back(100*(i+1) + j);
}
spec.getIntegerDataArrays()[i].setName(String("array number=") + array_number);
array_size *=2;
array_number +=1;
}
exp.push_back(spec);
MzMLFile f;
f.store("data/MzMLFile_6_uncompressed.mzML",exp);
f.getOptions().setCompression(true);
f.store("data/MzMLFile_6_compressed.mzML",exp);
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MzMLFile* ptr = 0;
MzMLFile* nullPointer = 0;
START_SECTION((MzMLFile()))
ptr = new MzMLFile;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~MzMLFile()))
delete ptr;
END_SECTION
START_SECTION(([EXTRA] Chromatogram section))
MzMLFile file;
PeakMap exp;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp);
TEST_EQUAL(exp.getChromatograms().size(), 2)
TEST_EQUAL(exp.getChromatograms()[0].size(), 15)
TEST_EQUAL(exp.getChromatograms()[1].size(), 10)
END_SECTION
START_SECTION(const PeakFileOptions& getOptions() const)
MzMLFile file;
TEST_EQUAL(file.getOptions().hasMSLevels(),false)
END_SECTION
START_SECTION(PeakFileOptions& getOptions())
MzMLFile file;
file.getOptions().addMSLevel(1);
TEST_EQUAL(file.getOptions().hasMSLevels(),true);
END_SECTION
}
#endif
TOLERANCE_ABSOLUTE(0.01)
START_SECTION((Size loadSize(const String & filename, Size& scount, Size& ccount)))
{
MzMLFile file;
Size spectra_count, chrom_count;
file.loadSize(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), spectra_count, chrom_count);
TEST_EQUAL(spectra_count, 4);
TEST_EQUAL(chrom_count, 2);
file.getOptions().addMSLevel(2); // only count MS2 scans
file.loadSize(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), spectra_count, chrom_count);
TEST_EQUAL(spectra_count, 1);
TEST_EQUAL(chrom_count, 2);
file.getOptions().addMSLevel(1); // only count MS1 + MS2 scans
file.loadSize(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), spectra_count, chrom_count);
TEST_EQUAL(spectra_count, 4);
TEST_EQUAL(chrom_count, 2);
file.getOptions().clearMSLevels();
file.getOptions().setRTRange(makeRange(5.0, 5.25));
file.loadSize(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), spectra_count, chrom_count);
TEST_EQUAL(spectra_count, 2);
TEST_EQUAL(chrom_count, 2);
file.getOptions().addMSLevel(1); // only count MS1 and range
file.loadSize(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), spectra_count, chrom_count);
TEST_EQUAL(spectra_count, 1);
TEST_EQUAL(chrom_count, 2);
}
END_SECTION
START_SECTION((template <typename MapType> void load(const String& filename, MapType& map)))
{
MzMLFile file;
PeakMap exp;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"),exp);
//test DocumentIdentifier addition
TEST_STRING_EQUAL(exp.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"));
TEST_STRING_EQUAL(FileTypes::typeToName(exp.getLoadedFileType()),"mzML");
//-------------------------- general information --------------------------
TEST_EQUAL(exp.size(),4)
//run
TEST_EQUAL(exp.getIdentifier(),"document_accession")
TEST_EQUAL(exp.getFractionIdentifier(),"the_best_fraction_ever")
TEST_EQUAL(exp.getDateTime().get(),"2007-06-27 15:23:45")
//contacts
TEST_EQUAL(exp.getContacts().size(),2)
TEST_STRING_EQUAL(exp.getContacts()[0].getFirstName(),"William")
TEST_STRING_EQUAL(exp.getContacts()[0].getLastName(),"Pennington")
TEST_STRING_EQUAL(exp.getContacts()[0].getEmail(),"wpennington@higglesworth.edu")
TEST_STRING_EQUAL(exp.getContacts()[0].getURL(),"http://www.higglesworth.edu/")
TEST_STRING_EQUAL(exp.getContacts()[0].getAddress(),"Higglesworth University, 12 Higglesworth Avenue, 12045, HI, USA")
TEST_STRING_EQUAL(exp.getContacts()[1].getFirstName(),"Guybrush")
TEST_STRING_EQUAL(exp.getContacts()[1].getLastName(),"Threepwood")
TEST_STRING_EQUAL(exp.getContacts()[1].getEmail(),"")
TEST_STRING_EQUAL(exp.getContacts()[1].getURL(),"")
TEST_STRING_EQUAL(exp.getContacts()[1].getAddress(),"")
//source files
TEST_EQUAL(exp.getSourceFiles().size(),5);
TEST_STRING_EQUAL(exp.getSourceFiles()[0].getNameOfFile(),"tiny1.RAW")
TEST_STRING_EQUAL(exp.getSourceFiles()[0].getPathToFile(),"file:///F:/data/Exp01")
TEST_STRING_EQUAL(exp.getSourceFiles()[0].getChecksum(),"71be39fb2700ab2f3c8b2234b91274968b6899b1")
TEST_EQUAL(exp.getSourceFiles()[0].getChecksumType(),SourceFile::ChecksumType::SHA1)
TEST_STRING_EQUAL(exp.getSourceFiles()[0].getFileType(),"Thermo RAW format")
TEST_STRING_EQUAL(exp.getSourceFiles()[0].getNativeIDType(),"multiple peak list nativeID format")
//sample
TEST_STRING_EQUAL(exp.getSample().getName(),"Sample1")
TEST_REAL_SIMILAR(exp.getSample().getMass(),11.7)
TEST_STRING_EQUAL(exp.getSample().getNumber(),"5")
TEST_REAL_SIMILAR(exp.getSample().getVolume(),3.1)
TEST_REAL_SIMILAR(exp.getSample().getConcentration(),5.5)
TEST_EQUAL(exp.getSample().getState(),Sample::SampleState::SUSPENSION)
//instrument (general)
TEST_STRING_EQUAL(exp.getInstrument().getName(),"LCQ Deca")
TEST_STRING_EQUAL(exp.getInstrument().getCustomizations(),"Umbau")
//ion sources
TEST_EQUAL(exp.getInstrument().getIonSources().size(),2)
TEST_EQUAL(exp.getInstrument().getIonSources()[0].getOrder(),101)
TEST_EQUAL(exp.getInstrument().getIonSources()[0].getInletType(),IonSource::InletType::DIRECT)
TEST_EQUAL(exp.getInstrument().getIonSources()[0].getIonizationMethod(),IonSource::IonizationMethod::ESI)
TEST_EQUAL(exp.getInstrument().getIonSources()[1].getOrder(),102)
TEST_EQUAL(exp.getInstrument().getIonSources()[1].getInletType(),IonSource::InletType::DIRECT)
TEST_EQUAL(exp.getInstrument().getIonSources()[1].getIonizationMethod(),IonSource::IonizationMethod::FAB)
//mass analyzers
TEST_EQUAL(exp.getInstrument().getMassAnalyzers().size(),2)
TEST_EQUAL(exp.getInstrument().getMassAnalyzers()[0].getOrder(),201)
TEST_EQUAL(exp.getInstrument().getMassAnalyzers()[0].getType(),MassAnalyzer::AnalyzerType::PAULIONTRAP)
TEST_REAL_SIMILAR(exp.getInstrument().getMassAnalyzers()[0].getAccuracy(),10.5)
TEST_REAL_SIMILAR(exp.getInstrument().getMassAnalyzers()[0].getMagneticFieldStrength(),14.56)
TEST_REAL_SIMILAR(exp.getInstrument().getMassAnalyzers()[0].getTOFTotalPathLength(),11.1)
TEST_EQUAL(exp.getInstrument().getMassAnalyzers()[1].getOrder(),202)
TEST_EQUAL(exp.getInstrument().getMassAnalyzers()[1].getType(),MassAnalyzer::AnalyzerType::LIT)
TEST_REAL_SIMILAR(exp.getInstrument().getMassAnalyzers()[1].getMagneticFieldStrength(),1414.14)
//detectors
TEST_EQUAL(exp.getInstrument().getIonDetectors().size(),2)
TEST_EQUAL(exp.getInstrument().getIonDetectors()[0].getOrder(),301)
TEST_EQUAL(exp.getInstrument().getIonDetectors()[0].getType(),IonDetector::Type::ELECTRONMULTIPLIER)
TEST_EQUAL(exp.getInstrument().getIonDetectors()[0].getAcquisitionMode(),IonDetector::AcquisitionMode::TDC)
TEST_REAL_SIMILAR(exp.getInstrument().getIonDetectors()[0].getResolution(),5.1)
TEST_REAL_SIMILAR(exp.getInstrument().getIonDetectors()[0].getADCSamplingFrequency(),1.1)
TEST_EQUAL(exp.getInstrument().getIonDetectors()[1].getOrder(),302)
TEST_EQUAL(exp.getInstrument().getIonDetectors()[1].getType(),IonDetector::Type::ELECTRONMULTIPLIER)
TEST_EQUAL(exp.getInstrument().getIonDetectors()[1].getAcquisitionMode(),IonDetector::AcquisitionMode::TDC)
TEST_REAL_SIMILAR(exp.getInstrument().getIonDetectors()[1].getResolution(),6.1)
TEST_REAL_SIMILAR(exp.getInstrument().getIonDetectors()[1].getADCSamplingFrequency(),1.1)
//instrument software
TEST_EQUAL(exp.getInstrument().getSoftware().getName(),"Bioworks")
TEST_EQUAL(exp.getInstrument().getSoftware().getVersion(),"3.3.1 sp1")
//-------------------------- spectrum 0 --------------------------
{
const MSSpectrum& spec = exp[0];
//peaks
TEST_EQUAL(spec.size(),15)
for (UInt i=0; i<15; ++i)
{
TEST_REAL_SIMILAR(spec[(Size)i].getMZ(),i);
TEST_REAL_SIMILAR(spec[(Size)i].getIntensity(),15-i);
}
//general info
TEST_EQUAL(spec.getMSLevel(),1)
TEST_EQUAL(spec.getInstrumentSettings().getScanMode(),InstrumentSettings::ScanMode::MS1SPECTRUM)
TEST_EQUAL(spec.getFloatDataArrays().size(),0)
TEST_EQUAL(spec.getType(),SpectrumSettings::SpectrumType::CENTROID)
TEST_REAL_SIMILAR(spec.getRT(),5.1)
TEST_REAL_SIMILAR(spec.getDriftTime(),7.1)
TEST_EQUAL(spec.getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true)
TEST_EQUAL(spec.getInstrumentSettings().getScanWindows().size(),1)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[0].begin,400.0)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[0].end,1800.0)
TEST_STRING_EQUAL(spec.getAcquisitionInfo().getMethodOfCombination(),"median of spectra")
TEST_EQUAL(spec.getAcquisitionInfo().size(),2)
TEST_EQUAL(spec.getAcquisitionInfo()[0].getIdentifier(),"4711")
TEST_STRING_EQUAL(spec.getAcquisitionInfo()[0].getMetaValue("source_file_name"),"ac.dta")
TEST_STRING_EQUAL(spec.getAcquisitionInfo()[0].getMetaValue("source_file_path"),"file:///F:/data/Exp02")
TEST_EQUAL(spec.getAcquisitionInfo()[1].getIdentifier(),"4712")
TEST_EQUAL(spec.getSourceFile()==SourceFile(),true)
//ids
TEST_STRING_EQUAL(spec.getNativeID(),"index=0")
TEST_STRING_EQUAL(spec.getMetaValue("maldi_spot_id"),"M0")
//precursors
TEST_EQUAL(spec.getPrecursors().size(),0)
TEST_EQUAL(spec.getProducts().size(),0)
//data processing
TEST_EQUAL(spec.getDataProcessing().size(),2)
TEST_EQUAL(spec.getDataProcessing()[0]->getSoftware().getName(),"Xcalibur")
TEST_EQUAL(spec.getDataProcessing()[0]->getSoftware().getVersion(),"2.0.5")
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().size(),2)
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().count(DataProcessing::DEISOTOPING),1)
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().count(DataProcessing::CHARGE_DECONVOLUTION),1)
TEST_STRING_EQUAL(spec.getDataProcessing()[0]->getCompletionTime().get(),"2001-02-03 04:05:00")
TEST_REAL_SIMILAR(double(spec.getDataProcessing()[0]->getMetaValue("low_intensity_threshold")),5.9)
TEST_REAL_SIMILAR(double(spec.getDataProcessing()[0]->getMetaValue("high_intensity_threshold")),10.9)
TEST_EQUAL(spec.getDataProcessing()[0]->isMetaEmpty(),false)
TEST_EQUAL(spec.getDataProcessing()[1]->getSoftware().getName(),"ProteoWizard software")
TEST_EQUAL(spec.getDataProcessing()[1]->getSoftware().getVersion(),"1.0")
TEST_EQUAL(spec.getDataProcessing()[1]->getProcessingActions().size(),1)
TEST_EQUAL(spec.getDataProcessing()[1]->getProcessingActions().count(DataProcessing::CONVERSION_MZML),1)
TEST_EQUAL(spec.getDataProcessing()[1]->isMetaEmpty(),false)
}
//-------------------------- spectrum 1 --------------------------
{
const MSSpectrum& spec = exp[1];
//peaks
TEST_EQUAL(spec.size(),10)
for (Size i=0; i<10; ++i)
{
TEST_REAL_SIMILAR(spec[i].getMZ(),2.0*i);
TEST_REAL_SIMILAR(spec[i].getIntensity(),20-2.0*i);
}
//general info
TEST_EQUAL(spec.getMSLevel(),2)
TEST_EQUAL(spec.getInstrumentSettings().getScanMode(),InstrumentSettings::ScanMode::MSNSPECTRUM)
TEST_EQUAL(spec.getType(),SpectrumSettings::SpectrumType::CENTROID)
TEST_REAL_SIMILAR(spec.getRT(),5.2)
// in the mzML, drift time is stored in precursor only but we still create a spectrum attribute for convenience
TEST_REAL_SIMILAR(spec.getDriftTime(),8.1)
TEST_EQUAL(spec.getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true)
TEST_EQUAL(spec.getInstrumentSettings().getPolarity(),IonSource::Polarity::POSITIVE)
TEST_EQUAL(spec.getInstrumentSettings().getScanWindows().size(),3)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[0].begin,100.0)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[0].end,500.0)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[1].begin,600.0)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[1].end,1000.0)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[2].begin,1100.0)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[2].end,1500.0)
TEST_EQUAL(spec.getAcquisitionInfo().getMethodOfCombination(),"no combination")
TEST_EQUAL(spec.getAcquisitionInfo().size(),1)
TEST_EQUAL(spec.getAcquisitionInfo()[0].getIdentifier(),"0")
//meta data arrays
TEST_EQUAL(spec.getFloatDataArrays().size(),2)
TEST_STRING_EQUAL(spec.getFloatDataArrays()[0].getName(),"signal to noise array")
TEST_EQUAL(spec.getFloatDataArrays()[0].size(),10)
TEST_EQUAL(spec.getFloatDataArrays()[0].getDataProcessing().size(),1)
TEST_EQUAL(spec.getFloatDataArrays()[0].getDataProcessing()[0]->getSoftware().getName(), "FileFilter")
TEST_EQUAL(spec.getFloatDataArrays()[0].getDataProcessing()[0]->getSoftware().getVersion(), "1.6.1")
TEST_EQUAL(spec.getFloatDataArrays()[0].getDataProcessing()[0]->getProcessingActions().size(), 1)
TEST_EQUAL(spec.getFloatDataArrays()[0].getDataProcessing()[0]->getProcessingActions().count(DataProcessing::CHARGE_CALCULATION), 1)
TEST_STRING_EQUAL(spec.getFloatDataArrays()[0].getDataProcessing()[0]->getCompletionTime().get(),"2001-02-03 04:15:00")
TEST_STRING_EQUAL(spec.getFloatDataArrays()[1].getName(),"user-defined name")
TEST_EQUAL(spec.getFloatDataArrays()[1].getDataProcessing().size(),0)
TEST_EQUAL(spec.getFloatDataArrays()[1].size(),10)
//precursors
TEST_EQUAL(spec.getPrecursors().size(),2)
TEST_REAL_SIMILAR(spec.getPrecursors()[0].getIntensity(),120053)
TEST_EQUAL(spec.getPrecursors()[0].getCharge(),2)
TEST_REAL_SIMILAR(spec.getPrecursors()[0].getMZ(),5.55)
TEST_REAL_SIMILAR(spec.getPrecursors()[0].getDriftTime(),8.1)
TEST_EQUAL(spec.getPrecursors()[0].getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true)
TEST_EQUAL(spec.getPrecursors()[0].getActivationMethods().size(),2)
TEST_EQUAL(spec.getPrecursors()[0].getActivationMethods().count(Precursor::ActivationMethod::CID),1)
TEST_EQUAL(spec.getPrecursors()[0].getActivationMethods().count(Precursor::ActivationMethod::PD),1)
TEST_REAL_SIMILAR(spec.getPrecursors()[0].getActivationEnergy(),35)
TEST_REAL_SIMILAR(spec.getPrecursors()[0].getIsolationWindowLowerOffset(),6.66)
TEST_REAL_SIMILAR(spec.getPrecursors()[0].getIsolationWindowUpperOffset(),7.77)
TEST_EQUAL(spec.getPrecursors()[0].getPossibleChargeStates().size(),3)
TEST_EQUAL(spec.getPrecursors()[0].getPossibleChargeStates()[0],1)
TEST_EQUAL(spec.getPrecursors()[0].getPossibleChargeStates()[1],3)
TEST_EQUAL(spec.getPrecursors()[0].getPossibleChargeStates()[2],4)
TEST_REAL_SIMILAR(spec.getPrecursors()[1].getMZ(),15.55)
TEST_REAL_SIMILAR(spec.getPrecursors()[1].getDriftTime(),-1) // none set
TEST_EQUAL(spec.getPrecursors()[1].getDriftTimeUnit() == DriftTimeUnit::NONE, true) // none set
TEST_REAL_SIMILAR(spec.getPrecursors()[1].getIsolationWindowLowerOffset(),16.66)
TEST_REAL_SIMILAR(spec.getPrecursors()[1].getIsolationWindowUpperOffset(),17.77)
TEST_EQUAL(spec.getPrecursors()[1].getActivationMethods().size(),1)
TEST_EQUAL(spec.getPrecursors()[1].getActivationMethods().count(Precursor::ActivationMethod::ETD),1)
TEST_REAL_SIMILAR(spec.getPrecursors()[1].getActivationEnergy(),36)
TEST_REAL_SIMILAR(spec.getPrecursors()[1].getIntensity(),0.0f)
TEST_EQUAL(spec.getPrecursors()[1].getCharge(),0)
TEST_EQUAL(spec.getPrecursors()[1].getPossibleChargeStates().size(),0)
//products
TEST_EQUAL(spec.getProducts().size(),0)
//source file
TEST_STRING_EQUAL(spec.getSourceFile().getNameOfFile(),"tiny1.dta")
TEST_STRING_EQUAL(spec.getSourceFile().getPathToFile(),"file:///F:/data/Exp01")
TEST_STRING_EQUAL(spec.getSourceFile().getChecksum(),"81be39fb2700ab2f3c8b2234b91274968b6899b1")
TEST_EQUAL(spec.getSourceFile().getChecksumType(),SourceFile::ChecksumType::SHA1)
//ids
TEST_STRING_EQUAL(spec.getNativeID(),"index=1")
TEST_STRING_EQUAL(spec.getMetaValue("maldi_spot_id"),"M1")
//data processing
TEST_EQUAL(spec.getDataProcessing().size(),2)
TEST_EQUAL(spec.getDataProcessing()[0]->getSoftware().getName(),"Xcalibur")
TEST_EQUAL(spec.getDataProcessing()[0]->getSoftware().getVersion(),"2.0.5")
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().size(),2)
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().count(DataProcessing::DEISOTOPING),1)
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().count(DataProcessing::CHARGE_DECONVOLUTION),1)
TEST_STRING_EQUAL(spec.getDataProcessing()[0]->getCompletionTime().get(),"2001-02-03 04:05:00")
TEST_REAL_SIMILAR(double(spec.getDataProcessing()[0]->getMetaValue("low_intensity_threshold")),5.9)
TEST_REAL_SIMILAR(double(spec.getDataProcessing()[0]->getMetaValue("high_intensity_threshold")),10.9)
TEST_EQUAL(spec.getDataProcessing()[0]->isMetaEmpty(),false)
TEST_EQUAL(spec.getDataProcessing()[1]->getSoftware().getName(),"ProteoWizard software")
TEST_EQUAL(spec.getDataProcessing()[1]->getSoftware().getVersion(),"1.0")
TEST_EQUAL(spec.getDataProcessing()[1]->getProcessingActions().size(),1)
TEST_EQUAL(spec.getDataProcessing()[1]->getProcessingActions().count(DataProcessing::CONVERSION_MZML),1)
TEST_EQUAL(spec.getDataProcessing()[1]->isMetaEmpty(),false)
}
//-------------------------- spectrum 2 --------------------------
{
const MSSpectrum& spec = exp[2];
//peaks
TEST_EQUAL(spec.size(),15)
for (UInt i=0; i<15; ++i)
{
TEST_REAL_SIMILAR(spec[(Size)i].getMZ(),i);
TEST_REAL_SIMILAR(spec[(Size)i].getIntensity(),15-i);
}
//general info
TEST_EQUAL(spec.getMSLevel(),1)
TEST_EQUAL(spec.getInstrumentSettings().getScanMode(),InstrumentSettings::ScanMode::MS1SPECTRUM)
TEST_EQUAL(spec.getFloatDataArrays().size(),0)
TEST_EQUAL(spec.getType(),SpectrumSettings::SpectrumType::CENTROID)
TEST_REAL_SIMILAR(spec.getRT(),5.3)
TEST_EQUAL(spec.getInstrumentSettings().getPolarity(),IonSource::Polarity::POSITIVE)
TEST_EQUAL(spec.getInstrumentSettings().getScanWindows().size(),1)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[0].begin,400.0)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[0].end,1800.0)
//acquisition
TEST_STRING_EQUAL(spec.getAcquisitionInfo().getMethodOfCombination(),"median of spectra")
TEST_EQUAL(spec.getAcquisitionInfo().size(),2)
TEST_EQUAL(spec.getAcquisitionInfo()[0].getIdentifier(),"4711")
TEST_EQUAL(spec.getAcquisitionInfo()[1].getIdentifier(),"4712")
TEST_EQUAL(spec.getSourceFile()==SourceFile(),true)
//ids
TEST_STRING_EQUAL(spec.getNativeID(),"index=2")
TEST_STRING_EQUAL(spec.getMetaValue("maldi_spot_id"),"M2")
//precursors
TEST_EQUAL(spec.getPrecursors().size(),0)
//products
TEST_EQUAL(spec.getProducts().size(),2)
TEST_REAL_SIMILAR(spec.getProducts()[0].getMZ(),18.88)
TEST_REAL_SIMILAR(spec.getProducts()[0].getIsolationWindowLowerOffset(),1.0)
TEST_REAL_SIMILAR(spec.getProducts()[0].getIsolationWindowUpperOffset(),2.0)
TEST_REAL_SIMILAR(spec.getProducts()[1].getMZ(),19.99)
TEST_REAL_SIMILAR(spec.getProducts()[1].getIsolationWindowLowerOffset(),3.0)
TEST_REAL_SIMILAR(spec.getProducts()[1].getIsolationWindowUpperOffset(),4.0)
//data processing
TEST_EQUAL(spec.getDataProcessing().size(),1)
TEST_EQUAL(spec.getDataProcessing()[0]->getSoftware().getName(),"Xcalibur")
TEST_EQUAL(spec.getDataProcessing()[0]->getSoftware().getVersion(),"2.0.5")
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().size(),2)
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().count(DataProcessing::DEISOTOPING),1)
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().count(DataProcessing::CHARGE_DECONVOLUTION),1)
TEST_STRING_EQUAL(spec.getDataProcessing()[0]->getCompletionTime().get(),"2001-02-03 04:05:00")
TEST_REAL_SIMILAR(double(spec.getDataProcessing()[0]->getMetaValue("low_intensity_threshold")),5.9)
TEST_REAL_SIMILAR(double(spec.getDataProcessing()[0]->getMetaValue("high_intensity_threshold")),10.9)
TEST_EQUAL(spec.getDataProcessing()[0]->isMetaEmpty(),false)
}
//-------------------------- spectrum 3 (no peaks) --------------------------
{
const MSSpectrum& spec = exp[3];
//peaks
TEST_EQUAL(spec.size(),0)
//general info
TEST_EQUAL(spec.getMSLevel(),1)
TEST_REAL_SIMILAR(spec.getRT(),5.4)
TEST_EQUAL(spec.getInstrumentSettings().getScanMode(),InstrumentSettings::ScanMode::MS1SPECTRUM)
TEST_EQUAL(spec.getInstrumentSettings().getZoomScan(),true)
TEST_EQUAL(spec.getFloatDataArrays().size(),0)
TEST_EQUAL(spec.getType(),SpectrumSettings::SpectrumType::PROFILE)
TEST_EQUAL(spec.getInstrumentSettings().getScanWindows().size(),1)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[0].begin,110.0)
TEST_REAL_SIMILAR(spec.getInstrumentSettings().getScanWindows()[0].end,905.0)
TEST_STRING_EQUAL(spec.getAcquisitionInfo().getMethodOfCombination(),"no combination")
TEST_EQUAL(spec.getAcquisitionInfo().size(),1)
TEST_EQUAL(spec.getAcquisitionInfo()[0].getIdentifier(),"0")
//ids
TEST_STRING_EQUAL(spec.getNativeID(),"index=3")
TEST_EQUAL(spec.metaValueExists("maldi_spot_id"),false)
//precursors
TEST_EQUAL(spec.getPrecursors().size(),0)
TEST_EQUAL(spec.getProducts().size(),0)
//data processing
TEST_EQUAL(spec.getDataProcessing().size(),1)
TEST_EQUAL(spec.getDataProcessing()[0]->getSoftware().getName(),"ProteoWizard software")
TEST_EQUAL(spec.getDataProcessing()[0]->getSoftware().getVersion(),"1.0")
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().size(),1)
TEST_EQUAL(spec.getDataProcessing()[0]->getProcessingActions().count(DataProcessing::CONVERSION_MZML),1)
TEST_EQUAL(spec.getDataProcessing()[0]->isMetaEmpty(),false)
}
//-------------------------- userParam --------------------------
//run
TEST_STRING_EQUAL(exp.getMetaValue("mzml_id"),"document_id")
TEST_EQUAL(exp.getMetaValue("flag").valueType(),DataValue::STRING_VALUE)
TEST_STRING_EQUAL((String)exp.getMetaValue("flag"),"")
TEST_EQUAL(exp.getMetaValue("string").valueType(),DataValue::STRING_VALUE)
TEST_STRING_EQUAL((String)exp.getMetaValue("string"),"bla")
TEST_EQUAL(exp.getMetaValue("float").valueType(),DataValue::DOUBLE_VALUE)
TEST_REAL_SIMILAR((double)exp.getMetaValue("float"),5.11)
TEST_EQUAL(exp.getMetaValue("int").valueType(),DataValue::INT_VALUE)
TEST_EQUAL((Int)exp.getMetaValue("int"),5)
//instrumentConfiguration
TEST_EQUAL(exp.getInstrument().getIonOptics(),Instrument::IonOpticsType::MAGNETIC_DEFLECTION)
TEST_STRING_EQUAL((String)exp.getInstrument().getMetaValue("name"),"instrumentConfiguration")
TEST_STRING_EQUAL((String)exp.getInstrument().getIonSources()[0].getMetaValue("name"),"source1")
TEST_STRING_EQUAL((String)exp.getInstrument().getIonSources()[1].getMetaValue("name"),"source2")
TEST_STRING_EQUAL((String)exp.getInstrument().getMassAnalyzers()[0].getMetaValue("name"),"analyzer1")
TEST_STRING_EQUAL((String)exp.getInstrument().getMassAnalyzers()[1].getMetaValue("name"),"analyzer2")
TEST_STRING_EQUAL((String)exp.getInstrument().getIonDetectors()[0].getMetaValue("name"),"detector1")
TEST_STRING_EQUAL((String)exp.getInstrument().getIonDetectors()[1].getMetaValue("name"),"detector2")
//sample
TEST_STRING_EQUAL((String)exp.getSample().getMetaValue("name"),"sample")
TEST_STRING_EQUAL((String)exp.getSample().getMetaValue("brenda source tissue"),"cardiac muscle")
TEST_STRING_EQUAL((String)exp.getSample().getMetaValue("GO cellular component"),"nucleus")
TEST_STRING_EQUAL((String)exp.getSample().getMetaValue("cellular quality"),"11.11")
//contact
TEST_STRING_EQUAL((String)exp.getContacts()[0].getMetaValue("name"),"contact1")
TEST_STRING_EQUAL((String)exp.getContacts()[1].getMetaValue("name"),"Pirate")
//spectrum
TEST_STRING_EQUAL((String)exp[0].getMetaValue("sdname"),"spectrumdescription1")
TEST_STRING_EQUAL((String)exp[1].getMetaValue("sdname"),"spectrumdescription2")
TEST_STRING_EQUAL((String)exp[2].getMetaValue("sdname"),"spectrumdescription3")
TEST_STRING_EQUAL((String)exp[3].getMetaValue("sdname"),"spectrumdescription4")
TEST_STRING_EQUAL((String)exp[0].getMetaValue("mzname"),"mzarray1")
TEST_STRING_EQUAL((String)exp[0].getMetaValue("itname"),"itarray1")
TEST_STRING_EQUAL((String)exp[1].getMetaValue("mzname"),"mzarray2")
TEST_STRING_EQUAL((String)exp[1].getMetaValue("itname"),"itarray2")
//binaryDataArray
TEST_STRING_EQUAL((String)exp[1].getFloatDataArrays()[0].getMetaValue("name"),"binaryDataArray_sn")
TEST_STRING_EQUAL((String)exp[1].getFloatDataArrays()[0].getMetaValue("name2"),"binaryDataArray_sn2")
TEST_STRING_EQUAL((String)exp[1].getFloatDataArrays()[1].getMetaValue("name"),"binaryDataArray_c")
TEST_STRING_EQUAL((String)exp[1].getFloatDataArrays()[1].getMetaValue("name2"),"")
//acquisition list
TEST_STRING_EQUAL((String)exp[0].getAcquisitionInfo().getMetaValue("name"),"acquisition_list")
//acquisition
TEST_STRING_EQUAL((String)exp[0].getAcquisitionInfo()[0].getMetaValue("name"),"acquisition1")
TEST_STRING_EQUAL((String)exp[0].getAcquisitionInfo()[1].getMetaValue("name"),"acquisition2")
//source file
TEST_STRING_EQUAL((String)exp.getSourceFiles()[0].getMetaValue("name"),"sourcefile1")
TEST_STRING_EQUAL((String)exp[1].getSourceFile().getMetaValue("name"),"sourcefile4")
//data processing
TEST_STRING_EQUAL(exp[0].getDataProcessing()[0]->getMetaValue("p1").toString(),"value1")
TEST_STRING_EQUAL(exp[0].getDataProcessing()[1]->getMetaValue("p2").toString(),"value2")
TEST_STRING_EQUAL(exp[1].getDataProcessing()[0]->getMetaValue("p1").toString(),"value1")
TEST_STRING_EQUAL(exp[1].getDataProcessing()[1]->getMetaValue("p2").toString(),"value2")
TEST_STRING_EQUAL(exp[2].getDataProcessing()[0]->getMetaValue("p1").toString(),"value1")
TEST_STRING_EQUAL(exp[3].getDataProcessing()[0]->getMetaValue("p2").toString(),"value2")
TEST_STRING_EQUAL(exp[1].getFloatDataArrays()[0].getDataProcessing()[0]->getMetaValue("p3").toString(),"value3")
//precursor
TEST_STRING_EQUAL(exp[1].getPrecursors()[0].getMetaValue("iwname").toString(),"isolationwindow1")
TEST_STRING_EQUAL(exp[1].getPrecursors()[0].getMetaValue("siname").toString(),"selectedion1")
TEST_STRING_EQUAL(exp[1].getPrecursors()[0].getMetaValue("acname").toString(),"activation1")
TEST_STRING_EQUAL(exp[1].getPrecursors()[1].getMetaValue("acname").toString(),"activation2")
TEST_STRING_EQUAL(exp[1].getPrecursors()[1].getMetaValue("iwname").toString(),"isolationwindow2")
//product
TEST_STRING_EQUAL(exp[2].getProducts()[0].getMetaValue("iwname").toString(),"isolationwindow3")
TEST_STRING_EQUAL(exp[2].getProducts()[1].getMetaValue("iwname").toString(),"isolationwindow4")
//scan window
TEST_STRING_EQUAL((String)exp[0].getInstrumentSettings().getScanWindows()[0].getMetaValue("name"),"scanwindow1")
//-------------------------- cvParam (but no member => meta data)--------------------------
//general
TEST_STRING_EQUAL((String)exp.getSample().getMetaValue("sample batch"),"4.4")
//spectrum 1
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("elution time (seconds)"),55.11)
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("lowest observed m/z"),400.39)
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("highest observed m/z"),1795.56)
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("lowest observed wavelength"),500.39)
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("highest observed wavelength"),795.56)
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("base peak m/z"),445.347)
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("base peak intensity"),120054)
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("total ion current"),16675500)
TEST_STRING_EQUAL((String)exp[0].getMetaValue("spectrum title"),"title")
TEST_STRING_EQUAL((String)exp[0].getMetaValue("peak list scans"),"15 scans")
TEST_STRING_EQUAL((String)exp[0].getMetaValue("peak list raw scans"),"16 scans")
TEST_STRING_EQUAL((String)exp[0].getMetaValue("mass resolution"),"4.3")
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("analyzer scan offset"),-4.5)
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("dwell time"),123.45)
TEST_STRING_EQUAL((String)exp[0].getMetaValue("filter string"),"+ c NSI Full ms [ 400.00-1800.00]")
TEST_STRING_EQUAL((String)exp[0].getMetaValue("preset scan configuration"),"3 abc")
TEST_REAL_SIMILAR((double)exp[0].getMetaValue("scan rate"),17.17)
//spectrum 2
TEST_STRING_EQUAL((String)exp[1].getMetaValue("mass resolution"),"4.1")
TEST_STRING_EQUAL((String)exp[1].getPrecursors()[0].getMetaValue("collision gas"), "Argon")
TEST_STRING_EQUAL((String)exp[1].getPrecursors()[0].getMetaValue("buffer gas"), "Krypton")
TEST_STRING_EQUAL((String)exp[1].getPrecursors()[0].getMetaValue("source_file_name"),"pr.dta")
TEST_STRING_EQUAL((String)exp[1].getPrecursors()[0].getMetaValue("source_file_path"),"file:///F:/data/Exp03")
/////////////////////// TESTING SPECIAL CASES ///////////////////////
//load a second time to make sure everything is re-initialized correctly
PeakMap exp2;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"),exp2);
TEST_EQUAL(exp==exp2,true)
//load minimal file
PeakMap exp3;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_2_minimal.mzML"),exp3);
TEST_EQUAL(exp3.size(), 0)
//load file with huge CDATA and whitespaces in CDATA
PeakMap exp4;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_5_long.mzML"), exp4);
TEST_EQUAL(exp4.size(), 1)
TEST_EQUAL(exp4[0].size(), 997530)
//test 32/64 bit floats, 32/64 bit integer, null terminated strings, zlib compression
PeakMap exp_ucomp;
STATUS("Reading uncompressed...")
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompressed.mzML"), exp_ucomp);
STATUS("Reading uncompressed done.")
PeakMap exp_comp;
STATUS("Reading compressed...")
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_compressed.mzML"), exp_comp);
STATUS("Reading compressed done.")
TEST_EQUAL(exp_ucomp.size(), exp_comp.size())
for (Size s = 0; s < exp_ucomp.size(); ++s)
{
//check if the same number of peak and meta data arrays is present
TEST_EQUAL(exp_ucomp[s].size(),exp_comp[s].size())
TEST_EQUAL(exp_ucomp[s].getFloatDataArrays().size(),exp_comp[s].getFloatDataArrays().size())
TEST_EQUAL(exp_ucomp[s].getIntegerDataArrays().size(),exp_comp[s].getIntegerDataArrays().size())
TEST_EQUAL(exp_ucomp[s].getStringDataArrays().size(),exp_comp[s].getStringDataArrays().size())
//check content of peak array
for (Size p = 0; p < exp_ucomp[s].size(); ++p)
{
TEST_REAL_SIMILAR(exp_ucomp[s][p].getMZ(),exp_comp[s][p].getMZ())
TEST_REAL_SIMILAR(exp_ucomp[s][p].getIntensity(),exp_comp[s][p].getIntensity())
}
//check content of float arrays
for (Size a = 0; a < exp_ucomp[s].getFloatDataArrays().size(); ++a)
{
for (Size m = 0; m < exp_ucomp[s].getFloatDataArrays()[a].size(); ++m)
{
TEST_REAL_SIMILAR(exp_ucomp[s].getFloatDataArrays()[a][m],exp_comp[s].getFloatDataArrays()[a][m])
}
}
//check content of integer arrays
for (Size a = 0; a < exp_ucomp[s].getIntegerDataArrays().size(); ++a)
{
for (Size m = 0; m < exp_ucomp[s].getIntegerDataArrays()[a].size(); ++m)
{
TEST_EQUAL(exp_ucomp[s].getIntegerDataArrays()[a][m],exp_comp[s].getIntegerDataArrays()[a][m])
}
}
//check content of string arrays
for (Size a = 0; a < exp_ucomp[s].getStringDataArrays().size(); ++a)
{
for (Size m = 0; m < exp_ucomp[s].getStringDataArrays()[a].size(); ++m)
{
TEST_STRING_EQUAL(exp_ucomp[s].getStringDataArrays()[a][m],exp_comp[s].getStringDataArrays()[a][m])
}
}
}
//Testing gzip compression of a whole file
PeakMap exp_whole_comp;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompressed.mzML.gz"),exp_whole_comp);
TEST_EQUAL(exp_ucomp.size(),exp_whole_comp.size())
for (Size s=0; s< exp_ucomp.size(); ++s)
{
//check if the same number of peak and meta data arrays is present
TEST_EQUAL(exp_ucomp[s].size(),exp_whole_comp[s].size())
TEST_EQUAL(exp_ucomp[s].getFloatDataArrays().size(),exp_whole_comp[s].getFloatDataArrays().size())
TEST_EQUAL(exp_ucomp[s].getIntegerDataArrays().size(),exp_whole_comp[s].getIntegerDataArrays().size())
TEST_EQUAL(exp_ucomp[s].getStringDataArrays().size(),exp_whole_comp[s].getStringDataArrays().size())
//check content of peak array
for (Size p=0; p< exp_ucomp[s].size(); ++p)
{
TEST_REAL_SIMILAR(exp_ucomp[s][p].getMZ(),exp_whole_comp[s][p].getMZ())
TEST_REAL_SIMILAR(exp_ucomp[s][p].getIntensity(),exp_whole_comp[s][p].getIntensity())
}
//check content of float arrays
for (Size a=0; a<exp_ucomp[s].getFloatDataArrays().size(); ++a)
{
for (Size m=0; m< exp_ucomp[s].getFloatDataArrays()[a].size(); ++m)
{
TEST_REAL_SIMILAR(exp_ucomp[s].getFloatDataArrays()[a][m],exp_whole_comp[s].getFloatDataArrays()[a][m])
}
}
//check content of integer arrays
for (Size a=0; a<exp_ucomp[s].getIntegerDataArrays().size(); ++a)
{
for (Size m=0; m< exp_ucomp[s].getIntegerDataArrays()[a].size(); ++m)
{
TEST_EQUAL(exp_ucomp[s].getIntegerDataArrays()[a][m],exp_whole_comp[s].getIntegerDataArrays()[a][m])
}
}
//check content of string arrays
for (Size a=0; a<exp_ucomp[s].getStringDataArrays().size(); ++a)
{
for (Size m=0; m< exp_ucomp[s].getStringDataArrays()[a].size(); ++m)
{
TEST_STRING_EQUAL(exp_ucomp[s].getStringDataArrays()[a][m],exp_whole_comp[s].getStringDataArrays()[a][m])
}
}
}
//Testing bzip2 compression of a whole file
PeakMap exp_bz;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompressed.mzML.bz2"),exp_bz);
TEST_EQUAL(exp_ucomp.size(),exp_bz.size())
for (Size s=0; s< exp_ucomp.size(); ++s)
{
//check if the same number of peak and meta data arrays is present
TEST_EQUAL(exp_ucomp[s].size(),exp_bz[s].size())
TEST_EQUAL(exp_ucomp[s].getFloatDataArrays().size(),exp_bz[s].getFloatDataArrays().size())
TEST_EQUAL(exp_ucomp[s].getIntegerDataArrays().size(),exp_bz[s].getIntegerDataArrays().size())
TEST_EQUAL(exp_ucomp[s].getStringDataArrays().size(),exp_bz[s].getStringDataArrays().size())
//check content of peak array
for (Size p=0; p< exp_ucomp[s].size(); ++p)
{
TEST_REAL_SIMILAR(exp_ucomp[s][p].getMZ(),exp_bz[s][p].getMZ())
TEST_REAL_SIMILAR(exp_ucomp[s][p].getIntensity(),exp_bz[s][p].getIntensity())
}
//check content of float arrays
for (Size a=0; a<exp_ucomp[s].getFloatDataArrays().size(); ++a)
{
for (Size m=0; m< exp_ucomp[s].getFloatDataArrays()[a].size(); ++m)
{
TEST_REAL_SIMILAR(exp_ucomp[s].getFloatDataArrays()[a][m],exp_bz[s].getFloatDataArrays()[a][m])
}
}
//check content of integer arrays
for (Size a=0; a<exp_ucomp[s].getIntegerDataArrays().size(); ++a)
{
for (Size m=0; m< exp_ucomp[s].getIntegerDataArrays()[a].size(); ++m)
{
TEST_EQUAL(exp_ucomp[s].getIntegerDataArrays()[a][m],exp_bz[s].getIntegerDataArrays()[a][m])
}
}
//check content of string arrays
for (Size a=0; a<exp_ucomp[s].getStringDataArrays().size(); ++a)
{
for (Size m=0; m< exp_ucomp[s].getStringDataArrays()[a].size(); ++m)
{
TEST_STRING_EQUAL(exp_ucomp[s].getStringDataArrays()[a][m],exp_bz[s].getStringDataArrays()[a][m])
}
}
}
//Testing corrupted files
// Note: the following two statements will trigger the AddressSanitizer
PeakMap exp_cor;
TEST_EXCEPTION(Exception::ParseError,file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompresscor.MzML.gz"),exp_cor)) // ASan says this leaks memory
PeakMap exp_cor2;
TEST_EXCEPTION(Exception::ParseError,file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompresscor.bz2"),exp_cor2)) // ASan says this leaks memory
{
//Testing automated sorting of files
PeakMap exp_inverse;
MSSpectrum spec;
MSChromatogram chrom;
Peak1D sp;
ChromatogramPeak cp;
// create spectrum and chromatogram in inversed order
for (Size i = 10; i != 0; --i)
{
sp.setMZ(i);
spec.push_back(sp);
cp.setRT(i);
chrom.push_back(cp);
}
exp_inverse.addSpectrum(spec);
exp_inverse.addChromatogram(chrom);
PeakMap exp_sorted(exp_inverse);
exp_sorted.sortSpectra(true);
exp_sorted.sortChromatograms(true);
MzMLFile file;
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
TEST_EQUAL(exp_inverse.getSpectrum(0).isSorted(), false);
TEST_EQUAL(exp_inverse.getChromatogram(0).isSorted(), false);
file.store(tmp_filename, exp_inverse);
PeakMap exp_sorted_on_load;
file.load(tmp_filename, exp_sorted_on_load);
TEST_EQUAL(exp_sorted_on_load.getSpectrum(0).isSorted(), true);
TEST_EQUAL(exp_sorted_on_load.getChromatogram(0).isSorted(), true);
}
}
END_SECTION
START_SECTION([EXTRA] load only meta data)
{
MzMLFile file;
file.getOptions().setMetadataOnly(true);
PeakMap exp;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"),exp);
TEST_EQUAL(exp.size(),0)
TEST_EQUAL(exp.getIdentifier(),"document_accession");
TEST_EQUAL(exp.getContacts().size(),2)
TEST_EQUAL(exp.getSourceFiles().size(),5);
TEST_EQUAL(exp.getInstrument().getMassAnalyzers().size(),2)
}
END_SECTION
START_SECTION([EXTRA] load with restricted MS levels)
{
MzMLFile file;
file.getOptions().addMSLevel(1);
PeakMap exp;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"),exp);
TEST_EQUAL(exp.size(),3)
TEST_REAL_SIMILAR(exp[0].getRT(),5.1)
TEST_REAL_SIMILAR(exp[1].getRT(),5.3)
TEST_REAL_SIMILAR(exp[2].getRT(),5.4)
}
END_SECTION
START_SECTION([EXTRA] load with restricted RT range)
{
MzMLFile file;
file.getOptions().setRTRange(makeRange(5.15,5.35));
PeakMap exp;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"),exp);
TEST_EQUAL(exp.size(),2)
TEST_REAL_SIMILAR(exp[0].getRT(),5.2)
TEST_REAL_SIMILAR(exp[1].getRT(),5.3)
}
END_SECTION
START_SECTION([EXTRA] load with restricted m/z range)
{
MzMLFile file;
file.getOptions().setMZRange(makeRange(6.5,9.5));
PeakMap exp;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"),exp);
TEST_EQUAL(exp.size(),4)
TEST_EQUAL(exp[0].size(),3)
TEST_REAL_SIMILAR(exp[0][0].getMZ(),7.0)
TEST_REAL_SIMILAR(exp[0][1].getMZ(),8.0)
TEST_REAL_SIMILAR(exp[0][2].getMZ(),9.0)
TEST_EQUAL(exp[1].size(),1)
TEST_REAL_SIMILAR(exp[1][0].getMZ(),8.0)
TEST_EQUAL(exp[2].size(),3)
TEST_REAL_SIMILAR(exp[2][0].getMZ(),7.0)
TEST_REAL_SIMILAR(exp[2][1].getMZ(),8.0)
TEST_REAL_SIMILAR(exp[2][2].getMZ(),9.0)
TEST_EQUAL(exp[3].size(),0)
}
END_SECTION
START_SECTION([EXTRA] load intensity range)
{
MzMLFile file;
file.getOptions().setIntensityRange(makeRange(6.5,9.5));
PeakMap exp;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"),exp);
TEST_EQUAL(exp.size(),4)
TEST_EQUAL(exp[0].size(),3)
TEST_REAL_SIMILAR(exp[0][0].getIntensity(),9.0)
TEST_REAL_SIMILAR(exp[0][1].getIntensity(),8.0)
TEST_REAL_SIMILAR(exp[0][2].getIntensity(),7.0)
TEST_EQUAL(exp[1].size(),1)
TEST_REAL_SIMILAR(exp[1][0].getIntensity(),8.0)
TEST_EQUAL(exp[2].size(),3)
TEST_REAL_SIMILAR(exp[2][0].getIntensity(),9.0)
TEST_REAL_SIMILAR(exp[2][1].getIntensity(),8.0)
TEST_REAL_SIMILAR(exp[2][2].getIntensity(),7.0)
TEST_EQUAL(exp[3].size(),0)
}
END_SECTION
START_SECTION([EXTRA] load xsd:integer types)
{
MzMLFile file;
PeakMap exp;
// just load without crashing...
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_xsd-ranges.mzML"), exp);
NOT_TESTABLE
}
END_SECTION
START_SECTION((template <typename MapType> void store(const String& filename, const MapType& map) const))
{
MzMLFile file;
//test with full file
{
//load map
PeakMap exp_original;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp_original);
//store map
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
file.store(tmp_filename, exp_original);
//load written map
PeakMap exp;
file.load(tmp_filename, exp);
//test if everything worked
TEST_TRUE(exp == exp_original)
//NOTE: If it does not work, use this code to find out where the difference is
TEST_EQUAL(exp.size() == exp_original.size(), true)
TEST_EQUAL(exp.ExperimentalSettings::operator==(exp_original), true)
TEST_EQUAL(exp[0].SpectrumSettings::operator==(exp_original[0]), true)
TEST_EQUAL(exp[0] == exp_original[0], true)
TEST_EQUAL(exp[1].SpectrumSettings::operator==(exp_original[1]), true)
TEST_EQUAL(exp[1] == exp_original[1], true)
TEST_EQUAL(exp[2].SpectrumSettings::operator==(exp_original[2]), true)
TEST_EQUAL(exp[2] == exp_original[2], true)
TEST_EQUAL(exp[3].SpectrumSettings::operator==(exp_original[3]), true)
TEST_EQUAL(exp[3] == exp_original[3], true)
TEST_EQUAL(exp.getChromatograms().size(), exp_original.getChromatograms().size());
TEST_EQUAL(exp.getChromatograms() == exp_original.getChromatograms(), true);
}
//test with empty map
{
PeakMap empty, exp;
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
file.store(tmp_filename,empty);
file.load(tmp_filename,exp);
TEST_EQUAL(exp==empty,true)
}
//test with one empty spectrum
{
PeakMap empty, exp;
empty.resize(1);
empty[0].setRT(17.1234);
//this will be set when writing (forced by mzML)
empty[0].setNativeID("spectrum=0");
empty[0].getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MS1SPECTRUM);
empty[0].getDataProcessing().emplace_back( new DataProcessing() );
empty[0].getDataProcessing()[0]->getProcessingActions().insert(DataProcessing::CONVERSION_MZML);
empty[0].getAcquisitionInfo().setMethodOfCombination("no combination");
empty[0].getAcquisitionInfo().resize(1);
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
file.store(tmp_filename,empty);
file.load(tmp_filename,exp);
TEST_EQUAL(exp == empty,true)
//NOTE: If it does not work, use this code to find out where the difference is
// TEST_EQUAL(exp.size()==empty.size(),true)
// TEST_EQUAL(exp.ExperimentalSettings::operator==(empty),true)
// TEST_EQUAL(exp[0].SpectrumSettings::operator==(empty[0]),true)
// TEST_EQUAL(exp[0]==empty[0],true);
}
//test 32/64 bit floats, 32/64 bit integer, null terminated strings, zlib compression
{
//load map
PeakMap exp_original;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_6_uncompressed.mzML"),exp_original);
//store map
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
file.getOptions().setCompression(true);
file.store(tmp_filename,exp_original);
//load written map
PeakMap exp;
file.load(tmp_filename,exp);
//test if everything worked
TEST_EQUAL(exp == exp_original,true)
}
}
END_SECTION
START_SECTION((void storeBuffer(std::string & output, const PeakMap& map) const))
{
MzMLFile file;
// test with full file
{
// load map
PeakMap exp_original;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), exp_original);
// store map in our output buffer
std::string out;
file.storeBuffer(out, exp_original);
TEST_EQUAL(out.size(), 38070)
TEST_EQUAL(out.substr(0, 100), "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<indexedmzML xmlns=\"http://psi.hupo.org/ms/mzml\" xmlns:x")
TEST_EQUAL(out.substr(38070 - 99, 38070 - 1), "</indexList>\n<indexListOffset>37622</indexListOffset>\n<fileChecksum>0</fileChecksum>\n</indexedmzML>")
TEST_EQUAL(String(out).hasSubstring("<spectrumList count=\"4\" defaultDataProcessingRef=\"dp_sp_0\">"), true)
TEST_EQUAL(String(out).hasSubstring("<chromatogramList count=\"2\" defaultDataProcessingRef=\"dp_sp_0\">"), true)
}
//test with empty map
{
PeakMap empty;
//store map
std::string out;
file.storeBuffer(out, empty);
TEST_EQUAL(out.size(), 3167)
TEST_EQUAL(out.substr(0, 100), "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<indexedmzML xmlns=\"http://psi.hupo.org/ms/mzml\" xmlns:x")
TEST_EQUAL(out.substr(3167-98, 3167-1), "</indexList>\n<indexListOffset>2978</indexListOffset>\n<fileChecksum>0</fileChecksum>\n</indexedmzML>")
}
}
END_SECTION
START_SECTION(bool isValid(const String& filename, std::ostream& os = std::cerr))
{
std::string tmp_filename;
MzMLFile file;
PeakMap e;
//written empty file
NEW_TMP_FILE(tmp_filename);
file.store(tmp_filename,e);
TEST_EQUAL(file.isValid(tmp_filename),true);
//written filled file
NEW_TMP_FILE(tmp_filename);
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"),e);
file.store(tmp_filename,e);
TEST_EQUAL(file.isValid(tmp_filename),true);
//indexed file
TEST_EQUAL(file.isValid(OPENMS_GET_TEST_DATA_PATH("MzMLFile_4_indexed.mzML")),true)
}
END_SECTION
START_SECTION(bool isSemanticallyValid(const String& filename, StringList& errors, StringList& warnings))
{
std::string tmp_filename;
MzMLFile file;
StringList errors, warnings;
PeakMap e;
//written empty file
NEW_TMP_FILE(tmp_filename);
file.store(tmp_filename,e);
TEST_EQUAL(file.isSemanticallyValid(tmp_filename, errors, warnings),true);
TEST_EQUAL(errors.size(),0)
TEST_EQUAL(warnings.size(),0)
//written filled file
NEW_TMP_FILE(tmp_filename);
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"),e);
file.store(tmp_filename,e);
TEST_EQUAL(file.isSemanticallyValid(tmp_filename, errors, warnings),true);
TEST_EQUAL(errors.size(),0)
TEST_EQUAL(warnings.size(),2) // add mappings for chromatogram/precursor/activation and selectedIon to reduce that count
//valid file
TEST_EQUAL(file.isSemanticallyValid(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), errors, warnings),true)
TEST_EQUAL(errors.size(),0)
TEST_EQUAL(warnings.size(),0)
for (Size i=0; i<errors.size(); ++i)
{
cout << "ERROR: " << errors[i] << endl;
}
for (Size i=0; i<warnings.size(); ++i)
{
cout << "WARNING: " << warnings[i] << endl;
}
//indexed MzML
TEST_EQUAL(file.isSemanticallyValid(OPENMS_GET_TEST_DATA_PATH("MzMLFile_4_indexed.mzML"), errors, warnings),true)
TEST_EQUAL(errors.size(), 0)
TEST_EQUAL(warnings.size(), 0)
//invalid file
TEST_EQUAL(file.isSemanticallyValid(OPENMS_GET_TEST_DATA_PATH("MzMLFile_3_invalid.mzML"), errors, warnings),false)
TEST_EQUAL(errors.size(), 8)
TEST_EQUAL(warnings.size(), 1)
// for (Size i=0; i<errors.size(); ++i)
// {
// cout << "ERROR: " << errors[i] << endl;
// }
// for (Size i=0; i<warnings.size(); ++i)
// {
// cout << "WARNING: " << warnings[i] << endl;
// }
}
END_SECTION
START_SECTION(void transform(const String& filename_in, Interfaces::IMSDataConsumer * consumer, bool skip_full_count = false, bool skip_first_pass = false))
{
// Create the consumer, set output file name, transform
TICConsumer consumer;
MzMLFile mzml;
String in = OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML");
PeakFileOptions opt = mzml.getOptions();
opt.setFillData(true); // whether to actually load any data
opt.setSkipXMLChecks(true); // save time by not checking base64 strings for whitespaces
opt.setMaxDataPoolSize(100);
opt.setAlwaysAppendData(false);
mzml.setOptions(opt);
mzml.transform(in, &consumer, true, true);
TEST_EQUAL(consumer.nr_spectra, 4)
TEST_EQUAL(consumer.nr_peaks, 40)
TEST_REAL_SIMILAR(consumer.TIC, 350)
}
END_SECTION
START_SECTION(void transform(const String& filename_in, Interfaces::IMSDataConsumer * consumer, PeakMap& map, bool skip_full_count = false, bool skip_first_pass = false))
{
// Create the consumer, set output file name, transform
TICConsumer consumer;
MzMLFile mzml;
PeakMap map;
String in = OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML");
PeakFileOptions opt = mzml.getOptions();
opt.setFillData(true); // whether to actually load any data
opt.setSkipXMLChecks(true); // save time by not checking base64 strings for whitespaces
opt.setMaxDataPoolSize(100);
opt.setAlwaysAppendData(false);
mzml.setOptions(opt);
mzml.transform(in, &consumer, map, true, true);
TEST_EQUAL(consumer.nr_spectra, 4)
TEST_EQUAL(consumer.nr_peaks, 40)
TEST_REAL_SIMILAR(consumer.TIC, 350)
TEST_EQUAL(map.getNrSpectra(), 4)
}
END_SECTION
START_SECTION((void testSkipChromatograms()))
{
MzMLFile file;
PeakFileOptions opts;
opts.setSkipChromatograms(true);
file.setOptions(opts);
PeakMap pm;
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), pm);
TEST_EQUAL(pm.getChromatograms().size(), 0)
opts.setSkipChromatograms(false);
file.setOptions(opts);
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), pm);
TEST_NOT_EQUAL(pm.getChromatograms().size(), 0)
}
END_SECTION
START_SECTION((test negative isolation window offsets are skipped))
{
// Test that negative isolation window offsets (which indicate null/invalid values)
// are properly skipped and don't cause exceptions
MzMLFile file;
PeakMap exp;
// This should not throw an exception even though the file contains negative offsets
file.load(OPENMS_GET_TEST_DATA_PATH("MzMLFile_negative_offsets.mzML"), exp);
// Verify the file was loaded
TEST_EQUAL(exp.size(), 2)
// Check the MS2 spectrum (second spectrum, index 1)
TEST_EQUAL(exp[1].getPrecursors().size(), 1)
// Verify that the precursor m/z was set correctly
TEST_REAL_SIMILAR(exp[1].getPrecursors()[0].getMZ(), 577.298034667969)
// Verify that the negative offsets were NOT set (should remain at default value of 0)
TEST_REAL_SIMILAR(exp[1].getPrecursors()[0].getIsolationWindowLowerOffset(), 0.0)
TEST_REAL_SIMILAR(exp[1].getPrecursors()[0].getIsolationWindowUpperOffset(), 0.0)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MRMFeature_test.cpp | .cpp | 5,354 | 213 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/KERNEL/MRMFeature.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(MRMFeature, "$Id$")
/////////////////////////////////////////////////////////////
MRMFeature* ptr = nullptr;
MRMFeature* nullPointer = nullptr;
START_SECTION(MRMFeature())
{
ptr = new MRMFeature();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~MRMFeature())
{
delete ptr;
}
END_SECTION
START_SECTION(MRMFeature(const MRMFeature &rhs))
{
MRMFeature tmp;
tmp.setIntensity(100.0);
tmp.addScore("testscore", 200);
MRMFeature tmp2 (tmp);
TEST_REAL_SIMILAR(tmp2.getMetaValue("testscore"), 200)
TEST_REAL_SIMILAR(tmp2.getIntensity(), 100.0)
}
END_SECTION
START_SECTION((MRMFeature(const MRMFeature&& source)))
{
#ifndef OPENMS_COMPILER_MSVC
// Ensure that MRMFeature has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
// Note that MSVS does not support noexcept move constructors for STL
// constructs such as std::map.
TEST_EQUAL(noexcept(MRMFeature(std::declval<MRMFeature&&>())), true)
#endif
}
END_SECTION
START_SECTION(MRMFeature& operator=(const MRMFeature &rhs))
{
MRMFeature tmp;
tmp.setIntensity(100.0);
tmp.addScore("testscore", 200);
MRMFeature tmp2;
tmp2 = tmp;
TEST_REAL_SIMILAR(tmp2.getMetaValue("testscore"), 200)
TEST_REAL_SIMILAR(tmp2.getIntensity(), 100.0)
}
END_SECTION
START_SECTION (const PGScoresType & getScores() const)
{
// tested with set/add score
NOT_TESTABLE
}
END_SECTION
START_SECTION (double getScore(const String & score_name))
{
// tested with set/add score
NOT_TESTABLE
}
END_SECTION
START_SECTION (Feature & getFeature(String key))
{
MRMFeature mrmfeature;
Feature f1;
f1.setMetaValue("dummy", 1);
Feature f2;
mrmfeature.addFeature(f1, "chromatogram1");
mrmfeature.addFeature(f1, "chromatogram2");
TEST_EQUAL(mrmfeature.getFeature("chromatogram1").getMetaValue("dummy"), 1)
}
END_SECTION
START_SECTION (void setScores(const PGScoresType & scores))
{
MRMFeature mrmfeature;
OpenSwath_Scores scores;
scores.library_sangle = 99;
mrmfeature.setScores(scores);
TEST_REAL_SIMILAR(scores.library_sangle, mrmfeature.getScores().library_sangle)
}
END_SECTION
START_SECTION (void addScore(const String & score_name, double score))
{
MRMFeature mrmfeature;
mrmfeature.addScore("score1",1);
mrmfeature.addScore("score2",2);
TEST_REAL_SIMILAR(mrmfeature.getMetaValue("score1"), 1)
TEST_REAL_SIMILAR(mrmfeature.getMetaValue("score2"), 2)
}
END_SECTION
START_SECTION (void addFeature(Feature & feature, const String & key))
{
// tested in getFeature
NOT_TESTABLE
}
END_SECTION
START_SECTION (const std::vector<Feature> & getFeatures() const)
{
MRMFeature mrmfeature;
Feature f1;
f1.setMetaValue("dummy", 1);
Feature f2;
mrmfeature.addFeature(f1, "chromatogram1");
mrmfeature.addFeature(f1, "chromatogram2");
TEST_EQUAL(mrmfeature.getFeatures().size(), 2)
}
END_SECTION
START_SECTION (void getFeatureIDs(std::vector<String> & result) const)
{
MRMFeature mrmfeature;
Feature f1;
f1.setMetaValue("dummy", 1);
Feature f2;
mrmfeature.addFeature(f1, "chromatogram1");
mrmfeature.addFeature(f1, "chromatogram2");
std::vector<String> result;
mrmfeature.getFeatureIDs(result);
TEST_EQUAL(result.size(), 2)
TEST_EQUAL(result[0], "chromatogram1")
TEST_EQUAL(result[1], "chromatogram2")
}
END_SECTION
START_SECTION (void addPrecursorFeature(Feature & feature, const String & key))
{
// Initially, there should be no feature present
MRMFeature mrmfeature;
{
std::vector<String> result;
mrmfeature.getPrecursorFeatureIDs(result);
TEST_EQUAL(result.size(), 0)
}
// After adding a feature, there should be one feature present
Feature f1;
mrmfeature.addPrecursorFeature(f1, "precursor_chromatogram1");
{
std::vector<String> result;
mrmfeature.getPrecursorFeatureIDs(result);
TEST_EQUAL(result.size(), 1)
}
}
END_SECTION
START_SECTION (void getPrecursorFeatureIDs(std::vector<String> & result) const)
{
MRMFeature mrmfeature;
Feature f1;
f1.setMetaValue("dummy", 1);
Feature f2;
mrmfeature.addPrecursorFeature(f1, "chromatogram1");
mrmfeature.addPrecursorFeature(f1, "chromatogram2");
std::vector<String> result;
mrmfeature.getPrecursorFeatureIDs(result);
TEST_EQUAL(result.size(), 2)
TEST_EQUAL(result[0], "chromatogram1")
TEST_EQUAL(result[1], "chromatogram2")
}
END_SECTION
START_SECTION (Feature & getPrecursorFeature(String key))
{
MRMFeature mrmfeature;
Feature f1;
f1.setMetaValue("dummy", 1);
Feature f2;
mrmfeature.addPrecursorFeature(f1, "chromatogram1");
mrmfeature.addPrecursorFeature(f1, "chromatogram2");
TEST_EQUAL(mrmfeature.getPrecursorFeature("chromatogram1").getMetaValue("dummy"), 1)
}
END_SECTION
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SimpleSVM_test.cpp | .cpp | 12,655 | 356 | // 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/ML/SVM/SimpleSVM.h>
///////////////////////////
#include <fstream>
#include <sstream>
using namespace OpenMS;
using namespace std;
START_TEST(SimpleSVM, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
SimpleSVM* ptr = nullptr;
SimpleSVM* null_ptr = nullptr;
START_SECTION((SimpleSVM()))
{
ptr = new SimpleSVM();
TEST_NOT_EQUAL(ptr, null_ptr);
}
END_SECTION
START_SECTION((~SimpleSVM()))
{
delete ptr;
}
END_SECTION
SimpleSVM svm, untrained_svm;
SimpleSVM::PredictorMap predictors;
map<Size, double> labels;
// read test data:
ifstream pred_file(OPENMS_GET_TEST_DATA_PATH("SimpleSVM_test_predictors.txt"));
if (pred_file.is_open())
{
string line;
while (getline(pred_file, line))
{
stringstream ss(line);
String name;
ss >> name;
while (ss.good())
{
double value;
ss >> value;
predictors[name].push_back(value);
}
}
pred_file.close();
}
ifstream label_file(OPENMS_GET_TEST_DATA_PATH("SimpleSVM_test_labels.txt"));
if (label_file.is_open())
{
while (label_file.good())
{
Size index;
Int label;
label_file >> index >> label;
labels[index] = label;
}
label_file.close();
}
START_SECTION((~SimpleSVM))
{
SimpleSVM* svm_new = new SimpleSVM();
delete svm_new;
}
END_SECTION
START_SECTION((void setup(PredictorMap& predictors,
const map<Size, double>& labels)))
{
ABORT_IF(predictors.empty());
ABORT_IF(labels.empty());
SimpleSVM::PredictorMap empty_pred;
TEST_EXCEPTION(Exception::IllegalArgument, svm.setup(empty_pred, labels));
map<Size, double> bad_labels;
bad_labels[0] = 1;
SimpleSVM::PredictorMap tmp(predictors); // copy predictors to prevent rescaling to 0..1
TEST_EXCEPTION(Exception::MissingInformation,
svm.setup(tmp, bad_labels));
bad_labels[100] = 0;
tmp = predictors; // copy predictors to prevent rescaling to 0..1
TEST_EXCEPTION(Exception::InvalidValue, svm.setup(tmp, bad_labels));
svm.setup(predictors, labels);
// check that data has been scaled:
for (const auto& it : predictors)
{
vector<double>::const_iterator pos = min_element(it.second.begin(),
it.second.end());
TEST_REAL_SIMILAR(*pos, 0);
pos = max_element(it.second.begin(), it.second.end());
TEST_REAL_SIMILAR(*pos, 1);
}
}
END_SECTION
START_SECTION((void predict(vector<Prediction>& predictions,
vector<Size> indexes) const))
{
vector<SimpleSVM::Prediction> predictions;
TEST_EXCEPTION(Exception::Precondition, untrained_svm.predict(predictions));
svm.predict(predictions);
TEST_EQUAL(predictions.size(), predictors.begin()->second.size());
for (vector<SimpleSVM::Prediction>::iterator it = predictions.begin();
it != predictions.end(); ++it)
{
if (it->outcome == 0)
{
TEST_EQUAL((it->probabilities[0] > 0.5) && (it->probabilities[0] < 1.0) &&
(it->probabilities[1] < 0.5) && (it->probabilities[1] > 0.0),
true);
}
else if (it->outcome == 1)
{
TEST_EQUAL((it->probabilities[1] > 0.5) && (it->probabilities[1] < 1.0) &&
(it->probabilities[0] < 0.5) && (it->probabilities[0] > 0.0),
true);
}
else TEST_EQUAL((it->outcome == 0) || (it->outcome == 1), true);
}
vector<Size> indexes(1, 0);
svm.predict(predictions, indexes);
TEST_EQUAL(predictions.size(), 1);
indexes.push_back(100);
TEST_EXCEPTION(Exception::InvalidValue, svm.predict(predictions, indexes));
}
END_SECTION
START_SECTION((void getFeatureWeights(map<String, double> feature_weights)
const))
{
map<String, double> feat_weights;
TEST_EXCEPTION(Exception::Precondition,
untrained_svm.getFeatureWeights(feat_weights));
svm.getFeatureWeights(feat_weights);
TEST_EQUAL(feat_weights.size(), predictors.size());
}
END_SECTION
START_SECTION((map<String, pair<double, double>> void getScaling()
const))
{
auto scaling = svm.getScaling();
TEST_REAL_SIMILAR(scaling["main_var_xx_swath_prelim_score"].first, -8.88447);
TEST_REAL_SIMILAR(scaling["main_var_xx_swath_prelim_score"].second, 4.96923);
TEST_REAL_SIMILAR(scaling["peak_apices_sum"].first, 1333.54);
TEST_REAL_SIMILAR(scaling["peak_apices_sum"].second, 16131200);
TEST_REAL_SIMILAR(scaling["rt_delta"].first, 0.0);
TEST_REAL_SIMILAR(scaling["rt_delta"].second, 308.866);
TEST_REAL_SIMILAR(scaling["sn_ratio"].first, 0.460926);
TEST_REAL_SIMILAR(scaling["sn_ratio"].second, 176.142);
TEST_REAL_SIMILAR(scaling["var_elution_model_fit_score"].first, -0.0801376);
TEST_REAL_SIMILAR(scaling["var_elution_model_fit_score"].second, 0.998876);
TEST_REAL_SIMILAR(scaling["var_intensity_score"].first, 0.00847651);
TEST_REAL_SIMILAR(scaling["var_intensity_score"].second, 0.994559);
TEST_REAL_SIMILAR(scaling["var_isotope_correlation_score"].first, -0.407676);
TEST_REAL_SIMILAR(scaling["var_isotope_correlation_score"].second, 0.999652);
TEST_REAL_SIMILAR(scaling["var_isotope_overlap_score"].first, 0.0);
TEST_REAL_SIMILAR(scaling["var_isotope_overlap_score"].second, 1.0);
TEST_REAL_SIMILAR(scaling["var_library_sangle"].first, 0.00104554)
TEST_REAL_SIMILAR(scaling["var_library_sangle"].second, 1.17082);
TEST_REAL_SIMILAR(scaling["var_log_sn_score"].first, 0.0);
TEST_REAL_SIMILAR(scaling["var_log_sn_score"].second, 5.17129);
TEST_REAL_SIMILAR(scaling["var_massdev_score"].first, 0.0)
TEST_REAL_SIMILAR(scaling["var_massdev_score"].second, 34.4887);
TEST_REAL_SIMILAR(scaling["var_xcorr_coelution"].first, 0.0)
TEST_REAL_SIMILAR(scaling["var_xcorr_coelution"].second, 73.397);
TEST_REAL_SIMILAR(scaling["var_xcorr_shape"].first, 0.333333)
TEST_REAL_SIMILAR(scaling["var_xcorr_shape"].second, 0.999965);
TEST_REAL_SIMILAR(scaling["xx_lda_prelim_score"].first, -4.61057)
TEST_REAL_SIMILAR(scaling["xx_lda_prelim_score"].second, 7.95003);
TEST_EQUAL(scaling.size(), predictors.size()); // one min/max entry for every predictor
}
END_SECTION
START_SECTION((void writeXvalResults(const String& path) const))
{
string xval_file;
NEW_TMP_FILE(xval_file);
svm.writeXvalResults(xval_file);
// cross-validation results are somewhat random, so don't be too strict:
TOLERANCE_ABSOLUTE(0.2);
TOLERANCE_RELATIVE(1.2);
TEST_FILE_SIMILAR(xval_file,
OPENMS_GET_TEST_DATA_PATH("SimpleSVM_test_xval.txt"));
}
END_SECTION
START_SECTION(regression_train_and_predict_on_all)
{
// create some noisy sinus data (data with clear outlier)
// python code:
// X = np.sort(5 * np.random.rand(40, 1), axis=0)
// y = np.sin(X).ravel()
// # add noise to targets
// y[::5] += 3 * (0.5 - np.random.rand(8))
SimpleSVM::PredictorMap x{ {"x", {
0.0604460, 0.0827345, 0.0860808, 0.1587253,
0.2340380, 0.2376890, 0.2420991, 0.3825909,
0.4185480, 0.4909027, 0.7375445, 0.9507514,
0.9566240, 1.0680931, 1.1448901, 1.2531016,
1.3127954, 1.6548730, 1.8522109, 1.9021369,
2.0112177, 2.2142165, 2.2331448, 2.3437173,
2.7221007, 2.8684072, 2.9972565, 3.0146882,
3.0934168, 3.2048384, 3.2171502, 3.2959385,
3.6047516, 4.0592506, 4.0725104, 4.1267237,
4.7097008, 4.7699635, 4.8069954, 4.8126888 }}};
map<Size, double> y{ {
{0, -0.0604637}, {1, 0.0826401}, {2, 0.0859745}, {3, 0.1580597}, {4, 0.2319073}, {5, 1.1990320},
{6, 0.2397410}, {7, 0.3733253}, {8, 0.4064343}, {9, 0.4714222}, {10, 2.1056848}, {11, 0.8138523},
{12, 0.8172507}, {13, 0.8762834}, {14, 0.9106647}, {15, 1.4817945}, {16, 0.9669019}, {17, 0.9964676},
{18, 0.9606635}, {19, 0.9456070}, {20, 1.3416947}, {21, 0.8000485}, {22, 0.7885501}, {23, 0.7158742},
{24, 0.4072964}, {25, -0.1396564}, {26, 0.1438354}, {27, 0.1265640}, {28, 0.0481571}, {29, -0.0632036},
{30, -0.2082548}, {31, -0.1537337}, {32, -0.4467765}, {33, -0.7941806}, {34, -0.8021682}, {35, -1.9997169},
{36, -0.9999963}, {37, -0.9983430}, {38, -0.9955281}, {39, -0.9949741 } } };
auto param = svm.getParameters();
param.setValue("kernel", "RBF");
param.setValue("log2_C", ListUtils::create<double>("9,11,13"));
param.setValue("log2_gamma", ListUtils::create<double>("-1,1,3"));
param.setValue("log2_p", ListUtils::create<double>("-6,-3.32192809489,0,3.32192809489"));
svm.setParameters(param);
svm.setup(x, y, false); // set up regression
vector<SimpleSVM::Prediction> predictions;
svm.predict(predictions);
// test a few inlier
TEST_EQUAL(std::abs(predictions[0].outcome - y[0]) < 0.2, true);
TEST_EQUAL(std::abs(predictions[23].outcome - y[23]) < 0.2, true);
TEST_EQUAL(std::abs(predictions[36].outcome - y[36]) < 0.2, true);
// test a few outlier
TEST_EQUAL(std::abs(predictions[10].outcome - y[10]) > 0.2, true);
TEST_EQUAL(std::abs(predictions[15].outcome - y[15]) > 0.2, true);
TEST_EQUAL(std::abs(predictions[35].outcome - y[35]) > 0.2, true);
/* debug code to produce prediction error
size_t index{};
for (const auto& p : predictions)
{
std::cout << "index: " << index << " y: " << y[index] << " predicted y: " << p.outcome << " abs. error: " << std::abs(y[index] - p.outcome) << std::endl;
++index;
}
*/
}
END_SECTION
START_SECTION(regression_train_and_predict_on_separate)
{
// Same data as above but with split out test data (inlier + outlier)
SimpleSVM::PredictorMap x{ {"x", {
0.0827345, 0.0860808, 0.1587253,
0.2340380, 0.2376890, 0.2420991, 0.3825909,
0.4185480, 0.4909027, 0.9507514,
0.9566240, 1.0680931, 1.1448901,
1.3127954, 1.6548730, 1.8522109, 1.9021369,
2.0112177, 2.2142165, 2.2331448,
2.7221007, 2.8684072, 2.9972565, 3.0146882,
3.0934168, 3.2048384, 3.2171502, 3.2959385,
3.6047516, 4.0592506, 4.0725104,
4.7699635, 4.8069954, 4.8126888 }}};
map<Size, double> y{ {
{0, 0.0826401}, {1, 0.0859745}, {2, 0.1580597}, {3, 0.2319073}, {4, 1.1990320},
{5, 0.2397410}, {6, 0.3733253}, {7, 0.4064343}, {8, 0.4714222}, {9, 0.8138523},
{10, 0.8172507}, {11, 0.8762834}, {12, 0.9106647}, {13, 0.9669019}, {14, 0.9964676},
{15, 0.9606635}, {16, 0.9456070}, {17, 1.3416947}, {18, 0.8000485}, {19, 0.7885501},
{20, 0.4072964}, {21, -0.1396564}, {22, 0.1438354}, {23, 0.1265640}, {24, 0.0481571}, {25, -0.0632036},
{26, -0.2082548}, {27, -0.1537337}, {28, -0.4467765}, {29, -0.7941806}, {30, -0.8021682},
{31, -0.9983430}, {32, -0.9955281}, {33, -0.9949741 } } };
SimpleSVM::PredictorMap x_test{ {"x", {
0.0604460,
0.7375445,
1.2531016,
2.3437173,
4.1267237,
4.7097008 }}};
map<Size, double> y_test{ {
{0, -0.0604637},
{1, 2.1056848},
{2, 1.4817945},
{3, 0.7158742},
{4, -1.9997169},
{5, -0.9999963} } };
auto param = svm.getParameters();
param.setValue("kernel", "RBF");
param.setValue("log2_C", ListUtils::create<double>("1,5"));
param.setValue("log2_gamma", ListUtils::create<double>("-5,5"));
param.setValue("log2_p", ListUtils::create<double>("-15,-3.32192809489"));
svm.setParameters(param);
svm.setParameters(param);
svm.setup(x, y, false); // set up regression
vector<SimpleSVM::Prediction> predictions;
svm.predict(x_test, predictions);
// test a few inlier
TEST_EQUAL(std::abs(predictions[0].outcome - y_test[0]) < 0.2, true);
TEST_EQUAL(std::abs(predictions[3].outcome - y_test[3]) < 0.2, true);
TEST_EQUAL(std::abs(predictions[5].outcome - y_test[5]) < 0.2, true);
// test a few outlier
TEST_EQUAL(std::abs(predictions[1].outcome - y_test[1]) > 0.2, true);
TEST_EQUAL(std::abs(predictions[2].outcome - y_test[2]) > 0.2, true);
TEST_EQUAL(std::abs(predictions[4].outcome - y_test[4]) > 0.2, true);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IsobaricQuantifier_test.cpp | .cpp | 2,665 | 98 | // 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/IsobaricQuantifier.h>
///////////////////////////
#include <OpenMS/ANALYSIS/QUANTITATION/ItraqFourPlexQuantitationMethod.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
using namespace OpenMS;
using namespace std;
START_TEST(IsobaricQuantifier, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IsobaricQuantifier* ptr = nullptr;
IsobaricQuantifier* null_ptr = nullptr;
ItraqFourPlexQuantitationMethod quant_meth;
START_SECTION((IsobaricQuantifier(const IsobaricQuantitationMethod *const quant_method)))
{
ptr = new IsobaricQuantifier(&quant_meth);
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IsobaricQuantifier())
{
delete ptr;
}
END_SECTION
START_SECTION((IsobaricQuantifier(const IsobaricQuantifier &other)))
{
IsobaricQuantifier quantifier(&quant_meth);
IsobaricQuantifier * quantifier2 = new IsobaricQuantifier(quantifier);
TEST_NOT_EQUAL(quantifier2, null_ptr)
delete quantifier2;
// equality cannot be checked
NOT_TESTABLE
}
END_SECTION
START_SECTION((IsobaricQuantifier& operator=(const IsobaricQuantifier &rhs)))
{
IsobaricQuantifier quantifier(&quant_meth);
IsobaricQuantifier quantifier2(&quant_meth);
quantifier2 = quantifier;
// equality cannot be checked
NOT_TESTABLE
}
END_SECTION
START_SECTION((void quantify(const ConsensusMap &consensus_map_in, ConsensusMap &consensus_map_out)))
{
ConsensusXMLFile cm_file;
ConsensusMap cm_in, cm_out;
cm_file.load(OPENMS_GET_TEST_DATA_PATH("IsobaricQuantifier.consensusXML"),cm_in);
IsobaricQuantifier iq(&quant_meth);
Param p;
p.setValue("normalization", "true");
p.setValue("isotope_correction", "true");
iq.setParameters(p);
iq.quantify(cm_in,cm_out);
String cm_file_out;
NEW_TMP_FILE(cm_file_out);
cm_file.store(cm_file_out,cm_out);
WHITELIST("<?xml-stylesheet");
// WHITELIST("<?xml-stylesheet,consensusElement id=");
TEST_FILE_SIMILAR(cm_file_out,OPENMS_GET_TEST_DATA_PATH("IsobaricQuantifier_out.consensusXML"));
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/TraMLFile_test.cpp | .cpp | 5,575 | 209 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/TraMLFile.h>
///////////////////////////
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
using namespace OpenMS;
using namespace std;
START_TEST(TraMLFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
TraMLFile * ptr = nullptr;
TraMLFile * nullPointer = nullptr;
START_SECTION((TraMLFile()))
{
ptr = new TraMLFile;
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION((~TraMLFile()))
{
delete ptr;
}
END_SECTION
START_SECTION((void load(const String &filename, TargetedExperiment & id)))
{
NOT_TESTABLE // tested below
}
END_SECTION
START_SECTION((void store(const String &filename, const TargetedExperiment &id) const))
{
TraMLFile file;
//load map
TargetedExperiment exp_original;
file.load(OPENMS_GET_TEST_DATA_PATH("ToyExample1.traML"), exp_original);
//store map
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
file.store(tmp_filename, exp_original);
//load written map
TargetedExperiment exp;
file.load(tmp_filename, exp);
//test if everything worked
TEST_TRUE(exp == exp_original)
// Test storing a minimal example
{
TargetedExperiment minimal_exp;
NEW_TMP_FILE(tmp_filename);
file.store(tmp_filename, minimal_exp);
TargetedExperiment newexp;
file.load(tmp_filename, newexp);
// Test if everything worked
//
// The two objects are not exactly identical, while storing some CVs are
// added that are not present in the newly instantiated object but get
// added to the object when loaded.
minimal_exp.setCVs(newexp.getCVs());
TEST_TRUE(newexp == minimal_exp)
}
// Test storing a minimal example (with one protein/peptide/transition)
{
TargetedExperiment minimal_exp;
TargetedExperimentHelper::Protein protein;
TargetedExperimentHelper::Peptide peptide;
ReactionMonitoringTransition tr;
minimal_exp.addProtein(protein);
minimal_exp.addPeptide(peptide);
minimal_exp.addTransition(tr);
NEW_TMP_FILE(tmp_filename);
file.store(tmp_filename, minimal_exp);
TargetedExperiment newexp;
file.load(tmp_filename, newexp);
// Test if everything worked
//
// The two objects are not exactly identical, while storing some CVs are
// added that are not present in the newly instantiated object but get
// added to the object when loaded.
minimal_exp.setCVs(newexp.getCVs());
TEST_TRUE(newexp == minimal_exp)
}
}
END_SECTION
START_SECTION((void equal()))
{
TraMLFile file;
TargetedExperiment exp_original;
TargetedExperiment exp_second;
file.load(OPENMS_GET_TEST_DATA_PATH("ToyExample1.traML"), exp_original);
file.load(OPENMS_GET_TEST_DATA_PATH("ToyExample1.traML"), exp_second);
TEST_TRUE(exp_second == exp_original)
}
END_SECTION
START_SECTION((void assign()))
{
TraMLFile file;
//load map
TargetedExperiment exp_original;
TargetedExperiment exp_added;
file.load(OPENMS_GET_TEST_DATA_PATH("ToyExample1.traML"), exp_original);
//store map
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
exp_added = exp_original;
TEST_EQUAL(exp_original.getTargetCVTerms().getCVTerms().size(), 1)
TEST_EQUAL(exp_added.getTargetCVTerms().getCVTerms().size(), 1)
TEST_TRUE(exp_added == exp_original)
}
END_SECTION
START_SECTION((void add()))
{
TraMLFile file;
//load map
TargetedExperiment exp_original;
TargetedExperiment exp_added;
file.load(OPENMS_GET_TEST_DATA_PATH("ToyExample1.traML"), exp_original);
//store map
std::string tmp_filename;
NEW_TMP_FILE(tmp_filename);
exp_added += exp_original;
TEST_TRUE(exp_added == exp_original)
}
END_SECTION
START_SECTION([EXTRA] bool isValid(const String & filename, std::ostream & os = std::cerr))
{
std::string tmp_filename;
TraMLFile file;
TargetedExperiment e;
//written empty file
NEW_TMP_FILE(tmp_filename);
file.store(tmp_filename, e);
TEST_EQUAL(file.isValid(tmp_filename, std::cerr), true);
//written filled file
NEW_TMP_FILE(tmp_filename);
file.load(OPENMS_GET_TEST_DATA_PATH("ToyExample1.traML"), e);
file.store(tmp_filename, e);
TEST_EQUAL(file.isValid(tmp_filename, std::cerr), true);
}
END_SECTION
START_SECTION(bool isSemanticallyValid(const String & filename, StringList & errors, StringList & warnings))
{
std::string tmp_filename;
TraMLFile file;
StringList errors, warnings;
TargetedExperiment e;
//written empty file
NEW_TMP_FILE(tmp_filename);
file.store(tmp_filename, e);
TEST_EQUAL(file.isSemanticallyValid(tmp_filename, errors, warnings), true);
TEST_EQUAL(errors.size(), 0)
TEST_EQUAL(warnings.size(), 0)
//written filled file
NEW_TMP_FILE(tmp_filename);
file.load(OPENMS_GET_TEST_DATA_PATH("ToyExample1.traML"), e);
file.store(tmp_filename, e);
//TEST_EQUAL(file.isSemanticallyValid(tmp_filename, errors, warnings),true);
TEST_EQUAL(errors.size(), 0)
TEST_EQUAL(warnings.size(), 0)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/PeakIntegrator_test.cpp | .cpp | 44,459 | 978 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/OPENSWATH/PeakIntegrator.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
class PeakIntegratorTest : PeakIntegrator
{
public:
// make protected member public
template <typename PeakContainerConstIteratorT>
double findPosAtPeakHeightPercent(
PeakContainerConstIteratorT it_left, // must not be past the end
PeakContainerConstIteratorT it_right, // might be past the end
PeakContainerConstIteratorT it_end, // definitely past-the-end
const double peak_height,
const double percent,
const bool is_left_half)
{
return findPosAtPeakHeightPercent_(it_left, it_right, it_end, peak_height, percent, is_left_half);
}
};
START_TEST(PeakIntegrator, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PeakIntegrator* ptr = 0;
PeakIntegrator* null_ptr = 0;
const double left = 2.472833334;
const double right = 3.022891666;
// 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> position_2 = {
2270.93, 2272.86, 2273.16
};
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> intensity_2 = {
410430.0, 166125.0, 896669.0
};
const double left_past_5 = position[41]; // 2.64065
const double left_past_10 = position[42]; // 2.65125
const double left_past_50 = position[44]; // 2.672716667
const double right_past_5 = position[54]; // 2.779016667
const double right_past_10 = position[53]; // 2.768416667
const double right_past_50 = position[49]; // 2.725683333
const double left_few = position[46]; // 2.6939
const double right_few = position[48]; // 2.715083333
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 chromatogram_2;
MSSpectrum spectrum_2;
for (Size i = 0; i < position_2.size(); ++i)
{
chromatogram_2.push_back(ChromatogramPeak(position_2[i], intensity_2[i]));
spectrum_2.push_back(Peak1D(position_2[i], intensity_2[i]));
}
MSChromatogram::ConstIterator chrom_left_it = chromatogram.RTBegin(left);
MSChromatogram::ConstIterator chrom_right_it = chromatogram.RTEnd(right) - 1;
MSChromatogram::ConstIterator chrom_right_1pt_it = chromatogram.RTEnd(2.477966667) - 1;
MSChromatogram::ConstIterator chrom_right_2pt_it = chromatogram.RTEnd(2.488216667) - 1;
MSSpectrum::ConstIterator spec_left_it = spectrum.MZBegin(left);
MSSpectrum::ConstIterator spec_right_it = spectrum.MZEnd(right) - 1;
MSSpectrum::ConstIterator spec_right_1pt_it = spectrum.MZEnd(2.477966667) - 1;
MSSpectrum::ConstIterator spec_right_2pt_it = spectrum.MZEnd(2.488216667) - 1;
// To test a chromatogram with missing (5,10,50)% peak's height points
MSChromatogram::ConstIterator chrom_left_past_5_it = chromatogram.RTBegin(left_past_5);
MSChromatogram::ConstIterator chrom_right_past_5_it = chromatogram.RTEnd(right_past_5) - 1;
MSChromatogram::ConstIterator chrom_left_past_10_it = chromatogram.RTBegin(left_past_10);
MSChromatogram::ConstIterator chrom_right_past_10_it = chromatogram.RTEnd(right_past_10) - 1;
MSChromatogram::ConstIterator chrom_left_past_50_it = chromatogram.RTBegin(left_past_50);
MSChromatogram::ConstIterator chrom_right_past_50_it = chromatogram.RTEnd(right_past_50) - 1;
// To test a spectrum with missing (5,10,50)% peak's height points
MSSpectrum::ConstIterator spec_left_past_5_it = spectrum.MZBegin(left_past_5);
MSSpectrum::ConstIterator spec_right_past_5_it = spectrum.MZEnd(right_past_5) - 1;
MSSpectrum::ConstIterator spec_left_past_10_it = spectrum.MZBegin(left_past_10);
MSSpectrum::ConstIterator spec_right_past_10_it = spectrum.MZEnd(right_past_10) - 1;
MSSpectrum::ConstIterator spec_left_past_50_it = spectrum.MZBegin(left_past_50);
MSSpectrum::ConstIterator spec_right_past_50_it = spectrum.MZEnd(right_past_50) - 1;
// To test a chromatogram (and a spectrum) with few points (3 points, in this case)
MSChromatogram::ConstIterator chrom_left_few_it = chromatogram.RTBegin(left_few);
MSChromatogram::ConstIterator chrom_right_few_it = chromatogram.RTEnd(right_few) - 1;
MSSpectrum::ConstIterator spec_left_few_it = spectrum.MZBegin(left_few);
MSSpectrum::ConstIterator spec_right_few_it = spectrum.MZEnd(right_few) - 1;
constexpr const char* INTEGRATION_TYPE_INTENSITYSUM = "intensity_sum";
constexpr const char* INTEGRATION_TYPE_TRAPEZOID = "trapezoid";
constexpr const char* INTEGRATION_TYPE_SIMPSON = "simpson";
constexpr const char* BASELINE_TYPE_BASETOBASE = "base_to_base";
constexpr const char* BASELINE_TYPE_VERTICALDIVISION_MIN = "vertical_division_min";
constexpr const char* BASELINE_TYPE_VERTICALDIVISION_MAX = "vertical_division_max";
START_SECTION(PeakIntegrator())
{
ptr = new PeakIntegrator();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~PeakIntegrator())
{
delete ptr;
}
END_SECTION
ptr = new PeakIntegrator();
START_SECTION(getParameters())
{
Param params = ptr->getParameters();
TEST_EQUAL(params.getValue("integration_type"), INTEGRATION_TYPE_INTENSITYSUM)
TEST_EQUAL(params.getValue("baseline_type"), BASELINE_TYPE_BASETOBASE)
}
END_SECTION
START_SECTION(PeakBackground estimateBackground(
const MSChromatogram& chromatogram, const double left, const double right,
const double peak_apex_pos
) const)
{
Param params = ptr->getParameters();
PeakIntegrator::PeakArea pa;
PeakIntegrator::PeakBackground pb;
params.setValue("baseline_type", BASELINE_TYPE_BASETOBASE);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, left, right);
pb = ptr->estimateBackground(chromatogram, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 123446.661339019)
TEST_REAL_SIMILAR(pb.height, 1908.59690598823)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MIN);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, left, right);
pb = ptr->estimateBackground(chromatogram, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 50217)
TEST_REAL_SIMILAR(pb.height, 881)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MAX);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, left, right);
pb = ptr->estimateBackground(chromatogram, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 190095)
TEST_REAL_SIMILAR(pb.height, 3335)
params.setValue("baseline_type", BASELINE_TYPE_BASETOBASE);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, left, right);
pb = ptr->estimateBackground(chromatogram, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 1140.392865964)
TEST_REAL_SIMILAR(pb.height, 1908.59690598823)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MIN);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, left, right);
pb = ptr->estimateBackground(chromatogram, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 476.606316373)
TEST_REAL_SIMILAR(pb.height, 881)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MAX);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, left, right);
pb = ptr->estimateBackground(chromatogram, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 1804.179415555)
TEST_REAL_SIMILAR(pb.height, 3335)
}
END_SECTION
START_SECTION(PeakBackground estimateBackground(
const MSChromatogram& chromatogram, MSChromatogram::ConstIterator& left, MSChromatogram::ConstIterator& right,
const double peak_apex_pos
) const)
{
Param params = ptr->getParameters();
PeakIntegrator::PeakArea pa;
PeakIntegrator::PeakBackground pb;
params.setValue("baseline_type", BASELINE_TYPE_BASETOBASE);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it);
pb = ptr->estimateBackground(chromatogram, chrom_left_it, chrom_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 123446.661339019)
TEST_REAL_SIMILAR(pb.height, 1908.59690598823)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MIN);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it);
pb = ptr->estimateBackground(chromatogram, chrom_left_it, chrom_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 50217)
TEST_REAL_SIMILAR(pb.height, 881)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MAX);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it);
pb = ptr->estimateBackground(chromatogram, chrom_left_it, chrom_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 190095)
TEST_REAL_SIMILAR(pb.height, 3335)
params.setValue("baseline_type", BASELINE_TYPE_BASETOBASE);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it);
pb = ptr->estimateBackground(chromatogram, chrom_left_it, chrom_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 1140.392865964)
TEST_REAL_SIMILAR(pb.height, 1908.59690598823)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MIN);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it);
pb = ptr->estimateBackground(chromatogram, chrom_left_it, chrom_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 476.606316373)
TEST_REAL_SIMILAR(pb.height, 881)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MAX);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it);
pb = ptr->estimateBackground(chromatogram, chrom_left_it, chrom_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 1804.179415555)
TEST_REAL_SIMILAR(pb.height, 3335)
}
END_SECTION
START_SECTION(PeakBackground estimateBackground(
const MSSpectrum& spectrum, const double left, const double right,
const double peak_apex_pos
) const)
{
Param params = ptr->getParameters();
PeakIntegrator::PeakArea pa;
PeakIntegrator::PeakBackground pb;
params.setValue("baseline_type", BASELINE_TYPE_BASETOBASE);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, left, right);
pb = ptr->estimateBackground(spectrum, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 123446.661339019)
TEST_REAL_SIMILAR(pb.height, 1908.59690598823)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MIN);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, left, right);
pb = ptr->estimateBackground(spectrum, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 50217)
TEST_REAL_SIMILAR(pb.height, 881)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MAX);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, left, right);
pb = ptr->estimateBackground(spectrum, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 190095)
TEST_REAL_SIMILAR(pb.height, 3335)
params.setValue("baseline_type", BASELINE_TYPE_BASETOBASE);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, left, right);
pb = ptr->estimateBackground(spectrum, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 1140.392865964)
TEST_REAL_SIMILAR(pb.height, 1908.59690598823)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MIN);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, left, right);
pb = ptr->estimateBackground(spectrum, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 476.606316373)
TEST_REAL_SIMILAR(pb.height, 881)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MAX);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, left, right);
pb = ptr->estimateBackground(spectrum, left, right, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 1804.179415555)
TEST_REAL_SIMILAR(pb.height, 3335)
}
END_SECTION
START_SECTION(PeakBackground estimateBackground(
const MSSpectrum& spectrum, MSSpectrum::ConstIterator& left, MSSpectrum::ConstIterator& right,
const double peak_apex_pos
) const)
{
Param params = ptr->getParameters();
PeakIntegrator::PeakArea pa;
PeakIntegrator::PeakBackground pb;
params.setValue("baseline_type", BASELINE_TYPE_BASETOBASE);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it);
pb = ptr->estimateBackground(spectrum, spec_left_it, spec_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 123446.661339019)
TEST_REAL_SIMILAR(pb.height, 1908.59690598823)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MIN);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it);
pb = ptr->estimateBackground(spectrum, spec_left_it, spec_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 50217)
TEST_REAL_SIMILAR(pb.height, 881)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MAX);
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it);
pb = ptr->estimateBackground(spectrum, spec_left_it, spec_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 190095)
TEST_REAL_SIMILAR(pb.height, 3335)
params.setValue("baseline_type", BASELINE_TYPE_BASETOBASE);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it);
pb = ptr->estimateBackground(spectrum, spec_left_it, spec_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 1140.392865964)
TEST_REAL_SIMILAR(pb.height, 1908.59690598823)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MIN);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it);
pb = ptr->estimateBackground(spectrum, spec_left_it, spec_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 476.606316373)
TEST_REAL_SIMILAR(pb.height, 881)
params.setValue("baseline_type", BASELINE_TYPE_VERTICALDIVISION_MAX);
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it);
pb = ptr->estimateBackground(spectrum, spec_left_it, spec_right_it, pa.apex_pos);
TEST_REAL_SIMILAR(pb.area, 1804.179415555)
TEST_REAL_SIMILAR(pb.height, 3335)
}
END_SECTION
START_SECTION(PeakArea integratePeak(
const MSChromatogram& chromatogram, const double left, const double right
) const)
{
Param params = ptr->getParameters();
PeakIntegrator::PeakArea pa;
params.setValue("integration_type", INTEGRATION_TYPE_SIMPSON);
ptr->setParameters(params);
STATUS("Integration type: simpson")
pa = ptr->integratePeak(chromatogram_2, 2270.93, 2273.16);
TEST_REAL_SIMILAR(pa.area, -665788.77663627) // TO DO: Simpson rule results in negative area for strictly positive input.
}
END_SECTION
START_SECTION(PeakArea integratePeak(
const MSChromatogram& chromatogram, const double left, const double right
) const)
{
Param params = ptr->getParameters();
PeakIntegrator::PeakArea pa;
MSChromatogram::ConstIterator it;
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
STATUS("Integration type: intensity_sum")
pa = ptr->integratePeak(chromatogram, left, right);
TEST_REAL_SIMILAR(pa.area, 6768778)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = chromatogram.RTBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getRT())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
STATUS("Integration type: trapezoid")
pa = ptr->integratePeak(chromatogram, left, right);
TEST_REAL_SIMILAR(pa.area, 71540.2)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = chromatogram.RTBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getRT())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: trapezoid (1 point)")
pa = ptr->integratePeak(chromatogram, left, 2.478);
TEST_REAL_SIMILAR(pa.area, 0.0)
TEST_REAL_SIMILAR(pa.height, 881.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.477966667)
params.setValue("integration_type", INTEGRATION_TYPE_SIMPSON);
ptr->setParameters(params);
STATUS("Integration type: simpson (ODD number of points)")
pa = ptr->integratePeak(chromatogram, left, right);
TEST_REAL_SIMILAR(pa.area, 71720.443144994)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = chromatogram.RTBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getRT())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: simpson (EVEN number of points)")
pa = ptr->integratePeak(chromatogram, left, 3.011416667); // a lower value of "right" is passed, to have 1 less point
TEST_REAL_SIMILAR(pa.area, 71515.0792609335)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = chromatogram.RTBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getRT())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: simpson (1 point)")
pa = ptr->integratePeak(chromatogram, left, 2.478);
TEST_REAL_SIMILAR(pa.area, 0.0)
TEST_REAL_SIMILAR(pa.height, 881.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.477966667)
STATUS("Integration type: simpson (2 points)")
pa = ptr->integratePeak(chromatogram, left, 2.489);
TEST_REAL_SIMILAR(pa.area, 11.6081250000001)
TEST_REAL_SIMILAR(pa.height, 1384)
TEST_REAL_SIMILAR(pa.apex_pos, 2.488216667)
}
END_SECTION
START_SECTION(PeakArea integratePeak(
const MSChromatogram& chromatogram, MSChromatogram::ConstIterator& left, MSChromatogram::ConstIterator& right
) const)
{
Param params = ptr->getParameters();
PeakIntegrator::PeakArea pa;
MSChromatogram::ConstIterator it;
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
STATUS("Integration type: intensity_sum")
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it);
TEST_REAL_SIMILAR(pa.area, 6768778)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = chromatogram.RTBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getRT())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
STATUS("Integration type: trapezoid")
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it);
TEST_REAL_SIMILAR(pa.area, 71540.2)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = chromatogram.RTBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getRT())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: trapezoid (1 point)")
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_1pt_it);
TEST_REAL_SIMILAR(pa.area, 0.0)
TEST_REAL_SIMILAR(pa.height, 881.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.477966667)
params.setValue("integration_type", INTEGRATION_TYPE_SIMPSON);
ptr->setParameters(params);
STATUS("Integration type: simpson (ODD number of points)")
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it);
TEST_REAL_SIMILAR(pa.area, 71720.443144994)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = chromatogram.RTBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getRT())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: simpson (EVEN number of points)")
MSChromatogram::ConstIterator chrom_right_it_less = chrom_right_it - 1;
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it_less); // a lower value of "right" is passed, to have 1 less point
TEST_REAL_SIMILAR(pa.area, 71515.0792609335)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = chromatogram.RTBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getRT())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: simpson (1 point)")
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_1pt_it);
TEST_REAL_SIMILAR(pa.area, 0.0)
TEST_REAL_SIMILAR(pa.height, 881.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.477966667)
STATUS("Integration type: simpson (2 points)")
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_2pt_it);
TEST_REAL_SIMILAR(pa.area, 11.6081250000001)
TEST_REAL_SIMILAR(pa.height, 1384)
TEST_REAL_SIMILAR(pa.apex_pos, 2.488216667)
}
END_SECTION
START_SECTION(PeakArea integratePeak(
const MSSpectrum& spectrum, const double left, const double right
) const)
{
Param params = ptr->getParameters();
PeakIntegrator::PeakArea pa;
MSSpectrum::ConstIterator it;
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
STATUS("Integration type: intensity_sum")
pa = ptr->integratePeak(spectrum, left, right);
TEST_REAL_SIMILAR(pa.area, 6768778)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = spectrum.MZBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getMZ())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
STATUS("Integration type: trapezoid")
pa = ptr->integratePeak(spectrum, left, right);
TEST_REAL_SIMILAR(pa.area, 71540.2)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = spectrum.MZBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getMZ())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: trapezoid (1 point)")
pa = ptr->integratePeak(spectrum, left, 2.478);
TEST_REAL_SIMILAR(pa.area, 0.0)
TEST_REAL_SIMILAR(pa.height, 881.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.477966667)
params.setValue("integration_type", INTEGRATION_TYPE_SIMPSON);
ptr->setParameters(params);
STATUS("Integration type: simpson (ODD number of points)")
pa = ptr->integratePeak(spectrum, left, right);
TEST_REAL_SIMILAR(pa.area, 71720.443144994)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = spectrum.MZBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getMZ())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: simpson (EVEN number of points)")
pa = ptr->integratePeak(spectrum, left, 3.011416667); // a lower value of "right" is passed, to have 1 less point
TEST_REAL_SIMILAR(pa.area, 71515.0792609335)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = spectrum.MZBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getMZ())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: simpson (1 point)")
pa = ptr->integratePeak(spectrum, left, 2.478);
TEST_REAL_SIMILAR(pa.area, 0.0)
TEST_REAL_SIMILAR(pa.height, 881.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.477966667)
STATUS("Integration type: simpson (2 points)")
pa = ptr->integratePeak(spectrum, left, 2.489);
TEST_REAL_SIMILAR(pa.area, 11.6081250000001)
TEST_REAL_SIMILAR(pa.height, 1384)
TEST_REAL_SIMILAR(pa.apex_pos, 2.488216667)
}
END_SECTION
START_SECTION(PeakArea integratePeak(
const MSSpectrum& spectrum, MSSpectrum::ConstIterator& left, MSSpectrum::ConstIterator& right
) const)
{
Param params = ptr->getParameters();
PeakIntegrator::PeakArea pa;
MSSpectrum::ConstIterator it;
params.setValue("integration_type", INTEGRATION_TYPE_INTENSITYSUM);
ptr->setParameters(params);
STATUS("Integration type: intensity_sum")
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it);
TEST_REAL_SIMILAR(pa.area, 6768778)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = spectrum.MZBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getMZ())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
params.setValue("integration_type", INTEGRATION_TYPE_TRAPEZOID);
ptr->setParameters(params);
STATUS("Integration type: trapezoid")
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it);
TEST_REAL_SIMILAR(pa.area, 71540.2)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = spectrum.MZBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getMZ())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: trapezoid (1 point)")
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_1pt_it);
TEST_REAL_SIMILAR(pa.area, 0.0)
TEST_REAL_SIMILAR(pa.height, 881.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.477966667)
params.setValue("integration_type", INTEGRATION_TYPE_SIMPSON);
ptr->setParameters(params);
STATUS("Integration type: simpson (ODD number of points)")
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it);
TEST_REAL_SIMILAR(pa.area, 71720.443144994)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = spectrum.MZBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getMZ())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: simpson (EVEN number of points)")
MSSpectrum::ConstIterator spec_right_it_less = spec_right_it - 1;
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it_less); // a lower value of "right" is passed, to have 1 less point
TEST_REAL_SIMILAR(pa.area, 71515.0792609335)
TEST_REAL_SIMILAR(pa.height, 966489.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.7045)
it = spectrum.MZBegin(left);
for (Size i = 0; i < pa.hull_points.size(); i += 4, it +=4)
{
TEST_REAL_SIMILAR(pa.hull_points[i][0], it->getMZ())
TEST_REAL_SIMILAR(pa.hull_points[i][1], it->getIntensity())
}
STATUS("Integration type: simpson (1 point)")
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_1pt_it);
TEST_REAL_SIMILAR(pa.area, 0.0)
TEST_REAL_SIMILAR(pa.height, 881.0)
TEST_REAL_SIMILAR(pa.apex_pos, 2.477966667)
STATUS("Integration type: simpson (2 points)")
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_2pt_it);
TEST_REAL_SIMILAR(pa.area, 11.6081250000001)
TEST_REAL_SIMILAR(pa.height, 1384)
TEST_REAL_SIMILAR(pa.apex_pos, 2.488216667)
}
END_SECTION
START_SECTION(PeakShapeMetrics calculatePeakShapeMetrics(
const MSChromatogram& chromatogram, const double left, const double right,
const double peak_height, const double peak_apex_pos
) const)
{
PeakIntegrator::PeakArea pa;
PeakIntegrator::PeakShapeMetrics psm;
pa = ptr->integratePeak(chromatogram, left, right);
psm = ptr->calculatePeakShapeMetrics(chromatogram, left, right, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.width_at_5, 0.15955)
TEST_REAL_SIMILAR(psm.width_at_10, 0.138366667)
TEST_REAL_SIMILAR(psm.width_at_50, 0.0741500000000004)
TEST_REAL_SIMILAR(psm.start_position_at_5, 2.630066667)
TEST_REAL_SIMILAR(psm.start_position_at_10, 2.64065)
TEST_REAL_SIMILAR(psm.start_position_at_50, 2.662116667)
TEST_REAL_SIMILAR(psm.end_position_at_5, 2.789616667)
TEST_REAL_SIMILAR(psm.end_position_at_10, 2.779016667)
TEST_REAL_SIMILAR(psm.end_position_at_50, 2.736266667)
TEST_REAL_SIMILAR(psm.total_width, 0.540983333)
TEST_REAL_SIMILAR(psm.tailing_factor, 1.07176444725376)
TEST_REAL_SIMILAR(psm.asymmetry_factor, 1.16705821456539)
TEST_REAL_SIMILAR(psm.slope_of_baseline, 2454)
TEST_REAL_SIMILAR(psm.baseline_delta_2_height, 0.00253908735640033)
TEST_EQUAL(psm.points_across_baseline, 57)
TEST_EQUAL(psm.points_across_half_height, 6)
pa = ptr->integratePeak(chromatogram, left_past_5, right_past_5);
psm = ptr->calculatePeakShapeMetrics(chromatogram, left_past_5, right_past_5, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_5)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_5)
pa = ptr->integratePeak(chromatogram, left_past_10, right_past_10);
psm = ptr->calculatePeakShapeMetrics(chromatogram, left_past_10, right_past_10, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_10)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_10)
TEST_REAL_SIMILAR(psm.start_position_at_10, left_past_10)
TEST_REAL_SIMILAR(psm.end_position_at_10, right_past_10)
pa = ptr->integratePeak(chromatogram, left_past_50, right_past_50);
psm = ptr->calculatePeakShapeMetrics(chromatogram, left_past_50, right_past_50, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_50)
TEST_REAL_SIMILAR(psm.start_position_at_10, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_10, right_past_50)
TEST_REAL_SIMILAR(psm.start_position_at_50, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_50, right_past_50)
pa = ptr->integratePeak(chromatogram, left_few, right_few);
psm = ptr->calculatePeakShapeMetrics(chromatogram, left_few, right_few, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_few)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_few)
}
END_SECTION
START_SECTION(PeakShapeMetrics calculatePeakShapeMetrics(
const MSChromatogram& chromatogram, MSChromatogram::ConstIterator& left, MSChromatogram::ConstIterator& right,
const double peak_height, const double peak_apex_pos
) const)
{
PeakIntegrator::PeakArea pa;
PeakIntegrator::PeakShapeMetrics psm;
pa = ptr->integratePeak(chromatogram, chrom_left_it, chrom_right_it);
psm = ptr->calculatePeakShapeMetrics(chromatogram, chrom_left_it, chrom_right_it, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.width_at_5, 0.15955)
TEST_REAL_SIMILAR(psm.width_at_10, 0.138366667)
TEST_REAL_SIMILAR(psm.width_at_50, 0.0741500000000004)
TEST_REAL_SIMILAR(psm.start_position_at_5, 2.630066667)
TEST_REAL_SIMILAR(psm.start_position_at_10, 2.64065)
TEST_REAL_SIMILAR(psm.start_position_at_50, 2.662116667)
TEST_REAL_SIMILAR(psm.end_position_at_5, 2.789616667)
TEST_REAL_SIMILAR(psm.end_position_at_10, 2.779016667)
TEST_REAL_SIMILAR(psm.end_position_at_50, 2.736266667)
TEST_REAL_SIMILAR(psm.total_width, 0.540983333)
TEST_REAL_SIMILAR(psm.tailing_factor, 1.07176444725376)
TEST_REAL_SIMILAR(psm.asymmetry_factor, 1.16705821456539)
TEST_REAL_SIMILAR(psm.slope_of_baseline, 2454)
TEST_REAL_SIMILAR(psm.baseline_delta_2_height, 0.00253908735640033)
TEST_EQUAL(psm.points_across_baseline, 57)
TEST_EQUAL(psm.points_across_half_height, 6)
pa = ptr->integratePeak(chromatogram, chrom_left_past_5_it, chrom_right_past_5_it);
psm = ptr->calculatePeakShapeMetrics(chromatogram, chrom_left_past_5_it, chrom_right_past_5_it, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_5)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_5)
pa = ptr->integratePeak(chromatogram, chrom_left_past_10_it, chrom_right_past_10_it);
psm = ptr->calculatePeakShapeMetrics(chromatogram, chrom_left_past_10_it, chrom_right_past_10_it, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_10)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_10)
TEST_REAL_SIMILAR(psm.start_position_at_10, left_past_10)
TEST_REAL_SIMILAR(psm.end_position_at_10, right_past_10)
pa = ptr->integratePeak(chromatogram, chrom_left_past_50_it, chrom_right_past_50_it);
psm = ptr->calculatePeakShapeMetrics(chromatogram, chrom_left_past_50_it, chrom_right_past_50_it, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_50)
TEST_REAL_SIMILAR(psm.start_position_at_10, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_10, right_past_50)
TEST_REAL_SIMILAR(psm.start_position_at_50, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_50, right_past_50)
pa = ptr->integratePeak(chromatogram, chrom_left_few_it, chrom_right_few_it);
psm = ptr->calculatePeakShapeMetrics(chromatogram, chrom_left_few_it, chrom_right_few_it, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_few)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_few)
}
END_SECTION
START_SECTION(PeakShapeMetrics calculatePeakShapeMetrics(
const MSSpectrum& spectrum, const double left, const double right,
const double peak_height, const double peak_apex_pos
) const)
{
PeakIntegrator::PeakArea pa;
PeakIntegrator::PeakShapeMetrics psm;
pa = ptr->integratePeak(spectrum, left, right);
psm = ptr->calculatePeakShapeMetrics(spectrum, left, right, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.width_at_5, 0.15955)
TEST_REAL_SIMILAR(psm.width_at_10, 0.138366667)
TEST_REAL_SIMILAR(psm.width_at_50, 0.0741500000000004)
TEST_REAL_SIMILAR(psm.start_position_at_5, 2.630066667)
TEST_REAL_SIMILAR(psm.start_position_at_10, 2.64065)
TEST_REAL_SIMILAR(psm.start_position_at_50, 2.662116667)
TEST_REAL_SIMILAR(psm.end_position_at_5, 2.789616667)
TEST_REAL_SIMILAR(psm.end_position_at_10, 2.779016667)
TEST_REAL_SIMILAR(psm.end_position_at_50, 2.736266667)
TEST_REAL_SIMILAR(psm.total_width, 0.540983333)
TEST_REAL_SIMILAR(psm.tailing_factor, 1.07176444725376)
TEST_REAL_SIMILAR(psm.asymmetry_factor, 1.16705821456539)
TEST_REAL_SIMILAR(psm.slope_of_baseline, 2454)
TEST_REAL_SIMILAR(psm.baseline_delta_2_height, 0.00253908735640033)
TEST_EQUAL(psm.points_across_baseline, 57)
TEST_EQUAL(psm.points_across_half_height, 6)
pa = ptr->integratePeak(spectrum, left_past_5, right_past_5);
psm = ptr->calculatePeakShapeMetrics(spectrum, left_past_5, right_past_5, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_5)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_5)
pa = ptr->integratePeak(spectrum, left_past_10, right_past_10);
psm = ptr->calculatePeakShapeMetrics(spectrum, left_past_10, right_past_10, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_10)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_10)
TEST_REAL_SIMILAR(psm.start_position_at_10, left_past_10)
TEST_REAL_SIMILAR(psm.end_position_at_10, right_past_10)
pa = ptr->integratePeak(spectrum, left_past_50, right_past_50);
psm = ptr->calculatePeakShapeMetrics(spectrum, left_past_50, right_past_50, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_50)
TEST_REAL_SIMILAR(psm.start_position_at_10, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_10, right_past_50)
TEST_REAL_SIMILAR(psm.start_position_at_50, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_50, right_past_50)
pa = ptr->integratePeak(spectrum, left_few, right_few);
psm = ptr->calculatePeakShapeMetrics(spectrum, left_few, right_few, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_few)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_few)
}
END_SECTION
START_SECTION(PeakShapeMetrics calculatePeakShapeMetrics(
const MSSpectrum& spectrum, MSSpectrum::ConstIterator& left, MSSpectrum::ConstIterator& right,
const double peak_height, const double peak_apex_pos
) const)
{
PeakIntegrator::PeakArea pa;
PeakIntegrator::PeakShapeMetrics psm;
pa = ptr->integratePeak(spectrum, spec_left_it, spec_right_it);
psm = ptr->calculatePeakShapeMetrics(spectrum, spec_left_it, spec_right_it, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.width_at_5, 0.15955)
TEST_REAL_SIMILAR(psm.width_at_10, 0.138366667)
TEST_REAL_SIMILAR(psm.width_at_50, 0.0741500000000004)
TEST_REAL_SIMILAR(psm.start_position_at_5, 2.630066667)
TEST_REAL_SIMILAR(psm.start_position_at_10, 2.64065)
TEST_REAL_SIMILAR(psm.start_position_at_50, 2.662116667)
TEST_REAL_SIMILAR(psm.end_position_at_5, 2.789616667)
TEST_REAL_SIMILAR(psm.end_position_at_10, 2.779016667)
TEST_REAL_SIMILAR(psm.end_position_at_50, 2.736266667)
TEST_REAL_SIMILAR(psm.total_width, 0.540983333)
TEST_REAL_SIMILAR(psm.tailing_factor, 1.07176444725376)
TEST_REAL_SIMILAR(psm.asymmetry_factor, 1.16705821456539)
TEST_REAL_SIMILAR(psm.slope_of_baseline, 2454)
TEST_REAL_SIMILAR(psm.baseline_delta_2_height, 0.00253908735640033)
TEST_EQUAL(psm.points_across_baseline, 57)
TEST_EQUAL(psm.points_across_half_height, 6)
pa = ptr->integratePeak(spectrum, spec_left_past_5_it, spec_right_past_5_it);
psm = ptr->calculatePeakShapeMetrics(spectrum, spec_left_past_5_it, spec_right_past_5_it, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_5)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_5)
pa = ptr->integratePeak(spectrum, spec_left_past_10_it, spec_right_past_10_it);
psm = ptr->calculatePeakShapeMetrics(spectrum, spec_left_past_10_it, spec_right_past_10_it, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_10)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_10)
TEST_REAL_SIMILAR(psm.start_position_at_10, left_past_10)
TEST_REAL_SIMILAR(psm.end_position_at_10, right_past_10)
pa = ptr->integratePeak(spectrum, spec_left_past_50_it, spec_right_past_50_it);
psm = ptr->calculatePeakShapeMetrics(spectrum, spec_left_past_50_it, spec_right_past_50_it, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_past_50)
TEST_REAL_SIMILAR(psm.start_position_at_10, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_10, right_past_50)
TEST_REAL_SIMILAR(psm.start_position_at_50, left_past_50)
TEST_REAL_SIMILAR(psm.end_position_at_50, right_past_50)
pa = ptr->integratePeak(spectrum, spec_left_few_it, spec_right_few_it);
psm = ptr->calculatePeakShapeMetrics(spectrum, spec_left_few_it, spec_right_few_it, pa.height, pa.apex_pos);
TEST_REAL_SIMILAR(psm.start_position_at_5, left_few)
TEST_REAL_SIMILAR(psm.end_position_at_5, right_few)
}
END_SECTION
START_SECTION([EXTRA] template <typename PeakContainerConstIteratorT> double findPosAtPeakHeightPercent_(...))
{
PeakIntegratorTest pit;
double pos = pit.findPosAtPeakHeightPercent(spectrum.begin(), spectrum.end(), spectrum.end(), 0.0, 0.0, true);
TEST_EQUAL(pos, spectrum[0].getPos()); // find first non-zero peak
pos = pit.findPosAtPeakHeightPercent(spectrum.begin(), spectrum.end(), spectrum.end(), 0.0, 0.0, false);
TEST_EQUAL(pos, spectrum.back().getPos()); // find non-zero peak from end
// corner cases: just a single point in range
pos = pit.findPosAtPeakHeightPercent(spectrum.begin(), spectrum.begin() + 1, spectrum.begin() + 1, 0.0, 0.0, false);
TEST_EQUAL(pos, spectrum[0].getPos()); // return the only peak there is
pos = pit.findPosAtPeakHeightPercent(spectrum.begin(), spectrum.begin() + 1, spectrum.begin() + 1, 0.0, 0.0, true);
TEST_EQUAL(pos, spectrum[0].getPos()); // return the only peak there is
// corner cases: empty range
TEST_EXCEPTION(Exception::InvalidRange, pit.findPosAtPeakHeightPercent(spectrum.end(), spectrum.end(), spectrum.end(), 0.0, 0.0, false))
TEST_EXCEPTION(Exception::InvalidRange, pit.findPosAtPeakHeightPercent(spectrum.end(), spectrum.end(), spectrum.end(), 0.0, 0.0, true))
}
END_SECTION
delete ptr;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ConsensusIDAlgorithmPEPMatrix_test.cpp | .cpp | 1,361 | 51 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Marc Sturm, Andreas Bertsch, Sven Nahnsen, Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmPEPMatrix.h>
#include <iostream>//wieder rausnehmen
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(ConsensusIDAlgorithmPEPMatrix, "$Id$")
/////////////////////////////////////////////////////////////
ConsensusIDAlgorithm* ptr = nullptr;
ConsensusIDAlgorithm* null_pointer = nullptr;
START_SECTION(ConsensusIDAlgorithmPEPMatrix())
{
ptr = new ConsensusIDAlgorithmPEPMatrix();
TEST_NOT_EQUAL(ptr, null_pointer);
}
END_SECTION
START_SECTION(~ConsensusIDAlgorithmPEPMatrix())
{
delete(ptr);
}
END_SECTION
START_SECTION(void apply(PeptideIdentificationList& ids))
{
NOT_TESTABLE // tested by ConsensusID TOPP tool tests
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/DefaultParamHandler_test.cpp | .cpp | 5,731 | 197 | // 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/DefaultParamHandler.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
///////////////////////////
START_TEST(DefaultParamHandler, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
class TestHandler
: public DefaultParamHandler
{
public:
explicit TestHandler(const String& name)
: DefaultParamHandler(name)
{
defaults_.setValue("int",0,"intdesc");
defaults_.setValue("string","default","stingdesc");
subsections_.push_back("ignore");
defaultsToParam_();
}
TestHandler(const TestHandler& rhs)
: DefaultParamHandler(rhs),
string_var(rhs.string_var)
{
updateMembers_();
}
TestHandler& operator= (const TestHandler& rhs)
{
if (&rhs == this) return *this;
DefaultParamHandler::operator=(rhs);
string_var = rhs.string_var;
updateMembers_();
return *this;
}
void updateMembers_() override
{
string_var = (string)(param_.getValue("string"));
}
String string_var;
};
DefaultParamHandler* ptr = nullptr;
DefaultParamHandler* nullPointer = nullptr;
START_SECTION((DefaultParamHandler(const String& name)))
ptr = new DefaultParamHandler("dummy");
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~DefaultParamHandler()))
delete ptr;
END_SECTION
START_SECTION((const String& getName() const))
DefaultParamHandler s("dummy2");
TEST_EQUAL(s.getName(), "dummy2")
END_SECTION
START_SECTION((void setName(const String& name)))
DefaultParamHandler s("dummy2");
s.setName("SetName");
TEST_EQUAL(s.getName(), "SetName")
END_SECTION
START_SECTION((const std::vector<String>& getSubsections() const))
DefaultParamHandler s("dummy2");
TEST_EQUAL(s.getSubsections().size(),0)
END_SECTION
START_SECTION((const Param& getDefaults() const))
DefaultParamHandler s("dummy2");
TEST_EQUAL(s.getDefaults().size(),0)
TestHandler t("dummy2");
TEST_EQUAL(t.getDefaults().size(),2)
END_SECTION
START_SECTION((const Param& getParameters() const))
TestHandler s("dummy");
Param empty;
TEST_EQUAL(s.getParameters().size(),2)
TEST_EQUAL((int)(s.getParameters().getValue("int")),0)
TEST_EQUAL((string)(s.getParameters().getValue("string")),"default")
TEST_EQUAL(s.string_var, "default")
END_SECTION
START_SECTION((void setParameters(const Param ¶m)))
Param p;
p.setValue("int",1);
p.setValue("string","test");
p.setValue("ignore:bli",4711);
TestHandler s("dummy");
s.setParameters(p);
TEST_EQUAL((int)(s.getParameters().getValue("int")), 1)
TEST_EQUAL((string)(s.getParameters().getValue("string")), "test")
TEST_EQUAL(s.string_var, "test")
END_SECTION
START_SECTION((bool operator == (const DefaultParamHandler& rhs) const))
TestHandler empty("dummy");
TestHandler h("dummy");
TEST_EQUAL(empty==h,true);
Param p;
p.setValue("int",1);
h.setParameters(p);
TEST_EQUAL(empty==h,false);
END_SECTION
START_SECTION((DefaultParamHandler & operator=(const DefaultParamHandler &rhs)))
Param p;
p.setValue("int",1);
p.setValue("string","test");
p.setValue("ignore:bli",4711);
TestHandler s("dummy");
s.setParameters(p);
TestHandler s2("dummy2");
s2 = s;
TEST_EQUAL((int)(s2.getParameters().getValue("int")), 1)
TEST_EQUAL((string)(s2.getParameters().getValue("string")), "test")
TEST_EQUAL(s2.string_var, "test")
s2 = TestHandler("dummy");
TEST_EQUAL(s2==TestHandler("dummy"),true)
END_SECTION
START_SECTION((DefaultParamHandler(const DefaultParamHandler &rhs)))
Param p;
p.setValue("int",1);
p.setValue("string","test");
p.setValue("ignore:bli",4711);
TestHandler s("dummy");
s.setParameters(p);
TestHandler s2(s);
TEST_EQUAL((int)(s2.getParameters().getValue("int")), 1)
TEST_EQUAL((string)(s2.getParameters().getValue("string")), "test")
TEST_EQUAL(s2.string_var, "test")
END_SECTION
START_SECTION(static void writeParametersToMetaValues(const Param& write_this, MetaInfoInterface& write_here, const String& prefix = ""))
MetaInfoInterface meta_values;
Param p;
p.setValue("int", 1);
p.setValue("string", "test");
p.setValue("ignore:bli", 4711);
DefaultParamHandler::writeParametersToMetaValues(p, meta_values);
DefaultParamHandler::writeParametersToMetaValues(p, meta_values, "prefix");
ABORT_IF(!meta_values.metaValueExists("int"))
ABORT_IF(!meta_values.metaValueExists("string"))
ABORT_IF(!meta_values.metaValueExists("bli"))
TEST_EQUAL(meta_values.getMetaValue("int"), 1)
TEST_EQUAL(meta_values.getMetaValue("string"), "test")
TEST_EQUAL(meta_values.getMetaValue("bli"), 4711)
ABORT_IF(!meta_values.metaValueExists("prefix:int"))
ABORT_IF(!meta_values.metaValueExists("prefix:string"))
ABORT_IF(!meta_values.metaValueExists("prefix:bli"))
TEST_EQUAL(meta_values.getMetaValue("prefix:int"), 1)
TEST_EQUAL(meta_values.getMetaValue("prefix:string"), "test")
TEST_EQUAL(meta_values.getMetaValue("prefix:bli"), 4711)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MapAlignmentAlgorithmPoseClustering_test.cpp | .cpp | 2,937 | 89 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Eva Lange, Clemens Groepl $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentAlgorithmPoseClustering.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLinear.h>
#include <OpenMS/FORMAT/MzMLFile.h>
using namespace std;
using namespace OpenMS;
/////////////////////////////////////////////////////////////
START_TEST(MapAlignmentAlgorithmPoseClustering, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MapAlignmentAlgorithmPoseClustering* ptr = nullptr;
MapAlignmentAlgorithmPoseClustering* nullPointer = nullptr;
START_SECTION((MapAlignmentAlgorithmPoseClustering()))
ptr = new MapAlignmentAlgorithmPoseClustering();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((virtual ~MapAlignmentAlgorithmPoseClustering()))
delete ptr;
END_SECTION
START_SECTION((template <typename MapType> void setReference(const MapType& map)))
{
NOT_TESTABLE // tested together with "align"
}
END_SECTION
START_SECTION((void align(const PeakMap& map, TransformationDescription& trafo)))
{
MzMLFile f;
std::vector<PeakMap > maps(2);
f.load(OPENMS_GET_TEST_DATA_PATH("MapAlignmentAlgorithmPoseClustering_in1.mzML.gz"), maps[0]);
f.load(OPENMS_GET_TEST_DATA_PATH("MapAlignmentAlgorithmPoseClustering_in2.mzML.gz"), maps[1]);
MapAlignmentAlgorithmPoseClustering aligner;
aligner.setReference(maps[0]);
TransformationDescription trafo;
aligner.align(maps[1], trafo);
TEST_EQUAL(trafo.getModelType(), "linear");
TEST_EQUAL(trafo.getDataPoints().size(), 307);
// @TODO: can we get the slope/intercept without fitting a model again?
TransformationModelLinear lm(trafo.getDataPoints(),
trafo.getModelParameters());
double slope, intercept;
String x_weight, y_weight;
double x_datum_min, x_datum_max, y_datum_min, y_datum_max;
lm.getParameters(slope, intercept, x_weight, y_weight, x_datum_min, x_datum_max, y_datum_min, y_datum_max);
TEST_REAL_SIMILAR(slope, 1.01164);
TEST_REAL_SIMILAR(intercept, -32.0912);
}
END_SECTION
START_SECTION((void align(const FeatureMap& map, TransformationDescription& trafo)))
{
// Tested extensively in TEST/TOPP
NOT_TESTABLE;
}
END_SECTION
START_SECTION((void align(const ConsensusMap& map, TransformationDescription& trafo)))
{
// Tested extensively in TEST/TOPP
NOT_TESTABLE;
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/FeatureDistance_test.cpp | .cpp | 5,987 | 182 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser
// $Authors: Clemens Groepl, Hendrik Weisser, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/MAPMATCHING/FeatureDistance.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/CONCEPT/Constants.h>
///////////////////////////
START_TEST(FeatureDistance, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
FeatureDistance* d_ptr = nullptr;
FeatureDistance* d_nullPointer = nullptr;
START_SECTION((FeatureDistance(double max_intensity=1.0, bool force_constraints=false)))
{
d_ptr = new FeatureDistance();
TEST_NOT_EQUAL(d_ptr, d_nullPointer);
}
END_SECTION
START_SECTION((~FeatureDistance()))
{
delete d_ptr;
}
END_SECTION
START_SECTION((std::pair<bool, double> operator()(const BaseFeature& left, const BaseFeature& right)))
{
FeatureDistance dist(1000.0, false);
Param param = dist.getDefaults();
param.setValue("distance_RT:max_difference", 100.0);
param.setValue("distance_MZ:max_difference", 1.0);
param.setValue("distance_MZ:exponent", 1.0);
param.setValue("distance_intensity:weight", 1.0);
dist.setParameters(param);
BaseFeature left, right;
left.setRT(100.0);
left.setMZ(100.0);
left.setIntensity(100.0);
// all distance components vary by 10% of the maximum:
right.setRT(110.0);
right.setMZ(100.1);
right.setIntensity(200.0);
pair<bool, double> result = dist(left, right);
TEST_EQUAL(result.first, true);
TEST_REAL_SIMILAR(result.second, 0.1);
// no differences:
result = dist(left, left);
TEST_EQUAL(result.first, true);
TEST_REAL_SIMILAR(result.second, 0.0);
// differences at maximum:
right.setRT(200.0);
right.setMZ(101.0);
right.setIntensity(1000.0);
left.setIntensity(0.0);
result = dist(left, right);
TEST_EQUAL(result.first, true);
TEST_REAL_SIMILAR(result.second, 1.0);
// differences beyond maximum:
right.setRT(300.0);
result = dist(left, right);
TEST_EQUAL(result.first, false);
TEST_REAL_SIMILAR(result.second, 1.33333333);
FeatureDistance dist2(1000.0, true);
result = dist2(left, right);
TEST_EQUAL(result.first, false);
TEST_EQUAL(result.second, FeatureDistance::infinity);
// ppm for m/z
param.setValue("distance_intensity:weight", 0.0);
param.setValue("distance_RT:weight", 0.0);
param.setValue("distance_MZ:weight", 1.0);
param.setValue("distance_MZ:max_difference", 10.0);
param.setValue("distance_MZ:unit", "ppm");
dist.setParameters(param);
left.setRT(100.0);
left.setIntensity(100.0);
left.setMZ(100.0);
right.setRT(110.0);
right.setIntensity(200.0);
right.setMZ(100.0 + 100.0/1e6 * 5); // 5ppm off
result = dist(left, right);
TEST_EQUAL(result.first, true);
TEST_REAL_SIMILAR(result.second, 0.5);
right.setMZ(100.0 + 100.0/1e6 * 20); // 20ppm off
result = dist(left, right);
TEST_EQUAL(result.first, false);
TEST_REAL_SIMILAR(result.second, 2);
// charge
param.setValue("ignore_charge", "false");
dist.setParameters(param);
right.setMZ(100.0 + 100.0/1e6 * 5); // 5ppm off --> valid in m/z
// charges differ
right.setCharge(1);
left.setCharge(2);
result = dist(left, right);
TEST_EQUAL(result.first, false); // --> invalid
TEST_REAL_SIMILAR(result.second, FeatureDistance::infinity);
// one charge 0 -- pass filter
right.setCharge(1);
left.setCharge(0);
result = dist(left, right);
TEST_EQUAL(result.first, true); // --> valid
TEST_REAL_SIMILAR(result.second, 0.5);
// ignore charge
param.setValue("ignore_charge", "true");
dist.setParameters(param);
// charges differ, but we don't care
right.setCharge(1);
left.setCharge(2);
result = dist(left, right);
TEST_EQUAL(result.first, true); // --> valid
TEST_REAL_SIMILAR(result.second, 0.5);
// adduct
param.setValue("ignore_adduct", "false");
dist.setParameters(param);
right.setMZ(100.0 + 100.0/1e6 * 5); // 5ppm off --> valid in m/z
// only one adduct set
right.setMetaValue(Constants::UserParam::DC_CHARGE_ADDUCTS, "NH4");
result = dist(left, right);
TEST_EQUAL(result.first, true); // --> valid
TEST_REAL_SIMILAR(result.second, 0.5);
//both set with adducts having same element composition (even if string different ordered)
left.setMetaValue(Constants::UserParam::DC_CHARGE_ADDUCTS, "H4N");
result = dist(left, right);
TEST_EQUAL(result.first, true); // --> valid
TEST_REAL_SIMILAR(result.second, 0.5);
//one different adduct
left.setMetaValue(Constants::UserParam::DC_CHARGE_ADDUCTS, "H5N");
result = dist(left, right);
TEST_EQUAL(result.first, false); // --> invalid
TEST_REAL_SIMILAR(result.second, FeatureDistance::infinity);
// ignore adduct
param.setValue("ignore_adduct", "true");
dist.setParameters(param);
// adducts differ, but we don't care
result = dist(left, right);
TEST_EQUAL(result.first, true); // --> valid
TEST_REAL_SIMILAR(result.second, 0.5);
}
END_SECTION
START_SECTION((FeatureDistance& operator=(const FeatureDistance& other)))
{
FeatureDistance dist(1000.0, true);
Param param = dist.getDefaults();
param.setValue("distance_RT:max_difference", 100.0);
param.setValue("distance_MZ:max_difference", 1.0);
param.setValue("distance_MZ:exponent", 1.0);
param.setValue("distance_intensity:weight", 1.0);
dist.setParameters(param);
FeatureDistance dist2;
dist2 = dist;
TEST_EQUAL(dist.getParameters(), dist2.getParameters());
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/FalseDiscoveryRate_test.cpp | .cpp | 9,506 | 297 | // 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 $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
///////////////////////////
#include <OpenMS/ANALYSIS/ID/FalseDiscoveryRate.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(FalseDiscoveryRate, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
FalseDiscoveryRate* ptr = nullptr;
FalseDiscoveryRate* nullPointer = nullptr;
START_SECTION(FalseDiscoveryRate())
{
ptr = new FalseDiscoveryRate();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~FalseDiscoveryRate())
{
delete ptr;
}
END_SECTION
START_SECTION((void apply(PeptideIdentificationList &fwd_ids, PeptideIdentificationList &rev_ids)))
{
ptr = new FalseDiscoveryRate();
vector<ProteinIdentification> fwd_prot_ids, rev_prot_ids;
PeptideIdentificationList fwd_pep_ids, rev_pep_ids;
String document_id;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("XTandem_fwd_ids.idXML"), fwd_prot_ids, fwd_pep_ids, document_id);
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("XTandem_rev_ids.idXML"), rev_prot_ids, rev_pep_ids, document_id);
ptr->apply(fwd_pep_ids, rev_pep_ids);
TOLERANCE_ABSOLUTE(0.0001)
for (PeptideIdentificationList::const_iterator it = fwd_pep_ids.begin(); it != fwd_pep_ids.end(); ++it)
{
if (!it->getHits().empty())
{
PeptideHit hit(*it->getHits().begin());
double fdr(hit.getScore());
double orig_score((double)hit.getMetaValue("XTandem_score"));
if (orig_score >= 39.4)
{
TEST_REAL_SIMILAR(fdr, 0)
}
if (orig_score <= 37.9 + 0.0001 && orig_score >= 37.9 - 0.0001)
{
TEST_REAL_SIMILAR(fdr, 0.08)
}
}
}
}
END_SECTION
START_SECTION((void apply(std::vector<ProteinIdentification> &fwd_ids, std::vector<ProteinIdentification> &rev_ids)))
{
vector<ProteinIdentification> fwd_prot_ids, rev_prot_ids;
PeptideIdentificationList fwd_pep_ids, rev_pep_ids;
String document_id;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("XTandem_fwd_ids_withProtScores.idXML"), fwd_prot_ids, fwd_pep_ids, document_id);
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("XTandem_rev_ids_withProtScores.idXML"), rev_prot_ids, rev_pep_ids, document_id);
ptr->apply(fwd_prot_ids, rev_prot_ids);
TOLERANCE_ABSOLUTE(0.001)
for (vector<ProteinIdentification>::const_iterator prot_it = fwd_prot_ids.begin(); prot_it != fwd_prot_ids.end(); ++prot_it)
{
if (!prot_it->getHits().empty())
{
for (vector<ProteinHit>::const_iterator it = prot_it->getHits().begin(); it != prot_it->getHits().end(); ++it)
{
ProteinHit hit(*it);
double fdr(hit.getScore());
double orig_score((double)hit.getMetaValue("XTandem_score"));
// it gets here, but neither of the conditions below are ever satisfied
if (orig_score < -1.8)
{
TEST_REAL_SIMILAR(fdr, 0)
}
if (orig_score == 0.0)
{
TEST_REAL_SIMILAR(fdr, 0.897384)
}
}
}
}
}
END_SECTION
START_SECTION((void apply(PeptideIdentificationList &id)))
{
vector<ProteinIdentification> prot_ids;
PeptideIdentificationList pep_ids;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("FalseDiscoveryRate_OMSSA.idXML"), prot_ids, pep_ids);
ptr->apply(pep_ids);
TOLERANCE_ABSOLUTE(0.001)
for (Size z = 1; z <= 4; ++z)
{
for (PeptideIdentificationList::const_iterator it = pep_ids.begin(); it != pep_ids.end(); ++it)
{
for (vector<PeptideHit>::const_iterator pit = it->getHits().begin(); pit != it->getHits().end(); ++pit)
{
double fdr(pit->getScore());
double orig_score((double)pit->getMetaValue("OMSSA_score"));
if (orig_score <= 10e-4)
{
TEST_REAL_SIMILAR(fdr, 0)
}
if (orig_score >= 1000 && pit->getCharge() != 1)
{
TEST_EQUAL(fdr > 0.1, true)
}
}
}
// target hit
PeptideIdentification pep_id = pep_ids[0];
PeptideHit pit = pep_id.getHits()[0];
double fdr(pit.getScore());
TEST_REAL_SIMILAR(fdr, 0.0730478589420655);
// target+decoy hit considered as target
pep_id = pep_ids[5];
pit = pep_id.getHits()[0];
fdr = pit.getScore();
TEST_REAL_SIMILAR(fdr, 0.409926470588235);
// decoy hit removed
pep_id = pep_ids[9];
TEST_EQUAL(pep_id.getHits().size(), 0)
}
}
END_SECTION
START_SECTION((void apply(std::vector<ProteinIdentification>& ids)))
{
vector<ProteinIdentification> fwd_prot_ids, rev_prot_ids, prot_ids;
PeptideIdentificationList fwd_pep_ids, rev_pep_ids, pep_ids;
String document_id;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("XTandem_fwd_ids.idXML"), fwd_prot_ids, fwd_pep_ids, document_id);
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("XTandem_rev_ids.idXML"), rev_prot_ids, rev_pep_ids, document_id);
for (vector<ProteinIdentification>::const_iterator it = fwd_prot_ids.begin(); it != fwd_prot_ids.end(); ++it)
{
prot_ids.push_back(*it);
for (vector<ProteinHit>::iterator hit_it = prot_ids.back().getHits().begin(); hit_it != prot_ids.back().getHits().end(); ++hit_it)
{
hit_it->setMetaValue("target_decoy", "target");
}
}
for (vector<ProteinIdentification>::const_iterator it = rev_prot_ids.begin(); it != rev_prot_ids.end(); ++it)
{
prot_ids.push_back(*it);
for (vector<ProteinHit>::iterator hit_it = prot_ids.back().getHits().begin(); hit_it != prot_ids.back().getHits().end(); ++hit_it)
{
hit_it->setMetaValue("target_decoy", "decoy");
}
}
ptr->apply(prot_ids);
TOLERANCE_ABSOLUTE(0.001)
for (vector<ProteinIdentification>::const_iterator prot_it = prot_ids.begin(); prot_it != prot_ids.end(); ++prot_it)
{
if (!prot_it->getHits().empty())
{
for (vector<ProteinHit>::const_iterator it = prot_it->getHits().begin(); it != prot_it->getHits().end(); ++it)
{
ProteinHit hit(*it);
double fdr(hit.getScore());
double orig_score((double)hit.getMetaValue("XTandem_score"));
if (orig_score < -1.8)
{
TEST_REAL_SIMILAR(fdr, 0)
}
if (orig_score == -1.7)
{
TEST_REAL_SIMILAR(fdr, 0.0617284)
}
if (orig_score > -1.2)
{
TEST_EQUAL(fdr > 0.1, true)
}
}
}
}
}
END_SECTION
START_SECTION((void applyPicked(std::vector<ProteinIdentification>& ids)))
{
vector<ProteinIdentification> prot_ids;
PeptideIdentificationList pep_ids;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("FalseDiscoveryRate_picked_in.idXML"), prot_ids, pep_ids);
ptr->applyPickedProteinFDR(prot_ids[0],"decoy_");
TOLERANCE_ABSOLUTE(0.001)
const auto& hits = prot_ids[0].getHits();
TEST_REAL_SIMILAR(hits[0].getScore(),0.25)
TEST_REAL_SIMILAR(hits[1].getScore(),0.25)
TEST_REAL_SIMILAR(hits[2].getScore(),0.25)
TEST_REAL_SIMILAR(hits[3].getScore(),0.4)
TEST_REAL_SIMILAR(hits[4].getScore(),0.4)
TEST_REAL_SIMILAR(hits[5].getScore(),0.5)
}
END_SECTION
START_SECTION((void apply(std::vector<ProteinIdentification>& ids)))
{
vector<ProteinIdentification> fwd_prot_ids, rev_prot_ids, prot_ids;
PeptideIdentificationList fwd_pep_ids, rev_pep_ids, pep_ids;
String document_id;
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("XTandem_fwd_ids.idXML"), fwd_prot_ids, fwd_pep_ids, document_id);
IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("XTandem_rev_ids.idXML"), rev_prot_ids, rev_pep_ids, document_id);
for (vector<ProteinIdentification>::const_iterator it = fwd_prot_ids.begin(); it != fwd_prot_ids.end(); ++it)
{
prot_ids.push_back(*it);
for (vector<ProteinHit>::iterator hit_it = prot_ids.back().getHits().begin(); hit_it != prot_ids.back().getHits().end(); ++hit_it)
{
hit_it->setMetaValue("target_decoy", "target");
}
}
for (vector<ProteinIdentification>::const_iterator it = rev_prot_ids.begin(); it != rev_prot_ids.end(); ++it)
{
prot_ids.push_back(*it);
for (vector<ProteinHit>::iterator hit_it = prot_ids.back().getHits().begin(); hit_it != prot_ids.back().getHits().end(); ++hit_it)
{
hit_it->setMetaValue("target_decoy", "decoy");
}
}
ptr->apply(prot_ids);
TOLERANCE_ABSOLUTE(0.001)
for (vector<ProteinIdentification>::const_iterator prot_it = prot_ids.begin(); prot_it != prot_ids.end(); ++prot_it)
{
if (!prot_it->getHits().empty())
{
for (vector<ProteinHit>::const_iterator it = prot_it->getHits().begin(); it != prot_it->getHits().end(); ++it)
{
ProteinHit hit(*it);
double fdr(hit.getScore());
double orig_score((double)hit.getMetaValue("XTandem_score"));
if (orig_score < -1.8)
{
TEST_REAL_SIMILAR(fdr, 0)
}
if (orig_score == -1.7)
{
TEST_REAL_SIMILAR(fdr, 0.0617284)
}
if (orig_score > -1.2)
{
TEST_EQUAL(fdr > 0.1, true)
}
}
}
}
}
END_SECTION
delete ptr;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Histogram_test.cpp | .cpp | 7,227 | 247 | // 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/MATH/STATISTICS/Histogram.h>
#include <iostream>
#include <vector>
using namespace OpenMS;
using namespace OpenMS::Math;
using namespace std;
///////////////////////////
START_TEST(Histogram, "$Id$")
/////////////////////////////////////////////////////////////
Histogram<float,float>* dis_ptr = nullptr;
Histogram<float,float>* dis_nullPointer = nullptr;
START_SECTION((Histogram()))
dis_ptr = new Histogram<float,float>();
TEST_NOT_EQUAL(dis_ptr, dis_nullPointer)
END_SECTION
START_SECTION((~Histogram()))
delete dis_ptr;
END_SECTION
Histogram<float,float> d(0, 10, 1);
START_SECTION((Histogram(const Histogram& histogram)))
Histogram<float, float> d2(d);
TEST_TRUE(d == d2)
END_SECTION
START_SECTION((BinSizeType minBound() const))
TEST_REAL_SIMILAR(d.minBound(), 0.0)
END_SECTION
START_SECTION((BinSizeType maxBound() const))
TEST_REAL_SIMILAR(d.maxBound(), 10.0)
END_SECTION
START_SECTION((BinSizeType binSize() const))
TEST_REAL_SIMILAR(d.binSize(), 1)
END_SECTION
START_SECTION((Size size() const ))
TEST_EQUAL(d.size(), 10)
END_SECTION
START_SECTION((Histogram(BinSizeType min, BinSizeType max, BinSizeType bin_size)))
Histogram<float, float> d3(5.5f, 7.7f, 0.2f);
TEST_REAL_SIMILAR(d3.minBound(), 5.5)
TEST_REAL_SIMILAR(d3.maxBound(), 7.7)
TEST_REAL_SIMILAR(d3.binSize(), 0.2)
END_SECTION
START_SECTION((ValueType minValue() const))
TEST_REAL_SIMILAR(d.minValue(), 0.0)
END_SECTION
START_SECTION((ValueType maxValue() const))
TEST_REAL_SIMILAR(d.maxValue(), 0.0)
END_SECTION
START_SECTION((ValueType operator [] (Size index) const))
d.reset(4, 14, 2);
TEST_EQUAL(d.size(),5);
TEST_REAL_SIMILAR(d[0],0.0);
TEST_REAL_SIMILAR(d[1],0.0);
TEST_REAL_SIMILAR(d[2],0.0);
TEST_REAL_SIMILAR(d[3],0.0);
TEST_REAL_SIMILAR(d[4],0.0);
TEST_EXCEPTION(Exception::IndexOverflow, d[5])
END_SECTION
START_SECTION((Size inc(BinSizeType val, ValueType increment=1)))
Size bin_index = 123456;
TEST_EXCEPTION(Exception::OutOfRange, d.inc(3.9f, 250.3f))
TEST_EXCEPTION(Exception::OutOfRange, d.inc(14.1f, 250.3f))
bin_index = d.inc(4.0f, 1.0);
TEST_EQUAL(bin_index,0);
bin_index = d.inc(5.9f, 1.0);
TEST_EQUAL(bin_index,0);
TEST_REAL_SIMILAR(d[0],2.0);
TEST_REAL_SIMILAR(d[1],0.0);
TEST_REAL_SIMILAR(d[2],0.0);
TEST_REAL_SIMILAR(d[3],0.0);
TEST_REAL_SIMILAR(d[4],0.0);
bin_index = d.inc(8.0f, 45.0);
TEST_EQUAL(bin_index,2);
bin_index = d.inc(8.1f, 1.0);
TEST_EQUAL(bin_index,2);
bin_index = d.inc(9.9f, 4.0);
TEST_EQUAL(bin_index,2);
TEST_REAL_SIMILAR(d[0],2.0);
TEST_REAL_SIMILAR(d[1],0.0);
TEST_REAL_SIMILAR(d[2],50.0);
TEST_REAL_SIMILAR(d[3],0.0);
TEST_REAL_SIMILAR(d[4],0.0);
bin_index = d.inc(12.0f, 1.0);
TEST_EQUAL(bin_index,4);
bin_index = d.inc(13.1f, 2.0);
TEST_EQUAL(bin_index,4);
bin_index = d.inc(14.0f, 3.0);
TEST_EQUAL(bin_index,4);
TEST_REAL_SIMILAR(d[0],2.0);
TEST_REAL_SIMILAR(d[1],0.0);
TEST_REAL_SIMILAR(d[2],50.0);
TEST_REAL_SIMILAR(d[3],0.0);
TEST_REAL_SIMILAR(d[4],6.0);
END_SECTION
START_SECTION((ConstIterator begin() const))
Histogram<float,float>::ConstIterator it = d.begin();
TEST_REAL_SIMILAR(*it, 2.0)
END_SECTION
START_SECTION((ConstIterator end() const))
Histogram<float,float>::ConstIterator it = d.begin();
TEST_REAL_SIMILAR(*it,2.0);
++it;
TEST_REAL_SIMILAR(*it,0.0);
++it;
TEST_REAL_SIMILAR(*it,50.0);
++it;
TEST_REAL_SIMILAR(*it,0.0);
++it;
TEST_REAL_SIMILAR(*it,6.0);
++it;
TEST_EQUAL(it==d.end(),true);
END_SECTION
START_SECTION((ValueType binValue(BinSizeType val) const))
TEST_EXCEPTION(Exception::OutOfRange, d.binValue(3.9f))
TEST_REAL_SIMILAR(d.binValue(4.0f),2.0);
TEST_REAL_SIMILAR(d.binValue(5.9f),2.0);
TEST_REAL_SIMILAR(d.binValue(6.0f),0.0);
TEST_REAL_SIMILAR(d.binValue(7.9f),0.0);
TEST_REAL_SIMILAR(d.binValue(8.0f),50.0);
TEST_REAL_SIMILAR(d.binValue(9.9f),50.0);
TEST_REAL_SIMILAR(d.binValue(10.0f),0.0);
TEST_REAL_SIMILAR(d.binValue(11.9f),0.0);
TEST_REAL_SIMILAR(d.binValue(12.0f),6.0);
TEST_REAL_SIMILAR(d.binValue(14.0f),6.0);
TEST_EXCEPTION(Exception::OutOfRange, d.binValue(14.1f))
END_SECTION
START_SECTION((void reset(BinSizeType min, BinSizeType max, BinSizeType bin_size)))
d.reset(1, 11, 2);
TEST_REAL_SIMILAR(d.minBound(), 1)
TEST_REAL_SIMILAR(d.maxBound(), 11)
TEST_EQUAL(d.size(), 5)
TEST_REAL_SIMILAR(d.binSize(), 2)
END_SECTION
START_SECTION((bool operator == (const Histogram& histogram) const))
Histogram<float, float> dist(1, 11, 2);
TEST_TRUE(d == dist)
END_SECTION
START_SECTION((bool operator != (const Histogram& histogram) const))
Histogram<float, float> dist(1, 12, 2);
TEST_FALSE(d == dist)
END_SECTION
START_SECTION((Histogram& operator = (const Histogram& histogram)))
Histogram<float, float> dist;
dist = d;
TEST_TRUE(d == dist)
END_SECTION
START_SECTION((void applyLogTransformation(BinSizeType multiplier)))
TOLERANCE_ABSOLUTE(0.01)
Histogram<float, float> dist(0,5,1);
dist.inc(0.5,1);
dist.inc(1.5,10);
dist.inc(2.5,100);
dist.inc(3.5,1000);
dist.inc(4.5,10000);
dist.applyLogTransformation(1.0);
TEST_REAL_SIMILAR(dist.binValue(0.5),0.6931);
TEST_REAL_SIMILAR(dist.binValue(1.5),2.3979);
TEST_REAL_SIMILAR(dist.binValue(2.5),4.61512);
TEST_REAL_SIMILAR(dist.binValue(3.5),6.90875);
TEST_REAL_SIMILAR(dist.binValue(4.5),9.21044);
END_SECTION
START_SECTION((BinSizeType centerOfBin(Size bin_index) const))
Histogram<float, float> dist(0,5,1);
dist.inc(0.5,1);
dist.inc(1.5,10);
dist.inc(2.5,100);
dist.inc(3.5,1000);
dist.inc(4.5,10000);
TEST_REAL_SIMILAR(dist.centerOfBin(0),0.5);
TEST_REAL_SIMILAR(dist.centerOfBin(1),1.5);
TEST_REAL_SIMILAR(dist.centerOfBin(2),2.5);
TEST_REAL_SIMILAR(dist.centerOfBin(3),3.5);
TEST_REAL_SIMILAR(dist.centerOfBin(4),4.5);
TEST_EXCEPTION(Exception::IndexOverflow, dist.centerOfBin(5))
END_SECTION
START_SECTION((BinSizeType leftBorderOfBin(Size bin_index) const))
Histogram<float, float> dist(0, 5, 1);
TEST_EQUAL(dist.leftBorderOfBin(0), 0);
TEST_EQUAL(dist.leftBorderOfBin(1), 1);
TEST_EQUAL(dist.leftBorderOfBin(2), 2);
TEST_EQUAL(dist.leftBorderOfBin(3), 3);
TEST_EQUAL(dist.leftBorderOfBin(4), 4);
TEST_EXCEPTION(Exception::IndexOverflow, dist.leftBorderOfBin(5))
END_SECTION
START_SECTION((BinSizeType rightBorderOfBin(Size bin_index) const))
Histogram<float, float> dist(0, 5, 1);
TEST_EQUAL(dist.rightBorderOfBin(0), 1);
TEST_EQUAL(dist.rightBorderOfBin(1), 2);
TEST_EQUAL(dist.rightBorderOfBin(2), 3);
TEST_EQUAL(dist.rightBorderOfBin(3), 4);
TEST_EQUAL(dist.rightBorderOfBin(4), std::nextafter(5.0f, 6.0f));// its actually the next item after 5.0
TEST_EXCEPTION(Exception::IndexOverflow, dist.rightBorderOfBin(5))
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MetaboliteFeatureDeconvolution_test.cpp | .cpp | 11,919 | 311 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <map>
///////////////////////////
#include <OpenMS/ANALYSIS/DECHARGING/MetaboliteFeatureDeconvolution.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/FORMAT/FeatureXMLFile.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/CONCEPT/FuzzyStringComparator.h>
///////////////////////////
namespace OpenMS
{
class MetaboliteFeatureDeconvolutionTest
: public MetaboliteFeatureDeconvolution
{
public:
/// List of adducts used to explain mass differences
MassExplainer::AdductsType getPotentialAdducts()
{ return potential_adducts_;}
/// labeling table
std::map<Size, String> getMapLabels()
{ return map_label_;}
/// labeling table inverse
std::map<String, Size> getMapLabelInverse()
{ return map_label_inverse_;}
/// status of intensity filter for edges
bool isIntensityFilterEnabled()
{ return enable_intensity_filter_;}
/// status of charge discovery
CHARGEMODE getChargeMode()
{ return q_try_;}
};
}
using namespace OpenMS;
using namespace std;
START_TEST(MetaboliteFeatureDeconvolution, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MetaboliteFeatureDeconvolution* ptr = nullptr;
MetaboliteFeatureDeconvolution* nullPointer = nullptr;
START_SECTION(MetaboliteFeatureDeconvolution())
ptr = new MetaboliteFeatureDeconvolution();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~MetaboliteFeatureDeconvolution())
delete ptr;
END_SECTION
START_SECTION([EXTRA](void updateMembers_()))
MetaboliteFeatureDeconvolutionTest fdt;
Param p;
p.setValue("charge_min", 11, "minimal possible charge");
p.setValue("charge_max", 13, "maximal possible charge");
p.setValue("retention_max_diff", 1.0, "maximum allowed RT difference between any two features if their relation shall be determined");
p.setValue("retention_max_diff_local", 2.0, "maxi");
p.setValue("potential_adducts", std::vector<std::string>{"H:+:0.7","Na:+:0.3","(2)H4H-4:0:0.2:-2:heavy"}, "Ad");
fdt.setParameters(p);
{
MassExplainer::AdductsType adducts = fdt.getPotentialAdducts();
std::map<Size, String> map = fdt.getMapLabels();
std::map<String, Size> map_i = fdt.getMapLabelInverse();
bool b_filter = fdt.isIntensityFilterEnabled();
MetaboliteFeatureDeconvolution::CHARGEMODE cm = fdt.getChargeMode();
TEST_EQUAL(adducts.size(), 3)
TEST_EQUAL(adducts[0].getFormula(), "H1");
TEST_EQUAL(adducts[0].getRTShift(), 0);
TEST_EQUAL(adducts[0].getCharge(), 1);
TEST_REAL_SIMILAR(adducts[0].getLogProb(), log(0.7));
TEST_EQUAL(adducts[1].getFormula(), "Na1");
TEST_EQUAL(adducts[1].getRTShift(), 0);
TEST_EQUAL(adducts[1].getCharge(), 1);
TEST_REAL_SIMILAR(adducts[1].getLogProb(), log(0.3));
TEST_EQUAL(adducts[2].getFormula(), "(2)H4H-4");
TEST_EQUAL(adducts[2].getRTShift(), -2);
TEST_EQUAL(adducts[2].getCharge(), 0);
TEST_REAL_SIMILAR(adducts[2].getLogProb(), log(0.2));
TEST_EQUAL(cm, MetaboliteFeatureDeconvolution::CHARGEMODE::QFROMFEATURE)
TEST_EQUAL(map.size(), 2)
TEST_EQUAL(map_i.size(), 2)
TEST_EQUAL(map[0], "decharged features");
TEST_EQUAL(map_i["decharged features"], 0);
TEST_EQUAL(map[1], "heavy");
TEST_EQUAL(map_i["heavy"], 1);
TEST_EQUAL(b_filter, false)
Param p_internal = fdt.getParameters();
TEST_REAL_SIMILAR((double) p_internal.getValue("retention_max_diff"), 1.0);
TEST_REAL_SIMILAR((double) p_internal.getValue("retention_max_diff_local"), 1.0);
}
// second param set
p.setValue("charge_min", 11, "minimal possible charge");
p.setValue("charge_max", 13, "maximal possible charge");
p.setValue("q_try", "heuristic", "Try dif");
p.setValue("potential_adducts", std::vector<std::string>{"H:+:0.9","Na:++:0.1"});
p.setValue("retention_max_diff", 1.0, "maximum ");
p.setValue("retention_max_diff_local", 1.0, "maxim");
p.setValue("intensity_filter", "true", "Enable");
p.setValue("default_map_label", "mylabel", "Label");
p.setValue("retention_max_diff", 2.0, "maximum allowed RT difference between any two features if their relation shall be determined");
p.setValue("retention_max_diff_local", 5.0, "maxi");
fdt.setParameters(p);
{
MassExplainer::AdductsType adducts = fdt.getPotentialAdducts();
std::map<Size, String> map = fdt.getMapLabels();
std::map<String, Size> map_i = fdt.getMapLabelInverse();
bool b_filter = fdt.isIntensityFilterEnabled();
MetaboliteFeatureDeconvolution::CHARGEMODE cm = fdt.getChargeMode();
TEST_EQUAL(adducts.size(), 2)
TEST_EQUAL(adducts[0].getFormula(), "H1");
TEST_EQUAL(adducts[0].getRTShift(), 0);
TEST_EQUAL(adducts[0].getCharge(), 1);
TEST_REAL_SIMILAR(adducts[0].getLogProb(), log(0.9));
TEST_EQUAL(adducts[1].getFormula(), "Na1");
TEST_EQUAL(adducts[1].getRTShift(), 0);
TEST_EQUAL(adducts[1].getCharge(), 2);
TEST_REAL_SIMILAR(adducts[1].getLogProb(), log(0.1));
TEST_EQUAL(cm, MetaboliteFeatureDeconvolution::CHARGEMODE::QHEURISTIC)
TEST_EQUAL(map.size(), 1)
TEST_EQUAL(map_i.size(), 1)
TEST_EQUAL(map[0], "mylabel");
TEST_EQUAL(map_i["mylabel"], 0);
TEST_EQUAL(b_filter, true)
Param p_internal = fdt.getParameters();
TEST_REAL_SIMILAR((double) p_internal.getValue("retention_max_diff"), 2.0);
TEST_REAL_SIMILAR((double) p_internal.getValue("retention_max_diff_local"), 2.0);
}
END_SECTION
START_SECTION(MetaboliteFeatureDeconvolution(const MetaboliteFeatureDeconvolution &source))
MetaboliteFeatureDeconvolution fd;
Param p;
p.setValue("charge_min", 11, "minimal possible charge");
p.setValue("charge_max", 13, "maximal possible charge");
fd.setParameters(p);
MetaboliteFeatureDeconvolution fd2(fd);
MetaboliteFeatureDeconvolution fd_untouched;
TEST_EQUAL(fd2.getParameters(), fd.getParameters())
TEST_NOT_EQUAL(fd2.getParameters(), fd_untouched.getParameters())
END_SECTION
START_SECTION(MetaboliteFeatureDeconvolution& operator=(const MetaboliteFeatureDeconvolution &source))
MetaboliteFeatureDeconvolution fd;
Param p;
p.setValue("charge_min", 11, "minimal possible charge");
p.setValue("charge_max", 13, "maximal possible charge");
fd.setParameters(p);
MetaboliteFeatureDeconvolution fd2 = fd;
MetaboliteFeatureDeconvolution fd_untouched;
TEST_EQUAL(fd2.getParameters(), fd.getParameters())
TEST_NOT_EQUAL(fd2.getParameters(), fd_untouched.getParameters())
END_SECTION
START_SECTION(void compute(const FeatureMapType &fm_in, FeatureMapType &fm_out, ConsensusMap &cons_map, ConsensusMap &cons_map_p))
//_CrtSetDbgFlag(_CrtSetDbgFlag(0)|_CRTDBG_CHECK_ALWAYS_DF);
MetaboliteFeatureDeconvolution fd;
Param p;
p.setValue("potential_adducts", std::vector<std::string>{"H:+:0.7","Na:+:0.3","(2)H4H-4:0:0.2:-2:heavy"}, "Ad");
p.setValue("mass_max_diff", 0.1);
p.setValue("use_minority_bound","true","enable bound");
fd.setParameters(p);
FeatureMap fm_in, fm_out;
ConsensusMap cm, cm2;
FeatureXMLFile fl;
fl.load(OPENMS_GET_TEST_DATA_PATH("FeatureDeconvolution_easy_input.featureXML"), fm_in);
fd.compute(fm_in, fm_out, cm, cm2);
String out_file;
NEW_TMP_FILE(out_file)
ConsensusXMLFile c1;
c1.store(out_file,cm);
WHITELIST("xml-stylesheet,consensusXML version=,consensusElement id=,<UserParam type=");
// WHITELIST("xml-stylesheet,map id,consensusElement id=");
TEST_FILE_SIMILAR(out_file, OPENMS_GET_TEST_DATA_PATH("MetaboliteFeatureDeconvolution_easy_output.consensusXML"));
//small pos test file with specific ions
Param p_pos;
p_pos.setValue("potential_adducts", std::vector<std::string>{"H:+:0.6","Na:+:0.2","NH4:+:0.1","K:+:0.1","C2H3N:0:0.05","H-2O-1:0:0.05","H-1Na:0:0.05"}, "Ad_p");
p_pos.setValue("charge_min", 1, "minimal possible charge");
p_pos.setValue("charge_max", 3, "maximal possible charge");
p_pos.setValue("charge_span_max", 3);
p_pos.setValue("max_neutrals", 1);
p_pos.setValue("q_try", "feature");
p_pos.setValue("mass_max_diff", 0.05);
p_pos.setValue("retention_max_diff", 1.0);
p_pos.setValue("retention_max_diff_local", 1.0);
p_pos.setValue("intensity_filter", "false");
p_pos.setValue("use_minority_bound", "false");
fd.setParameters(p_pos);
FeatureMap fm_p_in, fm_p_out;
ConsensusMap cm_p, cm_p2;
FeatureXMLFile fl_p;
fl_p.load(OPENMS_GET_TEST_DATA_PATH("MetaboliteFeatureDeconvolution_test.featureXML"), fm_p_in);
fd.compute(fm_p_in, fm_p_out, cm_p, cm_p2);
String out_file_p;
NEW_TMP_FILE(out_file_p)
ConsensusXMLFile c_p;
c_p.store(out_file_p,cm_p);
WHITELIST("xml-stylesheet,consensusXML version=,consensusElement id=,<UserParam type=");
TEST_FILE_SIMILAR(out_file_p, OPENMS_GET_TEST_DATA_PATH("MetaboliteFeatureDeconvolution_pos_output.consensusXML"));
//small neg test file with specific ions
Param p_neg;
p_neg.setValue("potential_adducts", std::vector<std::string>{"H-1:-:0.6","Cl:-:0.2","Br:-:0.2","CH2O2:0:0.05","H-2O-1:0:0.05","H-1Na:0:0.05","H-1K:0:0.05"}, "Ad_n");
p_neg.setValue("charge_min", -3, "minimal possible charge");
p_neg.setValue("charge_max", -1, "maximal possible charge");
p_neg.setValue("charge_span_max", 3);
p_neg.setValue("max_neutrals", 1);
p_neg.setValue("q_try", "feature");
p_neg.setValue("mass_max_diff", 0.05);
p_neg.setValue("retention_max_diff", 1.0);
p_neg.setValue("retention_max_diff_local", 1.0);
p_neg.setValue("intensity_filter", "false");
p_neg.setValue("use_minority_bound", "false");
p_neg.setValue("negative_mode", "true");
fd.setParameters(p_neg);
FeatureMap fm_n_in, fm_n_out;
ConsensusMap cm_n, cm_n2;
FeatureXMLFile fl_n;
fl_n.load(OPENMS_GET_TEST_DATA_PATH("MetaboliteFeatureDeconvolution_test.featureXML"), fm_n_in);
fd.compute(fm_n_in, fm_n_out, cm_n, cm_n2);
String out_file_n;
NEW_TMP_FILE(out_file_n)
ConsensusXMLFile c_n;
c_n.store(out_file_n,cm_n);
WHITELIST("xml-stylesheet,consensusXML version=,consensusElement id=,<UserParam type=");
TEST_FILE_SIMILAR(out_file_n, OPENMS_GET_TEST_DATA_PATH("MetaboliteFeatureDeconvolution_neg_output.consensusXML"));
//small pos test file with specific ions and ppm error
Param p_pos_ppm;
p_pos_ppm.setValue("potential_adducts", std::vector<std::string>{"H:+:0.6","Na:+:0.4"}, "Ad_p");
p_pos_ppm.setValue("charge_min", 1, "minimal possible charge");
p_pos_ppm.setValue("charge_max", 3, "maximal possible charge");
p_pos_ppm.setValue("charge_span_max", 3);
p_pos_ppm.setValue("max_neutrals", 1);
p_pos_ppm.setValue("q_try", "feature");
p_pos_ppm.setValue("mass_max_diff", 50.0);
p_pos_ppm.setValue("unit", "ppm");
p_pos_ppm.setValue("retention_max_diff", 1.0);
p_pos_ppm.setValue("retention_max_diff_local", 1.0);
p_pos_ppm.setValue("intensity_filter", "false");
p_pos_ppm.setValue("use_minority_bound", "false");
fd.setParameters(p_pos_ppm);
FeatureMap fm_ppm_in, fm_ppm_out;
ConsensusMap cm_ppm, cm_ppm2;
FeatureXMLFile fl_ppm;
fl_ppm.load(OPENMS_GET_TEST_DATA_PATH("MetaboliteFeatureDeconvolution_test_ppm.featureXML"), fm_ppm_in);
fd.compute(fm_ppm_in, fm_ppm_out, cm_ppm, cm_ppm2);
String out_file_ppm;
NEW_TMP_FILE(out_file_ppm)
ConsensusXMLFile f_ppm;
f_ppm.store(out_file_ppm,cm_ppm);
WHITELIST("xml-stylesheet,consensusXML version=,consensusElement id=,<UserParam type=");
TEST_FILE_SIMILAR(out_file_ppm, OPENMS_GET_TEST_DATA_PATH("MetaboliteFeatureDeconvolution_ppm_output.consensusXML"));
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ProteinHit_test.cpp | .cpp | 11,250 | 397 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <OpenMS/METADATA/ProteinHit.h>
#include <OpenMS/DATASTRUCTURES/String.h>
///////////////////////////
START_TEST(ProteinHit, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
float score = 4.4f;
UInt rank = 3;
String sequence = "ARRAY";
String accession = "PROOE34";
String description = "class II antigen";
ProteinHit* ptr = nullptr;
ProteinHit* nullPointer = nullptr;
START_SECTION(ProteinHit())
ptr = new ProteinHit();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~ProteinHit())
delete ptr;
END_SECTION
START_SECTION((ProteinHit(double score, UInt rank, String accession, String sequence)))
ProteinHit hit(score, rank, accession, sequence);
TEST_EQUAL(hit.getScore(), score)
TEST_EQUAL(hit.getRank(), rank)
TEST_EQUAL(hit.getAccession(), accession)
TEST_EQUAL(hit.getSequence(), sequence)
TEST_EQUAL(hit.getCoverage(), -1)
END_SECTION
START_SECTION(ProteinHit(const ProteinHit& source))
ProteinHit source;
source.setScore(score);
source.setRank(rank);
source.setAccession(accession);
source.setDescription(description);
source.setSequence(sequence);
source.setMetaValue("label",17);
source.setCoverage(123.123);
ProteinHit hit(source);
TEST_EQUAL(hit.getScore(), score)
TEST_EQUAL(hit.getRank(), rank)
TEST_EQUAL(hit.getAccession(), accession)
TEST_EQUAL(hit.getDescription(), description)
TEST_EQUAL(hit.getSequence(), sequence)
TEST_EQUAL((UInt)hit.getMetaValue("label"),17)
TEST_EQUAL(hit.getCoverage(), 123.123)
END_SECTION
START_SECTION(ProteinHit& operator=(const ProteinHit& source))
ProteinHit hit;
ProteinHit hit2(score, rank, accession, sequence);
hit2.setMetaValue("label",17);
hit2.setCoverage(123.123);
hit2.setDescription(description);
hit = hit2;
TEST_EQUAL(hit.getScore(), score)
TEST_EQUAL(hit.getRank(), rank)
TEST_EQUAL(hit.getAccession(), accession)
TEST_EQUAL(hit.getDescription(), description)
TEST_EQUAL(hit.getSequence(), sequence)
TEST_EQUAL((UInt)hit.getMetaValue("label"),17)
TEST_EQUAL(hit.getCoverage(), 123.123)
END_SECTION
START_SECTION(ProteinHit& operator= (const MetaInfoInterface& source))
ProteinHit hit(score, rank, accession, sequence);
hit.setCoverage(123.123);
MetaInfoInterface meta;
meta.setMetaValue("label",17);
hit = meta;
TEST_EQUAL(hit.getScore(), score)
TEST_EQUAL(hit.getRank(), rank)
TEST_EQUAL(hit.getAccession(), accession)
TEST_EQUAL(hit.getSequence(), sequence)
TEST_EQUAL(hit.getCoverage(), 123.123)
TEST_EQUAL((UInt)hit.getMetaValue("label"),17)
END_SECTION
START_SECTION(bool operator == (const ProteinHit& rhs) const)
ProteinHit hit, hit2;
TEST_EQUAL(hit==hit2,true);
hit.setScore(score);
TEST_EQUAL(hit==hit2,false);
hit = hit2;
hit.setRank(rank);
TEST_EQUAL(hit==hit2,false);
hit = hit2;
hit.setAccession(accession);
TEST_EQUAL(hit==hit2,false);
hit = hit2;
hit.setSequence(sequence);
TEST_EQUAL(hit==hit2,false);
hit = hit2;
hit.setMetaValue("label",17);
TEST_EQUAL(hit==hit2,false);
hit = hit2;
hit.setCoverage(123.123);
TEST_EQUAL(hit==hit2,false);
hit = hit2;
END_SECTION
START_SECTION(bool operator != (const ProteinHit& rhs) const)
ProteinHit hit, hit2;
TEST_EQUAL(hit!=hit2,false);
hit.setScore(score);
TEST_EQUAL(hit!=hit2,true);
hit = hit2;
hit.setRank(rank);
TEST_EQUAL(hit!=hit2,true);
hit = hit2;
hit.setAccession(accession);
TEST_EQUAL(hit!=hit2,true);
hit = hit2;
hit.setSequence(sequence);
TEST_EQUAL(hit!=hit2,true);
hit = hit2;
hit.setMetaValue("label",17);
TEST_EQUAL(hit!=hit2,true);
hit = hit2;
hit.setCoverage(123.123);
TEST_EQUAL(hit!=hit2,true);
hit = hit2;
END_SECTION
START_SECTION(const String& getAccession() const)
ProteinHit hit(score, rank, accession, sequence);
TEST_EQUAL(hit.getAccession(), accession)
END_SECTION
START_SECTION(const String& getDescription() const)
ProteinHit hit(score, rank, accession, sequence);
hit.setDescription(description);
TEST_EQUAL(hit.getDescription(), description)
END_SECTION
START_SECTION(const String& getSequence() const)
ProteinHit hit(score, rank, accession, sequence);
TEST_EQUAL(hit.getSequence(), sequence)
END_SECTION
START_SECTION(float getScore() const)
ProteinHit hit(score, rank, accession, sequence);
TEST_EQUAL(hit.getScore(), score)
END_SECTION
START_SECTION(UInt getRank() const)
ProteinHit hit(score, rank, accession, sequence);
TEST_EQUAL(hit.getRank(), rank)
END_SECTION
START_SECTION(double getCoverage() const)
ProteinHit hit(score, rank, accession, sequence);
TEST_EQUAL(hit.getCoverage(), -1)
hit.setCoverage(123.123);
TEST_EQUAL(hit.getCoverage(), 123.123)
END_SECTION
START_SECTION(void setRank(UInt newrank))
ProteinHit hit;
hit.setRank(rank);
TEST_EQUAL(hit.getRank(), rank)
END_SECTION
START_SECTION(void setScore(const double score))
ProteinHit hit;
hit.setScore(score);
TEST_EQUAL(hit.getScore(), score);
END_SECTION
START_SECTION(void setSequence(const String& sequence))
ProteinHit hit;
hit.setSequence(sequence);
TEST_EQUAL(hit.getSequence(), sequence)
END_SECTION
START_SECTION(void setAccession(const String& accession))
ProteinHit hit;
hit.setAccession(accession);
TEST_EQUAL(hit.getAccession(), accession)
END_SECTION
START_SECTION(void setDescription(const String& description))
ProteinHit hit;
hit.setDescription(description);
TEST_EQUAL(hit.getDescription(), description)
END_SECTION
START_SECTION(void setCoverage(const double coverage))
ProteinHit hit;
hit.setCoverage(123.123);
TEST_EQUAL(hit.getCoverage(), 123.123)
END_SECTION
START_SECTION(([ProteinHit::ScoreLess] template < typename Arg > bool operator()(const Arg &a, const Arg &b)))
{
ProteinHit a,b;
a.setScore(10);
b.setScore(20);
TEST_EQUAL(ProteinHit::ScoreLess().operator()(a,b), true)
TEST_EQUAL(ProteinHit::ScoreLess().operator()(b,a), false)
TEST_EQUAL(ProteinHit::ScoreLess().operator()(a,a), false)
}
END_SECTION
START_SECTION(([ProteinHit::ScoreMore] template < typename Arg > bool operator()(const Arg &a, const Arg &b)))
{
ProteinHit a,b;
a.setScore(20);
b.setScore(10);
TEST_EQUAL(ProteinHit::ScoreMore().operator()(a,b), true)
TEST_EQUAL(ProteinHit::ScoreMore().operator()(b,a), false)
TEST_EQUAL(ProteinHit::ScoreMore().operator()(a,a), false)
}
END_SECTION
START_SECTION((bool isDecoy() const))
{
ProteinHit hit;
// Test default behavior (no target_decoy meta value set)
TEST_EQUAL(hit.isDecoy(), false);
// Test with explicit "target" value
hit.setMetaValue("target_decoy", "target");
TEST_EQUAL(hit.isDecoy(), false);
// Test with "decoy" value
hit.setMetaValue("target_decoy", "decoy");
TEST_EQUAL(hit.isDecoy(), true);
// Test with "DECOY" (case insensitive)
hit.setMetaValue("target_decoy", "DECOY");
TEST_EQUAL(hit.isDecoy(), true);
// Test after removing meta value
hit.removeMetaValue("target_decoy");
TEST_EQUAL(hit.isDecoy(), false);
}
END_SECTION
START_SECTION((void setTargetDecoyType(TargetDecoyType type)))
{
ProteinHit hit;
// Test setting TARGET
hit.setTargetDecoyType(ProteinHit::TargetDecoyType::TARGET);
TEST_EQUAL(hit.getMetaValue("target_decoy"), "target");
// Test setting DECOY
hit.setTargetDecoyType(ProteinHit::TargetDecoyType::DECOY);
TEST_EQUAL(hit.getMetaValue("target_decoy"), "decoy");
// Test setting UNKNOWN (should remove meta value)
hit.setTargetDecoyType(ProteinHit::TargetDecoyType::UNKNOWN);
TEST_EQUAL(hit.metaValueExists("target_decoy"), false);
TEST_EQUAL(hit.getTargetDecoyType(), ProteinHit::TargetDecoyType::UNKNOWN);
}
END_SECTION
START_SECTION((TargetDecoyType getTargetDecoyType() const))
{
ProteinHit hit;
// Test default behavior (should return UNKNOWN when meta value doesn't exist)
TEST_EQUAL(hit.getTargetDecoyType(), ProteinHit::TargetDecoyType::UNKNOWN);
// Test with explicit "target" value
hit.setMetaValue("target_decoy", "target");
TEST_EQUAL(hit.getTargetDecoyType(), ProteinHit::TargetDecoyType::TARGET);
// Test with "decoy" value
hit.setMetaValue("target_decoy", "decoy");
TEST_EQUAL(hit.getTargetDecoyType(), ProteinHit::TargetDecoyType::DECOY);
// Test with "DECOY" (case insensitive)
hit.setMetaValue("target_decoy", "DECOY");
TEST_EQUAL(hit.getTargetDecoyType(), ProteinHit::TargetDecoyType::DECOY);
// Test after removing meta value (should return UNKNOWN)
hit.removeMetaValue("target_decoy");
TEST_EQUAL(hit.getTargetDecoyType(), ProteinHit::TargetDecoyType::UNKNOWN);
}
END_SECTION
START_SECTION(([EXTRA] std::hash<ProteinHit>))
{
// Test that equal ProteinHits have equal hashes
ProteinHit hit1(4.5, 1, "ACC123", "PEPTIDE");
hit1.setCoverage(45.5);
ProteinHit hit2(4.5, 1, "ACC123", "PEPTIDE");
hit2.setCoverage(45.5);
TEST_EQUAL(hit1 == hit2, true)
TEST_EQUAL(std::hash<ProteinHit>{}(hit1), std::hash<ProteinHit>{}(hit2))
// Test that different ProteinHits have different hashes (not guaranteed but expected)
ProteinHit hit3(4.5, 1, "ACC456", "PEPTIDE");
hit3.setCoverage(45.5);
TEST_NOT_EQUAL(std::hash<ProteinHit>{}(hit1), std::hash<ProteinHit>{}(hit3))
// Test different scores
ProteinHit hit4(5.5, 1, "ACC123", "PEPTIDE");
hit4.setCoverage(45.5);
TEST_NOT_EQUAL(std::hash<ProteinHit>{}(hit1), std::hash<ProteinHit>{}(hit4))
// Test different rank
ProteinHit hit5(4.5, 2, "ACC123", "PEPTIDE");
hit5.setCoverage(45.5);
TEST_NOT_EQUAL(std::hash<ProteinHit>{}(hit1), std::hash<ProteinHit>{}(hit5))
// Test different sequence
ProteinHit hit6(4.5, 1, "ACC123", "PROTEIN");
hit6.setCoverage(45.5);
TEST_NOT_EQUAL(std::hash<ProteinHit>{}(hit1), std::hash<ProteinHit>{}(hit6))
// Test different coverage
ProteinHit hit7(4.5, 1, "ACC123", "PEPTIDE");
hit7.setCoverage(50.0);
TEST_NOT_EQUAL(std::hash<ProteinHit>{}(hit1), std::hash<ProteinHit>{}(hit7))
// Test use in unordered_set
std::unordered_set<ProteinHit> hit_set;
hit_set.insert(hit1);
hit_set.insert(hit2); // Should not add duplicate
hit_set.insert(hit3); // Should add (different accession)
TEST_EQUAL(hit_set.size(), 2)
TEST_EQUAL(hit_set.count(hit1), 1)
TEST_EQUAL(hit_set.count(hit3), 1)
// Test use in unordered_map
std::unordered_map<ProteinHit, std::string> hit_map;
hit_map[hit1] = "first";
hit_map[hit3] = "second";
TEST_EQUAL(hit_map.size(), 2)
TEST_EQUAL(hit_map[hit1], "first")
TEST_EQUAL(hit_map[hit2], "first") // hit2 == hit1, so should get same value
TEST_EQUAL(hit_map[hit3], "second")
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MetaInfoInterface_test.cpp | .cpp | 13,476 | 435 | // 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/MetaInfoInterface.h>
///////////////////////////
START_TEST(Example, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace std;
using namespace OpenMS;
MetaInfoInterface* test = nullptr;
MetaInfoInterface* nullPointer = nullptr;
START_SECTION((MetaInfoInterface()))
test = new MetaInfoInterface;
TEST_NOT_EQUAL(test, nullPointer)
END_SECTION
START_SECTION((~MetaInfoInterface()))
delete test;
END_SECTION
MetaInfoInterface mi;
START_SECTION((static MetaInfoRegistry& metaRegistry()))
MetaInfoInterface mi2;
mi2.metaRegistry().registerName("testname","testdesc","testunit");
TEST_EQUAL(mi2.metaRegistry().getIndex("testname"),1024);
TEST_EQUAL(mi.metaRegistry().getIndex("testname"),1024);
END_SECTION
START_SECTION((void setMetaValue(const String& name, const DataValue& value)))
NOT_TESTABLE //tested in the get method
END_SECTION
START_SECTION((void setMetaValue(UInt index, const DataValue& value)))
NOT_TESTABLE //tested in the get method
END_SECTION
START_SECTION((const DataValue& getMetaValue(UInt index, const DataValue& default_value = DataValue::EMPTY) const))
{
mi.setMetaValue(1024, String("testtesttest"));
TEST_STRING_EQUAL(mi.getMetaValue(1024), "testtesttest");
TEST_EQUAL(mi.getMetaValue(1025) == DataValue::EMPTY, true);
TEST_EQUAL(mi.getMetaValue(1025, 10) == DataValue(10), true);
}
END_SECTION
START_SECTION((const DataValue& getMetaValue(const String& name, const DataValue& default_value = DataValue::EMPTY) const))
{
mi.setMetaValue("testname", String("testtesttest2"));
TEST_STRING_EQUAL(mi.getMetaValue("testname"), "testtesttest2");
TEST_EQUAL(mi.getMetaValue("notdefined") == DataValue::EMPTY, true);
TEST_EQUAL(mi.getMetaValue("notdefined", 10) == DataValue(10), true);
}
END_SECTION
mi.setMetaValue("cluster_id", 4711.12f);
mi.setMetaValue(2, 4712.12f);
START_SECTION((bool isMetaEmpty() const))
MetaInfoInterface tmp;
TEST_EQUAL(tmp.isMetaEmpty(),true)
tmp.setMetaValue(1024,String("testtesttest"));
TEST_EQUAL(tmp.isMetaEmpty(),false)
END_SECTION
TOLERANCE_ABSOLUTE(0.001)
// Copy Constructor
START_SECTION((MetaInfoInterface(const MetaInfoInterface& rhs)))
{
//test if copy worked
MetaInfoInterface mi3(mi);
TEST_REAL_SIMILAR(double(mi.getMetaValue("cluster_id")),double(mi3.getMetaValue("cluster_id")))
//test if a deep copy was done
mi3.setMetaValue("cluster_id",11.9);
TEST_REAL_SIMILAR(double(mi.getMetaValue("cluster_id")),4712.12)
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")),11.9)
}
END_SECTION
/// Move constructor
START_SECTION(( MetaInfoInterface(MetaInfoInterface&&) noexcept ))
{
// Ensure that MetaInfoInterface has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
TEST_EQUAL(noexcept(MetaInfoInterface(std::declval<MetaInfoInterface&&>())), true)
MetaInfoInterface example(mi);
MetaInfoInterface mi3(std::move(example));
// test if move worked
TEST_EQUAL(mi3.metaValueExists("cluster_id"), true);
TEST_EQUAL(example.metaValueExists("cluster_id"), false);
TEST_EQUAL(example.isMetaEmpty(), true);
TEST_REAL_SIMILAR(double(mi.getMetaValue("cluster_id")), double(mi3.getMetaValue("cluster_id")))
// test if a deep copy was done
mi3.setMetaValue("cluster_id", 11.9);
TEST_REAL_SIMILAR(double(mi.getMetaValue("cluster_id")), 4712.12)
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")), 11.9)
}
END_SECTION
START_SECTION((MetaInfoInterface& operator=(const MetaInfoInterface& rhs)))
{
//test if copy worked
MetaInfoInterface mi3,mi4;
mi3 = mi;
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")),double(mi.getMetaValue("cluster_id")))
//test if a deep copy was done
mi3.setMetaValue("cluster_id",11.9);
TEST_REAL_SIMILAR(double(mi.getMetaValue("cluster_id")),4712.12)
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")),11.9)
//test what happens when left side is not empty
mi3 = mi;
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")),double(mi.getMetaValue("cluster_id")))
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")), 4712.12)
//test if a deep copy was done
mi3.setMetaValue("cluster_id",11.9);
TEST_REAL_SIMILAR(double(mi.getMetaValue("cluster_id")),double(mi.getMetaValue("cluster_id")))
TEST_REAL_SIMILAR(double(mi.getMetaValue("cluster_id")),4712.12)
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")),11.9)
//test what happens when source is empty
mi3 = mi4;
TEST_EQUAL(mi3.isMetaEmpty(),true)
}
END_SECTION
START_SECTION((MetaInfoInterface& operator=(MetaInfoInterface&& rhs)))
{
// Ensure that MetaInfoInterface has a no-except move assignment operator.
TEST_EQUAL(noexcept(declval<MetaInfoInterface&>() = declval<MetaInfoInterface &&>()), true)
MetaInfoInterface mi3, mi4;
MetaInfoInterface example(mi);
mi3 = std::move(example);
// test if move worked
TEST_EQUAL(mi3.metaValueExists("cluster_id"), true);
TEST_EQUAL(example.metaValueExists("cluster_id"), false);
TEST_EQUAL(example.isMetaEmpty(), true);
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")), double(mi.getMetaValue("cluster_id")))
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")), 4712.12)
// test if a deep copy was done
mi3.setMetaValue("cluster_id", 11.9);
TEST_REAL_SIMILAR(double(mi.getMetaValue("cluster_id")), 4712.12)
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")), 11.9)
// test what happens when left side is not empty
example = mi;
mi3 = std::move(example);
TEST_EQUAL(mi3.metaValueExists("cluster_id"), true);
TEST_EQUAL(example.metaValueExists("cluster_id"), false);
TEST_EQUAL(example.isMetaEmpty(), true);
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")), double(mi.getMetaValue("cluster_id")))
// test if a deep copy was done
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")), 4712.12)
mi3.setMetaValue("cluster_id", 11.9);
TEST_REAL_SIMILAR(double(mi.getMetaValue("cluster_id")), double(mi.getMetaValue("cluster_id")))
TEST_REAL_SIMILAR(double(mi3.getMetaValue("cluster_id")), 11.9)
// test what happens when source is empty
mi3 = std::move(example);
TEST_EQUAL(mi3.isMetaEmpty(), true)
TEST_EQUAL(example.isMetaEmpty(), true)
}
END_SECTION
START_SECTION((void getKeys(std::vector<String>& keys) const))
vector<String> tmp,tmp2;
tmp.push_back("cluster_id");
tmp.push_back("testname");
mi.getKeys(tmp2);
TEST_EQUAL(tmp2.size(),tmp.size())
TEST_EQUAL(tmp2[0],tmp[0])
TEST_EQUAL(tmp2[1],tmp[1])
MetaInfoInterface mi2(mi);
mi2.getKeys(tmp2);
TEST_EQUAL(tmp2.size(),tmp.size())
TEST_EQUAL(tmp2[0],tmp[0])
TEST_EQUAL(tmp2[1],tmp[1])
mi2.metaRegistry().registerName("a","test");
mi2.metaRegistry().registerName("d","test");
mi2.metaRegistry().registerName("x","test");
mi2.setMetaValue("a",1);
mi2.setMetaValue("d",1);
mi2.setMetaValue("x",1);
mi2.getKeys(tmp2);
tmp.clear();
tmp.push_back("cluster_id");
tmp.push_back("testname");
tmp.push_back("a");
tmp.push_back("d");
tmp.push_back("x");
TEST_EQUAL(tmp2.size(),tmp.size())
TEST_EQUAL(tmp2[0],tmp[0])
TEST_EQUAL(tmp2[1],tmp[1])
TEST_EQUAL(tmp2[2],tmp[2])
TEST_EQUAL(tmp2[3],tmp[3])
TEST_EQUAL(tmp2[4],tmp[4])
END_SECTION
START_SECTION((void getKeys(std::vector< UInt > &keys) const))
MetaInfoInterface mi;
mi.setMetaValue("label",String("tag"));
mi.setMetaValue("icon",String("kreis"));
vector<UInt> vec;
mi.getKeys(vec);
TEST_EQUAL(vec.size(),2)
TEST_EQUAL(vec[0],3)
TEST_EQUAL(vec[1],4)
mi.metaRegistry().registerName("a","test");
mi.metaRegistry().registerName("d","test");
mi.metaRegistry().registerName("x","test");
mi.setMetaValue("a",1);
mi.setMetaValue("d",1);
mi.setMetaValue("x",1);
mi.getKeys(vec);
TEST_EQUAL(vec.size(),5)
TEST_EQUAL(vec[0],3)
TEST_EQUAL(vec[1],4)
TEST_EQUAL(vec[2],1025)
TEST_EQUAL(vec[3],1026)
TEST_EQUAL(vec[4],1027)
END_SECTION
START_SECTION((bool metaValueExists(const String& name) const))
MetaInfoInterface mi4;
TEST_EQUAL(mi4.metaValueExists("cluster_id"),false)
mi4.setMetaValue("cluster_id",4712.1234);
TEST_EQUAL(mi4.metaValueExists("cluster_id"),true)
END_SECTION
START_SECTION((bool metaValueExists(UInt index) const))
MetaInfoInterface mi4;
TEST_EQUAL(mi4.metaValueExists(2),false)
mi4.setMetaValue("cluster_id",4712.1234);
TEST_EQUAL(mi4.metaValueExists(2),true)
END_SECTION
START_SECTION(([EXTRA] void getKeys(std::vector<String>& keys) const))
std::vector<String> keys;
mi.getKeys(keys);
TEST_EQUAL(keys.size(),2)
TEST_EQUAL(keys[0],"cluster_id")
TEST_EQUAL(keys[1],"testname")
END_SECTION
START_SECTION((void clearMetaInfo()))
MetaInfoInterface i;
TEST_EQUAL(i.isMetaEmpty(),true)
i.setMetaValue("label",String("test"));
TEST_EQUAL(i.isMetaEmpty(),false)
i.clearMetaInfo();
TEST_EQUAL(i.isMetaEmpty(),true)
END_SECTION
START_SECTION((bool operator== (const MetaInfoInterface& rhs) const))
MetaInfoInterface i,i2;
TEST_EQUAL(i==i2,true)
TEST_EQUAL(i2==i,true)
i.setMetaValue("label",String("test"));
TEST_EQUAL(i==i2,false)
TEST_EQUAL(i2==i,false)
i2.setMetaValue("label",String("test"));
TEST_EQUAL(i==i2,true)
TEST_EQUAL(i2==i,true)
END_SECTION
START_SECTION((bool operator!= (const MetaInfoInterface& rhs) const))
MetaInfoInterface i,i2;
TEST_EQUAL(i!=i2,false)
TEST_EQUAL(i2!=i,false)
i.setMetaValue("label",String("test"));
TEST_EQUAL(i!=i2,true)
TEST_EQUAL(i2!=i,true)
i2.setMetaValue("label",String("test"));
TEST_EQUAL(i!=i2,false)
TEST_EQUAL(i2!=i,false)
END_SECTION
START_SECTION((void removeMetaValue(UInt index)))
MetaInfoInterface i,i2;
i.setMetaValue(1,String("bla"));
TEST_EQUAL(i==i2,false)
i.removeMetaValue(1);
TEST_EQUAL(i==i2,true)
//try if removing a non-existing value works as well
i.removeMetaValue(1234);
END_SECTION
START_SECTION((void removeMetaValue(const String& name)))
MetaInfoInterface i,i2;
i.setMetaValue("label",String("bla"));
TEST_EQUAL(i==i2,false)
i.removeMetaValue("label");
TEST_EQUAL(i==i2,true)
//try if removing a non-existing value works as well
i.removeMetaValue("icon");
END_SECTION
START_SECTION((void addMetaValues(const MetaInfoInterface& from)))
MetaInfoInterface m_new, m_base;
m_base.setMetaValue("label", String("old"));
m_base.setMetaValue("exists_no_overwrite", 5.2);
m_new.setMetaValue("label", String("new")); // will be overwritten
m_new.setMetaValue("icon", 4.3); // will be added
m_base.addMetaValues(m_new);
TEST_EQUAL(m_base.getMetaValue("label"), String("new"));
TEST_EQUAL(m_base.getMetaValue("icon"), 4.3);
TEST_EQUAL(m_base.getMetaValue("exists_no_overwrite"), 5.2);
END_SECTION
START_SECTION((void swap(MetaInfoInterface&& rhs)))
{
MetaInfoInterface mi1, mi2;
mi1.setMetaValue("a", 1);
mi2.setMetaValue("b", 2);
mi1.swap(mi2);
TEST_EQUAL(mi1.metaValueExists("a"), false);
TEST_EQUAL(mi2.metaValueExists("b"), false);
TEST_EQUAL(mi1.getMetaValue("b"), 2);
TEST_EQUAL(mi2.getMetaValue("a"), 1);
}
END_SECTION
START_SECTION((MetaInfoConstIterator metaBegin() const))
{
// Test with empty meta info (null meta_)
MetaInfoInterface mi_empty;
TEST_EQUAL(mi_empty.metaBegin() == mi_empty.metaEnd(), true)
// Test with non-empty meta info
MetaInfoInterface mi_filled;
mi_filled.setMetaValue("test_key", 42);
TEST_EQUAL(mi_filled.metaBegin() != mi_filled.metaEnd(), true)
TEST_EQUAL(mi_filled.metaBegin()->second, DataValue(42))
}
END_SECTION
START_SECTION((MetaInfoConstIterator metaEnd() const))
NOT_TESTABLE // tested with metaBegin()
END_SECTION
START_SECTION((Size metaSize() const))
{
// Test with null meta_
MetaInfoInterface mi_empty;
TEST_EQUAL(mi_empty.metaSize(), 0)
// Test with non-null meta_
MetaInfoInterface mi_filled;
mi_filled.setMetaValue("key1", 1);
TEST_EQUAL(mi_filled.metaSize(), 1)
mi_filled.setMetaValue("key2", 2);
TEST_EQUAL(mi_filled.metaSize(), 2)
mi_filled.removeMetaValue("key1");
TEST_EQUAL(mi_filled.metaSize(), 1)
mi_filled.clearMetaInfo();
TEST_EQUAL(mi_filled.metaSize(), 0)
}
END_SECTION
START_SECTION([EXTRA] Range-based for loop iteration via iterators)
{
MetaInfoInterface mi_iter;
mi_iter.setMetaValue("a", 1);
mi_iter.setMetaValue("b", 2);
mi_iter.setMetaValue("c", 3);
int count = 0;
for (auto it = mi_iter.metaBegin(); it != mi_iter.metaEnd(); ++it)
{
++count;
TEST_EQUAL(it->second.valueType() == DataValue::INT_VALUE, true)
}
TEST_EQUAL(count, 3)
}
END_SECTION
START_SECTION([EXTRA] addMetaValues with empty source)
{
MetaInfoInterface m_base, m_empty;
m_base.setMetaValue("key", 1);
// Adding empty to non-empty should not change anything
m_base.addMetaValues(m_empty);
TEST_EQUAL(m_base.metaSize(), 1)
TEST_EQUAL(m_base.getMetaValue("key"), DataValue(1))
// Adding non-empty to empty
MetaInfoInterface m_new;
m_new.addMetaValues(m_base);
TEST_EQUAL(m_new.metaSize(), 1)
TEST_EQUAL(m_new.getMetaValue("key"), DataValue(1))
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/FIAMSScheduler_test.cpp | .cpp | 1,996 | 67 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Svetlana Kutuzova, Douglas McCloskey $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/ID/FIAMSScheduler.h>
#include <OpenMS/SYSTEM/File.h>
#include <QDir>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(FIAMSScheduler, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
FIAMSScheduler* ptr_1 = nullptr;
FIAMSScheduler* null_ptr_2 = nullptr;
START_SECTION(FIAMSScheduler())
{
ptr_1 = new FIAMSScheduler(
String(OPENMS_GET_TEST_DATA_PATH("FIAMS_input/params_test.csv"))
);
TEST_NOT_EQUAL(ptr_1, null_ptr_2);
TEST_EQUAL(ptr_1->getBaseDir(), "/");
}
END_SECTION
START_SECTION(virtual ~FIAMSScheduler())
{
delete ptr_1;
}
END_SECTION
START_SECTION(FIAMSScheduler)
{
QDir d;
String tmp_dir = d.currentPath().toStdString() + "/"; // write output to current directory
FIAMSScheduler fia_scheduler(
String(OPENMS_GET_TEST_DATA_PATH("FIAMS_input/params_test.csv")),
String(OPENMS_GET_TEST_DATA_PATH("")),
tmp_dir
);
const vector<map<String, String>> samples = fia_scheduler.getSamples();
TEST_EQUAL(samples[0].at("time"), "10");
fia_scheduler.run();
String outfile = String(OPENMS_GET_TEST_DATA_PATH("FIAMS_output/SerumTest_10.mzTab"));
String outfile2 = tmp_dir + "FIAMS_output/SerumTest_10.mzTab";
TEST_FILE_EQUAL(outfile2.c_str(), outfile.c_str());
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST | C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/QCBase_test.cpp | .cpp | 2,252 | 85 | // 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/QC/QCBase.h>
#include <OpenMS/KERNEL/MSExperiment.h>
///////////////////////////
using namespace OpenMS;
START_TEST(SpectraMap, "$Id$")
QCBase::SpectraMap* ptr = nullptr;
QCBase::SpectraMap* nulpt = nullptr;
START_SECTION(QCBase::SpectraMap())
{
ptr = new QCBase::SpectraMap();
TEST_NOT_EQUAL(ptr, nulpt)
}
END_SECTION
START_SECTION(~QCBase::SpectraMap())
{
delete ptr;
}
END_SECTION
MSExperiment exp;
MSSpectrum spec1;
spec1.setNativeID("XTandem::0");
MSSpectrum spec2;
spec2.setNativeID("XTandem::1");
MSSpectrum spec3;
spec3.setNativeID("XTandem::2");
exp.setSpectra({spec1,spec2,spec3});
START_SECTION(QCBase::SpectraMap::calculateMap(const MSExperiment& exp))
QCBase::SpectraMap spec_map;
spec_map.calculateMap(exp);
ABORT_IF(spec_map.size() != 3);
TEST_EQUAL(spec_map.at("XTandem::0"), 0);
TEST_EQUAL(spec_map.at("XTandem::1"), 1);
TEST_EQUAL(spec_map.at("XTandem::2"), 2);
TEST_EXCEPTION(Exception::ElementNotFound, spec_map.at("XTandem::15"));
END_SECTION
START_SECTION(QCBase::SpectraMap::SpectraMap(const MSExperiment& exp))
QCBase::SpectraMap spec_map(exp);
TEST_EQUAL(spec_map.size(), 3);
END_SECTION
START_SECTION(QCBase::SpectraMap::empty())
QCBase::SpectraMap spec_map;
TEST_EQUAL(spec_map.empty(),true);
END_SECTION
START_SECTION(QCBase::SpectraMap::clear())
QCBase::SpectraMap spec_map;
spec_map.calculateMap(exp);
TEST_EQUAL(spec_map.empty(),false);
spec_map.clear();
TEST_EQUAL(spec_map.empty(),true);
END_SECTION
START_SECTION(QCBase::SpectraMap::at(const String& identifier))
NOT_TESTABLE;
END_SECTION
START_SECTION(QCBase::SpectraMap::size())
NOT_TESTABLE;
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/GzipInputStream_test.cpp | .cpp | 3,054 | 90 | // 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/GzipInputStream.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <xercesc/util/PlatformUtils.hpp>
using namespace OpenMS;
///////////////////////////
START_TEST(GzipInputStream, "$Id$")
xercesc::XMLPlatformUtils::Initialize();
GzipInputStream* ptr = nullptr;
GzipInputStream* nullPointer = nullptr;
START_SECTION(GzipInputStream(const char *const file_name))
TEST_EXCEPTION(Exception::FileNotFound, GzipInputStream gzip2(OPENMS_GET_TEST_DATA_PATH("ThisFileDoesNotExist")))
ptr = new GzipInputStream(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1.gz"));
TEST_NOT_EQUAL(ptr, nullPointer)
TEST_EQUAL(ptr->getIsOpen(),true)
END_SECTION
START_SECTION((~GzipInputStream()))
delete ptr;
END_SECTION
START_SECTION(GzipInputStream(const String& file_name))
TEST_EXCEPTION(Exception::FileNotFound, GzipInputStream gzip2(OPENMS_GET_TEST_DATA_PATH("ThisFileDoesNotExist")))
String filename(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1.gz"));
ptr = new GzipInputStream(filename);
TEST_NOT_EQUAL(ptr, nullPointer)
TEST_EQUAL(ptr->getIsOpen(),true)
delete ptr;
END_SECTION
START_SECTION(virtual XMLSize_t readBytes(XMLByte *const to_fill, const XMLSize_t max_to_read))
GzipInputStream gzip(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1.gz"));
char buffer[31];
buffer[30] = buffer[29] = '\0';
XMLByte* xml_buffer = reinterpret_cast<XMLByte* >(buffer);
TEST_EQUAL(gzip.getIsOpen(),true)
TEST_EQUAL(gzip.readBytes(xml_buffer,(XMLSize_t)10),10)
TEST_EQUAL(gzip.readBytes(&xml_buffer[10],(XMLSize_t)10),10)
TEST_EQUAL(gzip.readBytes(&xml_buffer[20],(XMLSize_t)9),9)
TEST_EQUAL(String(buffer), String("Was decompression successful?"))
TEST_EQUAL(gzip.getIsOpen(),true)
TEST_EQUAL(gzip.readBytes(&xml_buffer[30],(XMLSize_t)10),1)
TEST_EQUAL(gzip.getIsOpen(),false)
END_SECTION
START_SECTION(XMLFilePos curPos() const)
GzipInputStream gzip(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1.gz"));
TEST_EQUAL(gzip.curPos(), 0)
char buffer[31];
buffer[30] = buffer[29] = '\0';
XMLByte* xml_buffer = reinterpret_cast<XMLByte* >(buffer);
gzip.readBytes(xml_buffer,(XMLSize_t)10);
TEST_EQUAL(gzip.curPos(),10)
END_SECTION
START_SECTION(bool getIsOpen() const )
//test above
NOT_TESTABLE
END_SECTION
START_SECTION(virtual const XMLCh* getContentType() const )
GzipInputStream gzip2(OPENMS_GET_TEST_DATA_PATH("GzipIfStream_1.gz"));
XMLCh* xmlch_nullPointer = nullptr;
TEST_EQUAL(gzip2.getContentType(),xmlch_nullPointer)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/DPeak_test.cpp | .cpp | 1,318 | 57 | // 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/DPeak.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(DPeak<D>, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
DPeak<1>::Type* ptr1 = nullptr;
DPeak<1>::Type* nullPointer1 = nullptr;
START_SECTION(DPeak())
{
ptr1 = new DPeak<1>::Type();
TEST_NOT_EQUAL(ptr1, nullPointer1);
}
END_SECTION
START_SECTION(~DPeak())
{
delete ptr1;
}
END_SECTION
DPeak<2>::Type* ptr2 = nullptr;
DPeak<2>::Type* nullPointer2 = nullptr;
START_SECTION([EXTRA]DPeak())
{
ptr2 = new DPeak<2>::Type();
TEST_NOT_EQUAL(ptr2, nullPointer2);
}
END_SECTION
START_SECTION([EXTRA]~DPeak())
{
delete ptr2;
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ExternalProcess_test.cpp | .cpp | 3,988 | 115 | // 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/SYSTEM/ExternalProcess.h>
///////////////////////////
#include <OpenMS/config.h>
using namespace OpenMS;
using namespace std;
// we just need ANY commandline tool available on (hopefully) all boxes.
// note that commands like "dir" or "type" are only known within cmd.exe and are not actual executables (unlike on Linux)
#ifdef OPENMS_WINDOWSPLATFORM
const QString exe = "cmd";
const QStringList args = QStringList() << "/C" << "echo hi";
const QStringList args_broken = QStringList() << "/C" << "doesnotexist";
#else
const QString exe = "ls";
const QStringList args("-l");
const QStringList args_broken = QStringList() << "-0";
#endif //
START_TEST(ExternalProcess, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION(ExternalProcess())
NOT_TESTABLE; // tested below
END_SECTION
START_SECTION(ExternalProcess(std::function<void(const String&)> callbackStdOut, std::function<void(const String&)> callbackStdErr))
NOT_TESTABLE; // tested below
END_SECTION
START_SECTION(~ExternalProcess())
NOT_TESTABLE; // tested below
END_SECTION
START_SECTION(void setCallbacks(std::function<void(const String&)> callbackStdOut, std::function<void(const String&)> callbackStdErr))
NOT_TESTABLE; // tested below
END_SECTION
START_SECTION(RETURNSTATE run(const QString& exe, const QStringList& args, const QString& working_dir, const bool verbose, String& error_msg))
{
String error_msg;
{ // without callbacks
ExternalProcess ep;
String error_msg;
auto r = ep.run(exe, args, "", true, error_msg);
TEST_EQUAL(r, ExternalProcess::RETURNSTATE::SUCCESS)
TEST_EQUAL(error_msg.size(), 0)
r = ep.run("this_exe_does_not_exist", args, "", true, error_msg);
TEST_EQUAL(r,ExternalProcess::RETURNSTATE::FAILED_TO_START)
TEST_NOT_EQUAL(error_msg.size(), 0);
r = ep.run(exe, args_broken, "", true, error_msg);
TEST_EQUAL(r, ExternalProcess::RETURNSTATE::NONZERO_EXIT)
TEST_NOT_EQUAL(error_msg.size(), 0);
}
{ // with callbacks
String all_out, all_err;
auto l_out = [&](const String& out) {all_out += out;};
auto l_err = [&](const String& out) {all_err += out;};
ExternalProcess ep(l_out, l_err);
auto r = ep.run(exe, args, "", true, error_msg);
TEST_EQUAL(r, ExternalProcess::RETURNSTATE::SUCCESS)
TEST_EQUAL(error_msg.size(), 0);
TEST_NOT_EQUAL(all_out.size(), 0)
TEST_EQUAL(all_err.size(), 0)
all_out.clear();
all_err.clear();
r = ep.run(exe, args_broken, "", false, error_msg);
TEST_EQUAL(r, ExternalProcess::RETURNSTATE::NONZERO_EXIT)
TEST_NOT_EQUAL(error_msg.size(), 0);
TEST_EQUAL(all_out.size(), 0)
std::cout << all_out << "\n\n";
TEST_NOT_EQUAL(all_err.size(), 0)
all_out.clear();
all_err.clear();
ep.setCallbacks(l_err, l_out); // swap callbacks
r = ep.run(exe, args_broken, "", false, error_msg);
TEST_EQUAL(r, ExternalProcess::RETURNSTATE::NONZERO_EXIT)
TEST_NOT_EQUAL(error_msg.size(), 0);
TEST_NOT_EQUAL(all_out.size(), 0)
TEST_EQUAL(all_err.size(), 0)
all_out.clear();
all_err.clear();
}
}
END_SECTION
START_SECTION(ExternalProcess::RETURNSTATE run(QWidget* parent, const QString& exe, const QStringList& args, const QString& working_dir, const bool verbose = false))
NOT_TESTABLE // tested above..
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/QcMLFile_test.cpp | .cpp | 7,847 | 324 | // 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/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/QcMLFile.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(QcMLFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
QcMLFile* ptr = 0;
QcMLFile* null_ptr = 0;
START_SECTION(QcMLFile())
{
ptr = new QcMLFile();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~QcMLFile())
{
delete ptr;
}
END_SECTION
START_SECTION((~QcMLFile()))
{
// uh, twice?! No!
}
END_SECTION
QcMLFile qcmlfile;
qcmlfile.registerRun("123","testrun1");
qcmlfile.registerRun("456","testrun2");
START_SECTION((void registerRun(const String id, const String name)))
{
QcMLFile qcmlfile1;
qcmlfile1.registerRun("abc","somerun");
TEST_EQUAL(qcmlfile1.existsRun("abc"), true)
TEST_EQUAL(qcmlfile1.existsRun("somerun",true), true)
}
END_SECTION
START_SECTION((void registerSet(const String id, const String name, const std::set< String > &names)))
{
QcMLFile qcmlfile1;
std::set<String> n;
n.insert("somerun1");
n.insert("somerun2");
qcmlfile1.registerSet("def","someset", n);
TEST_EQUAL(qcmlfile1.existsSet("def"), true)
TEST_EQUAL(qcmlfile1.existsSet("someset",true), true)
}
END_SECTION
START_SECTION((void addRunQualityParameter(String r, QualityParameter qp)))
NOT_TESTABLE
END_SECTION
START_SECTION((void addRunAttachment(String r, Attachment at)))
NOT_TESTABLE
END_SECTION
START_SECTION((void addSetQualityParameter(String r, QualityParameter qp)))
NOT_TESTABLE
END_SECTION
START_SECTION((void addSetAttachment(String r, Attachment at)))
NOT_TESTABLE
END_SECTION
START_SECTION((void removeAttachment(String r, std::vector< String > &ids, String at="")))
NOT_TESTABLE
END_SECTION
START_SECTION((void removeAttachment(String r, String at)))
NOT_TESTABLE
END_SECTION
START_SECTION((void removeAllAttachments(String at)))
NOT_TESTABLE
END_SECTION
START_SECTION((void removeQualityParameter(String r, std::vector< String > &ids)))
NOT_TESTABLE
END_SECTION
START_SECTION((void merge(const QcMLFile &addendum, String setname="")))
NOT_TESTABLE
END_SECTION
START_SECTION((void collectSetParameter(const String setname, const String qp, std::vector< String > &ret)))
NOT_TESTABLE
END_SECTION
START_SECTION((String exportAttachment(const String filename, const String qpname) const ))
NOT_TESTABLE
END_SECTION
START_SECTION((String exportQP(const String filename, const String qpname) const ))
NOT_TESTABLE
END_SECTION
START_SECTION((String exportQPs(const String filename, const StringList qpnames) const ))
NOT_TESTABLE
END_SECTION
START_SECTION((String map2csv(const std::map< String, std::map< String, String > > &cvs_table, const String &separator) const ))
NOT_TESTABLE
END_SECTION
START_SECTION((String exportIDstats(const String &filename) const ))
NOT_TESTABLE
END_SECTION
START_SECTION((void getRunIDs(std::vector< String > &ids) const ))
{
std::vector< String > ids, test;
test.push_back("123");
test.push_back("456");
qcmlfile.getRunIDs(ids);
TEST_EQUAL(StringList(ids),StringList(test))
}
END_SECTION
START_SECTION((void getRunNames(std::vector< String > &ids) const ))
{
std::vector< String > ids, test;
test.push_back("testrun1");
test.push_back("testrun2");
qcmlfile.getRunNames(ids);
TEST_EQUAL(ids==test,true)
}
END_SECTION
START_SECTION((bool existsRun(const String filename, bool checkname=false) const ))
{
QcMLFile qcmlfile1;
qcmlfile.registerRun("abc","somerun");
TEST_EQUAL(qcmlfile.existsRun("abc"), true)
TEST_EQUAL(qcmlfile.existsRun("somerun",true), true)
}
END_SECTION
START_SECTION((bool existsSet(const String filename, bool checkname=false) const ))
NOT_TESTABLE
END_SECTION
START_SECTION((void existsRunQualityParameter(const String filename, const String qpname, std::vector< String > &ids) const ))
NOT_TESTABLE
END_SECTION
START_SECTION((void existsSetQualityParameter(const String filename, const String qpname, std::vector< String > &ids) const ))
NOT_TESTABLE
END_SECTION
START_SECTION((void store(const String &filename) const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((void load(const String &filename)))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([QcMLFile::Attachment] Attachment()))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([QcMLFile::Attachment] Attachment(const Attachment &rhs)))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([QcMLFile::Attachment] Attachment& operator=(const Attachment &rhs)))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([QcMLFile::Attachment] bool operator==(const Attachment &rhs) const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([QcMLFile::Attachment] bool operator<(const Attachment &rhs) const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([QcMLFile::Attachment] bool operator>(const Attachment &rhs) const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([QcMLFile::Attachment] String toXMLString(UInt indentation_level) const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([QcMLFile::Attachment] String toCSVString(String separator) const ))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(([QcMLFile::QualityParameter] QualityParameter()))
NOT_TESTABLE
END_SECTION
START_SECTION(([QcMLFile::QualityParameter] QualityParameter(const QualityParameter &rhs)))
{
QcMLFile::QualityParameter qp1;
qp1.name = "somename"; ///< Name
qp1.id = "id"; ///< Identifier
qp1.cvRef = "MS"; ///< cv reference
qp1.cvAcc = "MS:1000577";
qp1.value = "somevalue";
QcMLFile::QualityParameter qp2 = QcMLFile::QualityParameter(qp1);
TEST_EQUAL(qp1.name, qp2.name)
TEST_EQUAL(qp1.id, qp2.id)
TEST_EQUAL(qp1.value, qp2.value)
}
END_SECTION
START_SECTION(([QcMLFile::QualityParameter] QualityParameter& operator=(const QualityParameter &rhs)))
{
QcMLFile::QualityParameter qp1;
qp1.name = "somename"; ///< Name
qp1.id = "id"; ///< Identifier
qp1.cvRef = "MS"; ///< cv reference
qp1.cvAcc = "MS:1000577";
qp1.value = "somevalue";
QcMLFile::QualityParameter qp2 = QcMLFile::QualityParameter(qp1);
qp2.name = "someothername"; ///< Name
qp2.id = "otherid"; ///< Identifier
qp2.cvRef = "MS"; ///< cv reference
qp2.cvAcc = "MS:1000577";
qp2.value = "someothervalue";
qp2 = qp1;
TEST_EQUAL(qp1.name, qp2.name)
TEST_EQUAL(qp1.id, qp2.id)
TEST_EQUAL(qp1.value, qp2.value)
}
END_SECTION
START_SECTION(([QcMLFile::QualityParameter] bool operator==(const QualityParameter &rhs) const ))
{
QcMLFile::QualityParameter qp1;
qp1.name = "somename"; ///< Name
QcMLFile::QualityParameter qp2 = QcMLFile::QualityParameter(qp1);
TEST_TRUE(qp1 == qp2)
}
END_SECTION
START_SECTION(([QcMLFile::QualityParameter] bool operator<(const QualityParameter &rhs) const ))
{
QcMLFile::QualityParameter qp1;
qp1.name = "somename"; ///< Name
QcMLFile::QualityParameter qp2;
qp2.name = "tomename"; ///< Name
TEST_EQUAL(qp1<qp2, true)
}
END_SECTION
START_SECTION(([QcMLFile::QualityParameter] bool operator>(const QualityParameter &rhs) const ))
{
QcMLFile::QualityParameter qp1;
qp1.name = "somename"; ///< Name
QcMLFile::QualityParameter qp2;
qp2.name = "romename"; ///< Name
TEST_EQUAL(qp1>qp2, true)
}
END_SECTION
START_SECTION(([QcMLFile::QualityParameter] String toXMLString(UInt indentation_level) const ))
{
NOT_TESTABLE
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/SeedListGenerator_test.cpp | .cpp | 4,376 | 147 | // 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 <map>
///////////////////////////
#include <OpenMS/FEATUREFINDER/SeedListGenerator.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(SeedListGenerator, "$Id$")
/////////////////////////////////////////////////////////////
SeedListGenerator* slg_ptr = nullptr;
SeedListGenerator* slg_nullPointer = nullptr;
START_SECTION((SeedListGenerator()))
{
slg_ptr = new SeedListGenerator();
TEST_NOT_EQUAL(slg_ptr, slg_nullPointer);
}
END_SECTION
START_SECTION(([EXTRA] ~SeedListGenerator()))
{
delete slg_ptr;
}
END_SECTION
START_SECTION((void generateSeedList(const PeakMap& experiment, SeedList& seeds)))
{
PeakMap experiment;
String path = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test.mzML");
MzMLFile().load(path, experiment);
SeedListGenerator::SeedList seeds;
SeedListGenerator().generateSeedList(experiment, seeds);
TEST_EQUAL(seeds.size(), 9);
TEST_EQUAL(seeds[0], DPosition<2>(0.5927, 538.605));
TEST_EQUAL(seeds[1], DPosition<2>(0.5927, 637.885));
TEST_EQUAL(seeds[2], DPosition<2>(0.5927, 678.384));
// ...
TEST_EQUAL(seeds[8], DPosition<2>(3.7572, 512.784));
}
END_SECTION
START_SECTION((void generateSeedList(PeptideIdentificationList& peptides, SeedList& seeds, bool use_peptide_mass = false)))
{
PeptideIdentificationList peptides(3);
peptides[0].setRT(1.1);
peptides[0].setMZ(111.111);
peptides[1].setRT(2.2);
peptides[1].setMZ(222.222);
peptides[2].setRT(3.3);
peptides[2].setMZ(333.333);
SeedListGenerator::SeedList seeds;
SeedListGenerator().generateSeedList(peptides, seeds);
TEST_EQUAL(seeds.size(), 3);
TEST_EQUAL(seeds[0], DPosition<2>(1.1, 111.111));
TEST_EQUAL(seeds[1], DPosition<2>(2.2, 222.222));
TEST_EQUAL(seeds[2], DPosition<2>(3.3, 333.333));
PeptideHit hit;
hit.setSequence(AASequence::fromString("TEST"));
hit.setCharge(2);
peptides[0].insertHit(hit);
peptides.resize(1);
SeedListGenerator().generateSeedList(peptides, seeds, true);
TEST_EQUAL(seeds.size(), 1);
TEST_REAL_SIMILAR(seeds[0][1], 219.09755);
}
END_SECTION
START_SECTION((void generateSeedLists(const ConsensusMap& consensus, Map<UInt64, SeedList>& seed_lists)))
{
ConsensusMap consensus;
String path = OPENMS_GET_TEST_DATA_PATH("ConsensusXMLFile_1.consensusXML");
ConsensusXMLFile().load(path, consensus);
std::map<UInt64, SeedListGenerator::SeedList> seed_lists;
SeedListGenerator().generateSeedLists(consensus, seed_lists);
TEST_EQUAL(seed_lists.size(), 2);
TEST_EQUAL(seed_lists[0].size(), 0);
TEST_EQUAL(seed_lists[1].size(), 2);
TEST_EQUAL(seed_lists[1][0], DPosition<2>(1273.27, 904.47));
TEST_EQUAL(seed_lists[1][1], DPosition<2>(1184.46, 953.368));
}
END_SECTION
START_SECTION((void convertSeedList(const SeedList& seeds, FeatureMap& features)))
{
SeedListGenerator::SeedList seeds(3);
seeds[0] = DPosition<2>(1.1, 111.111);
seeds[1] = DPosition<2>(2.2, 222.222);
seeds[2] = DPosition<2>(3.3, 333.333);
FeatureMap features;
SeedListGenerator().convertSeedList(seeds, features);
TEST_EQUAL(features.size(), 3);
TEST_EQUAL(features[0].getRT(), 1.1);
TEST_EQUAL(features[0].getMZ(), 111.111);
TEST_EQUAL(features[1].getRT(), 2.2);
TEST_EQUAL(features[1].getMZ(), 222.222);
TEST_EQUAL(features[2].getRT(), 3.3);
TEST_EQUAL(features[2].getMZ(), 333.333);
}
END_SECTION
START_SECTION((void convertSeedList(const FeatureMap& features, SeedList& seeds)))
{
FeatureMap features;
features.resize(3);
features[0].setRT(1.1);
features[0].setMZ(111.111);
features[1].setRT(2.2);
features[1].setMZ(222.222);
features[2].setRT(3.3);
features[2].setMZ(333.333);
SeedListGenerator::SeedList seeds;
SeedListGenerator().convertSeedList(features, seeds);
TEST_EQUAL(seeds.size(), 3);
TEST_EQUAL(seeds[0], DPosition<2>(1.1, 111.111));
TEST_EQUAL(seeds[1], DPosition<2>(2.2, 222.222));
TEST_EQUAL(seeds[2], DPosition<2>(3.3, 333.333));
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/PrecursorCorrection_test.cpp | .cpp | 10,903 | 365 | // 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/PROCESSING/CALIBRATION/PrecursorCorrection.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/CONCEPT/FuzzyStringComparator.h>
#include <OpenMS/DATASTRUCTURES/ConvexHull2D.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(PrecursorCorrection, "$Id$")
/////////////////////////////////////////////////////////////
// Prepare dummy data
MSExperiment exp;
vector<Precursor> v_precursor_1, v_precursor_2, v_precursor_3;
Precursor precursor_1, precursor_2, precursor_3;
MSSpectrum ms1_spectrum_1, ms1_spectrum_2, ms1_spectrum_3, ms2_spectrum_1, ms2_spectrum_2, ms2_spectrum_3;
vector<MSSpectrum> v_spectra;
// precursor
precursor_1.setIntensity(240.0f);
precursor_1.setMZ(509.9999);
v_precursor_1.push_back(precursor_1);
precursor_2.setIntensity(230.0f);
precursor_2.setMZ(610.0001);
precursor_2.setCharge(1);
v_precursor_2.push_back(precursor_2);
precursor_3.setIntensity(220.0f);
precursor_3.setMZ(611.0035);
precursor_3.setCharge(1);
v_precursor_3.push_back(precursor_3);
// peaks
Peak1D p1;
p1.setIntensity(200.0f);
p1.setMZ(509.9994);
Peak1D p2;
p2.setIntensity(250.0f);
p2.setMZ(510.0000);
Peak1D p3;
p3.setIntensity(150.0f);
p3.setMZ(510.0001);
Peak1D p4;
p4.setIntensity(250.0f);
p4.setMZ(609.9998);
Peak1D p5;
p5.setIntensity(200.0f);
p5.setMZ(610.0000);
Peak1D p6;
p6.setIntensity(180.0f);
p6.setMZ(610.0005);
Peak1D p7;
p7.setIntensity(250.0f);
p7.setMZ(611.0031);
Peak1D p8;
p8.setIntensity(200.0f);
p8.setMZ(611.0033);
Peak1D p9;
p9.setIntensity(180.0f);
p9.setMZ(611.0038);
vector<Peak1D> peaks_1{p1,p2,p3};
vector<Peak1D> peaks_2{p4,p5,p6};
vector<Peak1D> peaks_3{p7,p8,p9};
vector<Peak1D> empty_peaks{};
// ms1
ms1_spectrum_1.insert(ms1_spectrum_1.begin(), peaks_1.begin(), peaks_1.end());
ms1_spectrum_1.setMSLevel(1);
ms1_spectrum_1.setNativeID("scan=1");
ms1_spectrum_1.setRT(100.0);
ms1_spectrum_2.insert(ms1_spectrum_2.begin(), peaks_2.begin(), peaks_2.end());
ms1_spectrum_2.setMSLevel(1);
ms1_spectrum_2.setNativeID("scan=3");
ms1_spectrum_2.setRT(180.85);
ms1_spectrum_3.insert(ms1_spectrum_3.begin(), peaks_3.begin(), peaks_3.end());
ms1_spectrum_2.setNativeID("scan=5");
ms1_spectrum_3.setMSLevel(1);
ms1_spectrum_3.setRT(183.85);
// ms2
ms2_spectrum_1.insert(ms2_spectrum_1.begin(), empty_peaks.begin(), empty_peaks.end());
ms2_spectrum_1.setMSLevel(2);
ms2_spectrum_1.setNativeID("scan=2");
ms2_spectrum_1.setRT(100.1);
ms2_spectrum_2.insert(ms2_spectrum_2.begin(), empty_peaks.begin(), empty_peaks.end());
ms2_spectrum_2.setMSLevel(2);
ms2_spectrum_2.setNativeID("scan=4");
ms2_spectrum_2.setRT(180.90);
ms2_spectrum_3.insert(ms2_spectrum_3.begin(), empty_peaks.begin(), empty_peaks.end());
ms2_spectrum_3.setMSLevel(2);
ms2_spectrum_3.setNativeID("scan=6");
ms2_spectrum_3.setRT(183.92);
// ms2 precursor information
ms2_spectrum_1.setPrecursors(v_precursor_1);
ms2_spectrum_2.setPrecursors(v_precursor_2);
ms2_spectrum_3.setPrecursors(v_precursor_3);
v_spectra.push_back(ms1_spectrum_1);
v_spectra.push_back(ms2_spectrum_1);
v_spectra.push_back(ms1_spectrum_2);
v_spectra.push_back(ms2_spectrum_2);
v_spectra.push_back(ms1_spectrum_3);
v_spectra.push_back(ms2_spectrum_3);
// MSExperiment
exp.setSpectra(v_spectra);
exp.sortSpectra();
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PrecursorCorrection* ptr = nullptr;
PrecursorCorrection* null_ptr = nullptr;
START_SECTION(PrecursorCorrection())
{
ptr = new PrecursorCorrection();
TEST_NOT_EQUAL(ptr, null_ptr);
}
END_SECTION
START_SECTION(~PrecursorCorrection())
{
delete ptr;
}
END_SECTION
START_SECTION((static void getPrecursors(const MSExperiment &exp, std::vector< Precursor > &precursors, std::vector< double > &precursors_rt, std::vector< Size > &precursor_scan_index)))
{
MSExperiment getP_exp = exp;
vector<Precursor> precursor;
vector<double> rt;
vector<Size> index;
PrecursorCorrection::getPrecursors(getP_exp, precursor, rt, index);
TEST_EQUAL(precursor.size(), 3);
TEST_EQUAL(rt.size(), 3);
TEST_EQUAL(index.size(), 3);
TEST_REAL_SIMILAR(precursor[0].getMZ(), 509.9999)
TEST_REAL_SIMILAR(precursor[0].getIntensity(), 240.0);
TEST_REAL_SIMILAR(rt[0], 100.1);
}
END_SECTION
FuzzyStringComparator fsc;
fsc.setAcceptableAbsolute(1e-8);
START_SECTION((static void writeHist(const String &out_csv, const std::vector< double > &deltaMZs, const std::vector< double > &mzs, const std::vector< double > &rts)))
{
MSExperiment write_exp = exp;
String csv_tmp;
NEW_TMP_FILE(csv_tmp);
vector<double> dmz;
vector<double> mz;
vector<double> rt;
PrecursorCorrection::correctToNearestMS1Peak(write_exp, 2, true, dmz, mz, rt);
PrecursorCorrection::writeHist(csv_tmp, dmz, mz,rt);
TEST_EQUAL(fsc.compareFiles(csv_tmp, OPENMS_GET_TEST_DATA_PATH("PrecursorCorrection_out.csv")),true);
}
END_SECTION
START_SECTION((static std::set<Size> correctToNearestMS1Peak(MSExperiment &exp, double mz_tolerance, bool ppm, std::vector< double > &deltaMZs, std::vector< double > &mzs, std::vector< double > &rts)))
{
// test with 1 ppm (1)
MSExperiment nearest_exp_1 = exp;
vector<double> dmz_1;
vector<double> mz_1;
vector<double> rt_1;
// corrected precursor_1: 510.0000
// corrected precursor_2: 610.0000
// corrected precursor_3: none
PrecursorCorrection::correctToNearestMS1Peak(nearest_exp_1, 1, true, dmz_1, mz_1, rt_1);
TEST_REAL_SIMILAR(dmz_1[0], 0.0001);
TEST_REAL_SIMILAR(dmz_1[1], -0.0001);
// test with 5 ppm (2)
MSExperiment nearest_exp_2 = exp;
vector<double> dmz_2;
vector<double> mz_2;
vector<double> rt_2;
// corrected precursor_1: 510.0000
// corrected precursor_2: 610.0000
// corrected precursor_3: 611.0033
PrecursorCorrection::correctToNearestMS1Peak(nearest_exp_2, 5, true, dmz_2, mz_2, rt_2);
TEST_REAL_SIMILAR(dmz_2[0], 0.0001);
TEST_REAL_SIMILAR(dmz_2[1], -0.0001);
TEST_REAL_SIMILAR(dmz_2[2], -0.0002);
}
END_SECTION
START_SECTION((static std::set<Size> correctToHighestIntensityMS1Peak(MSExperiment &exp, double mz_tolerance, bool ppm, std::vector< double > &deltaMZs, std::vector< double > &mzs, std::vector< double > &rts)))
{
// test with 0.0001 Da (1)
MSExperiment highest_exp_1 = exp;
vector<double> dmz_1;
vector<double> mz_1;
vector<double> rt_1;
// corrected precursor_1: 510.0000
// corrected precursor_2: 610.0000
// corrected precursor_3: none
PrecursorCorrection::correctToHighestIntensityMS1Peak(highest_exp_1, 0.0001, false, dmz_1, mz_1, rt_1);
TEST_REAL_SIMILAR(dmz_1[0], 0.0001);
TEST_REAL_SIMILAR(dmz_1[1], -0.0001);
// test with 0.0005 Da (2)
MSExperiment highest_exp_2 = exp;
vector<double> dmz_2;
vector<double> mz_2;
vector<double> rt_2;
// corrected precursor_1: 510.0000
// corrected precursor_2: 609.9998
// corrected precursor_3: 611.0031
PrecursorCorrection::correctToHighestIntensityMS1Peak(highest_exp_2, 0.0005, false, dmz_2, mz_2, rt_2);
TEST_REAL_SIMILAR(dmz_2[0], 0.0001);
TEST_REAL_SIMILAR(dmz_2[1], -0.0003);
TEST_REAL_SIMILAR(dmz_2[2], -0.0004);
}
END_SECTION
// check ppm
START_SECTION((static std::set<Size> correctToHighestIntensityMS1Peak(MSExperiment &exp, double mz_tolerance, bool ppm, std::vector< double > &deltaMZs, std::vector< double > &mzs, std::vector< double > &rts)))
{
// test with 1 ppm (1)
MSExperiment highest_exp_1 = exp;
vector<double> dmz_1;
vector<double> mz_1;
vector<double> rt_1;
// corrected precursor_1: 510.0000
// corrected precursor_2: 609.9998 (1 ppm of 610.0001 = +/- 0.000610)
// corrected precursor_3: none
PrecursorCorrection::correctToHighestIntensityMS1Peak(highest_exp_1, 2, true, dmz_1, mz_1, rt_1);
std::cout << dmz_1[0] << std::endl;
std::cout << dmz_1[1] << std::endl;
TEST_REAL_SIMILAR(dmz_1[0], 0.0001);
TEST_REAL_SIMILAR(dmz_1[1], -0.0003);
// test with 5 ppm Da
MSExperiment highest_exp_2 = exp;
vector<double> dmz_2;
vector<double> mz_2;
vector<double> rt_2;
// corrected precursor_1: 510.0000
// corrected precursor_2: 609.9998
// corrected precursor_3: 611.0031
PrecursorCorrection::correctToHighestIntensityMS1Peak(highest_exp_2, 5, true, dmz_2, mz_2, rt_2);
std::cout << dmz_2[0] << std::endl;
std::cout << dmz_2[1] << std::endl;
std::cout << dmz_2[2] << std::endl;
TEST_REAL_SIMILAR(dmz_2[0], 0.0001);
TEST_REAL_SIMILAR(dmz_2[1], -0.0003);
TEST_REAL_SIMILAR(dmz_2[2], -0.0004);
}
END_SECTION
// FeatureMap
DPosition<2> position_1(175.0, 609.9100);
DPosition<2> position_2(185.0, 611.9300);
vector<DPosition<2> > vec;
vec.push_back(position_1);
vec.push_back(position_2);
ConvexHull2D hull;
hull.setHullPoints(vec);
hull.expandToBoundingBox();
vector<ConvexHull2D> hulls;
hulls.push_back(hull);
FeatureMap fmap;
Feature feature;
feature.setMZ(610.0000);
feature.setRT(180.0);
feature.setCharge(1);
feature.setConvexHulls(hulls);
fmap.push_back(feature);
START_SECTION((static std::set<Size> correctToNearestFeature(const FeatureMap &features, MSExperiment &exp, double rt_tolerance_s=0.0, double mz_tolerance=0.0, bool ppm=true, bool believe_charge=false, bool keep_original=false, bool all_matching_features=false, int max_trace=2, int debug_level=0)))
{
MSExperiment f_exp = exp;
double rt_tolerance = 5;
double mz_tolerance = 5;
bool ppm = true;
vector<Precursor> precursor_before_correction;
vector<Precursor> precursor_after_correction;
vector<MSSpectrum> f_spectra_before = f_exp.getSpectra();
for (const auto& it : f_spectra_before)
{
if (it.getNativeID() == "scan=6")
{
precursor_before_correction = it.getPrecursors();
}
}
// the precursor of the ms2 with nativeID 6 should be corrected
PrecursorCorrection::correctToNearestFeature(fmap, f_exp, rt_tolerance, mz_tolerance, ppm);
vector<MSSpectrum> f_spectra_after = f_exp.getSpectra();
for (const auto& it : f_spectra_after)
{
if (it.getNativeID() == "scan=6")
{
precursor_after_correction = it.getPrecursors();
}
}
TEST_EQUAL(precursor_before_correction.size(), 1);
TEST_EQUAL(precursor_after_correction.size(), 1);
TEST_REAL_SIMILAR(precursor_before_correction[0].getPos(), 611.0035);
TEST_REAL_SIMILAR(precursor_after_correction[0].getPos(), 610.0000);
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ChromeleonFile_test.cpp | .cpp | 8,692 | 194 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/ChromeleonFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/SYSTEM/File.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(ChromeleonFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
ChromeleonFile* ptr = 0;
ChromeleonFile* null_ptr = 0;
START_SECTION(ChromeleonFile())
{
ptr = new ChromeleonFile();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~ChromeleonFile())
{
delete ptr;
}
END_SECTION
START_SECTION(void load(const String& filename, MSExperiment& experiment) const)
{
String input_filepath = OPENMS_GET_TEST_DATA_PATH("20171013_HMP_C61_ISO_P1_GA1_UV_VIS_2.txt");
MSExperiment experiment;
ChromeleonFile cf;
cf.load(input_filepath, experiment);
TEST_EQUAL(experiment.getMetaValue("acq_method_name"), "UV_VIS_2")
TEST_EQUAL(experiment.getMetaValue("mzml_id"), "20171013_C61_ISO_P1_GA1")
TEST_EQUAL(experiment.getExperimentalSettings().getInstrument().getName(), "HM_metode_ZorBax_0,02%_Acetic_acid_ver6")
TEST_EQUAL(experiment.getExperimentalSettings().getInstrument().getSoftware().getName(), "New ProcMethod")
TEST_EQUAL(experiment.getMetaValue("injection_date"), "10/13/2017")
TEST_EQUAL(experiment.getMetaValue("injection_time"), "6:28:26 PM")
TEST_EQUAL(experiment.getMetaValue("detector"), "UV")
TEST_EQUAL(experiment.getMetaValue("signal_quantity"), "Absorbance")
TEST_EQUAL(experiment.getMetaValue("signal_unit"), "mAU")
TEST_EQUAL(experiment.getMetaValue("signal_info"), "WVL:280 nm")
const vector<MSChromatogram> chromatograms = experiment.getChromatograms();
TEST_EQUAL(chromatograms.size(), 1);
TEST_EQUAL(chromatograms[0].size(), 3301);
const MSChromatogram& c = chromatograms[0];
TEST_REAL_SIMILAR(c[0].getRT(), 0.0)
TEST_REAL_SIMILAR(c[0].getIntensity(), 0.0)
TEST_REAL_SIMILAR(c[660].getRT(), 2.2)
TEST_REAL_SIMILAR(c[660].getIntensity(), -0.812998)
TEST_REAL_SIMILAR(c[1320].getRT(), 4.4)
TEST_REAL_SIMILAR(c[1320].getIntensity(), -0.791189)
TEST_REAL_SIMILAR(c[1980].getRT(), 6.6)
TEST_REAL_SIMILAR(c[1980].getIntensity(), -0.285533)
TEST_REAL_SIMILAR(c[2640].getRT(), 8.8)
TEST_REAL_SIMILAR(c[2640].getIntensity(), -0.485941)
TEST_REAL_SIMILAR(c[3300].getRT(), 11.0)
TEST_REAL_SIMILAR(c[3300].getIntensity(), -0.130904)
MzMLFile mzml;
const String output_filepath = File::getTemporaryFile();
mzml.store(output_filepath, experiment);
MSExperiment read_exp;
mzml.load(output_filepath, read_exp);
TEST_EQUAL(read_exp.getChromatograms().size(), 1);
const MSChromatogram& c1 = experiment.getChromatograms()[0];
const MSChromatogram& c2 = read_exp.getChromatograms()[0];
TEST_EQUAL(c1.size(), c2.size())
TEST_REAL_SIMILAR(c1[0].getRT(), c2[0].getRT())
TEST_REAL_SIMILAR(c1[0].getIntensity(), c2[0].getIntensity())
TEST_REAL_SIMILAR(c1[660].getRT(), c2[660].getRT())
TEST_REAL_SIMILAR(c1[660].getIntensity(), c2[660].getIntensity())
TEST_REAL_SIMILAR(c1[1320].getRT(), c2[1320].getRT())
TEST_REAL_SIMILAR(c1[1320].getIntensity(), c2[1320].getIntensity())
TEST_REAL_SIMILAR(c1[1980].getRT(), c2[1980].getRT())
TEST_REAL_SIMILAR(c1[1980].getIntensity(), c2[1980].getIntensity())
TEST_REAL_SIMILAR(c1[2640].getRT(), c2[2640].getRT())
TEST_REAL_SIMILAR(c1[2640].getIntensity(), c2[2640].getIntensity())
TEST_REAL_SIMILAR(c1[3300].getRT(), c2[3300].getRT())
TEST_REAL_SIMILAR(c1[3300].getIntensity(), c2[3300].getIntensity())
}
END_SECTION
START_SECTION(load_with_new_raw_data_header)
{
String input_filepath = OPENMS_GET_TEST_DATA_PATH("ChromeleonFile_new_header.txt");
MSExperiment experiment;
ChromeleonFile cf;
cf.load(input_filepath, experiment);
TEST_EQUAL(experiment.getMetaValue("acq_method_name"), "RID_Signal")
TEST_EQUAL(experiment.getMetaValue("mzml_id"), "S1")
TEST_EQUAL(experiment.getExperimentalSettings().getInstrument().getName(), "SUGARS_MP.M")
TEST_EQUAL(experiment.getExperimentalSettings().getInstrument().getSoftware().getName(), "SUGARS_CAL")
TEST_EQUAL(experiment.getMetaValue("injection_date"), "13/06/2019")
TEST_EQUAL(experiment.getMetaValue("injection_time"), "12:11:41 AM")
TEST_EQUAL(experiment.getMetaValue("detector"), "LCSystem")
TEST_EQUAL(experiment.getMetaValue("signal_quantity"), "")
TEST_EQUAL(experiment.getMetaValue("signal_unit"), "nRIU")
TEST_EQUAL(experiment.getMetaValue("signal_info"), "")
const vector<MSChromatogram> chromatograms = experiment.getChromatograms();
TEST_EQUAL(chromatograms.size(), 1);
TEST_EQUAL(chromatograms[0].size(), 10);
const MSChromatogram& c = chromatograms[0];
TEST_REAL_SIMILAR(c[0].getRT(), 0.0)
TEST_REAL_SIMILAR(c[0].getIntensity(), 5.060000)
TEST_REAL_SIMILAR(c[2].getRT(), 0.014430)
TEST_REAL_SIMILAR(c[2].getIntensity(), 5.450000)
TEST_REAL_SIMILAR(c[4].getRT(), 0.028860)
TEST_REAL_SIMILAR(c[4].getIntensity(), 5.580000)
TEST_REAL_SIMILAR(c[6].getRT(), 0.043290)
TEST_REAL_SIMILAR(c[6].getIntensity(), 5.380000)
TEST_REAL_SIMILAR(c[9].getRT(), 0.064935)
TEST_REAL_SIMILAR(c[9].getIntensity(), 4.930000)
MzMLFile mzml;
const String output_filepath = File::getTemporaryFile();
mzml.store(output_filepath, experiment);
MSExperiment read_exp;
mzml.load(output_filepath, read_exp);
TEST_EQUAL(read_exp.getChromatograms().size(), 1);
const MSChromatogram& c1 = experiment.getChromatograms()[0];
const MSChromatogram& c2 = read_exp.getChromatograms()[0];
TEST_EQUAL(c1.size(), c2.size())
TEST_REAL_SIMILAR(c1[0].getRT(), c2[0].getRT())
TEST_REAL_SIMILAR(c1[0].getIntensity(), c2[0].getIntensity())
TEST_REAL_SIMILAR(c1[2].getRT(), c2[2].getRT())
TEST_REAL_SIMILAR(c1[2].getIntensity(), c2[2].getIntensity())
TEST_REAL_SIMILAR(c1[4].getRT(), c2[4].getRT())
TEST_REAL_SIMILAR(c1[4].getIntensity(), c2[4].getIntensity())
TEST_REAL_SIMILAR(c1[6].getRT(), c2[6].getRT())
TEST_REAL_SIMILAR(c1[6].getIntensity(), c2[6].getIntensity())
TEST_REAL_SIMILAR(c1[9].getRT(), c2[9].getRT())
TEST_REAL_SIMILAR(c1[9].getIntensity(), c2[9].getIntensity())
}
END_SECTION
START_SECTION(load_file_with_comma_thousands_separator)
{
String input_filepath = OPENMS_GET_TEST_DATA_PATH("ChromeleonFile_commas.txt");
MSExperiment experiment;
ChromeleonFile cf;
cf.load(input_filepath, experiment);
TEST_EQUAL(experiment.getMetaValue("acq_method_name"), "RID_Signal")
TEST_EQUAL(experiment.getMetaValue("mzml_id"), "S2")
TEST_EQUAL(experiment.getExperimentalSettings().getInstrument().getName(), "SUGARS_MP.M")
TEST_EQUAL(experiment.getExperimentalSettings().getInstrument().getSoftware().getName(), "SUGARS_CAL")
TEST_EQUAL(experiment.getMetaValue("injection_date"), "12/06/2019")
TEST_EQUAL(experiment.getMetaValue("injection_time"), "11:49:36 PM")
TEST_EQUAL(experiment.getMetaValue("detector"), "LCSystem")
TEST_EQUAL(experiment.getMetaValue("signal_quantity"), "")
TEST_EQUAL(experiment.getMetaValue("signal_unit"), "nRIU")
TEST_EQUAL(experiment.getMetaValue("signal_info"), "")
const vector<MSChromatogram> chromatograms = experiment.getChromatograms();
TEST_EQUAL(chromatograms.size(), 1);
TEST_EQUAL(chromatograms[0].size(), 8);
const MSChromatogram& c = chromatograms[0];
TEST_REAL_SIMILAR(c[0].getRT(), 0.0)
TEST_REAL_SIMILAR(c[1].getRT(), 8.300000)
TEST_REAL_SIMILAR(c[2].getRT(), 8.513709)
TEST_REAL_SIMILAR(c[3].getRT(), 8.520924)
TEST_REAL_SIMILAR(c[4].getRT(), 9.855700)
TEST_REAL_SIMILAR(c[5].getRT(), 9.884560)
TEST_REAL_SIMILAR(c[6].getRT(), 9.898991)
TEST_REAL_SIMILAR(c[7].getRT(), 9.920635)
TEST_REAL_SIMILAR(c[0].getIntensity(), 1.4)
TEST_REAL_SIMILAR(c[1].getIntensity(), 1.6)
TEST_REAL_SIMILAR(c[2].getIntensity(), -18.980000)
TEST_REAL_SIMILAR(c[3].getIntensity(), -1234567.890000)
TEST_REAL_SIMILAR(c[4].getIntensity(), 1946.610000)
TEST_REAL_SIMILAR(c[5].getIntensity(), 2067.450000)
TEST_REAL_SIMILAR(c[6].getIntensity(), 2345678.900000)
TEST_REAL_SIMILAR(c[7].getIntensity(), 2028.580000)
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ToolDescriptionFile_test.cpp | .cpp | 2,043 | 76 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/ToolDescriptionFile.h>
#include <OpenMS/APPLICATIONS/ToolHandler.h>
///////////////////////////
#include <QStringList>
#include <QDir>
using namespace OpenMS;
using namespace std;
START_TEST(ToolDescriptionFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
ToolDescriptionFile* ptr = nullptr;
ToolDescriptionFile* null_ptr = nullptr;
START_SECTION(ToolDescriptionFile())
{
ptr = new ToolDescriptionFile();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(virtual ~ToolDescriptionFile())
{
delete ptr;
}
END_SECTION
START_SECTION((void load(const String &filename, std::vector< Internal::ToolDescription > &tds)))
{
ToolDescriptionFile f;
std::vector< Internal::ToolDescription > tds;
QStringList list;
QDir dir( ToolHandler::getExternalToolsPath().toQString(), "*.ttd");
QStringList files = dir.entryList();
for (int i=0;i<files.size();++i)
{
files[i] = dir.absolutePath()+QDir::separator()+files[i];
f.load(files[i], tds);
//std::cerr << "load: " << String(files[i]) << "\n";
TEST_EQUAL(!tds.empty(), true)
}
}
END_SECTION
START_SECTION((void store(const String &filename, const std::vector< Internal::ToolDescription > &tds) const ))
{
ToolDescriptionFile f;
std::vector< Internal::ToolDescription > tds;
TEST_EXCEPTION( Exception::NotImplemented, f.store("bla", tds))
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/ExperimentalDesignFile_test.cpp | .cpp | 1,485 | 53 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Timo Sachsenberg$
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/METADATA/ExperimentalDesign.h>
#include <OpenMS/FORMAT/ExperimentalDesignFile.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(ExperimentalDesignFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
ExperimentalDesignFile* ptr = 0;
ExperimentalDesignFile* null_ptr = 0;
START_SECTION(ExperimentalDesignFile())
{
ptr = new ExperimentalDesignFile();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~ExperimentalDesignFile())
{
delete ptr;
}
END_SECTION
START_SECTION((static ExperimentalDesign load(const String &tsv_file, bool require_spectra_files)))
{
ExperimentalDesign design = ExperimentalDesignFile::load(
OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_1.tsv"), false);
// tested in ExperimentalDesign_test
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/XMassFile_test.cpp | .cpp | 2,315 | 80 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Guillaune Belz $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/XMassFile.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
///////////////////////////
START_TEST(XMassFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
XMassFile* ptr = nullptr;
XMassFile* nullPointer = nullptr;
START_SECTION(XMassFile())
ptr = new XMassFile;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~XMassFile())
delete ptr;
END_SECTION
START_SECTION(template<typename SpectrumType> void load(const String& filename, MSSpectrum& spectrum) )
TOLERANCE_ABSOLUTE(0.001)
MSSpectrum s;
MSSpectrum::ConstIterator it;
TextFile::ConstIterator f_it;
XMassFile f;
TEST_EXCEPTION(Exception::FileNotFound, f.load("data_Idontexist", s);)
f.load(OPENMS_GET_TEST_DATA_PATH("XMassFile_test/fid"),s);
TEST_EQUAL(s.size(), 80478)
ABORT_IF(s.size() != 80478)
// read data for comparison
TextFile file;
file.load(OPENMS_GET_TEST_DATA_PATH("XMassFile_test_data.txt"));
TEST_EQUAL((file.end() - file.begin()), 80478)
ABORT_IF((file.end() - file.begin()) != 80478)
for(it=s.begin(), f_it = file.begin(); it != s.end() && f_it != file.end(); ++it, ++f_it)
{
DoubleList test_values = ListUtils::create<double>(*f_it);
ABORT_IF(test_values.size() != 2)
TEST_REAL_SIMILAR(it->getPosition()[0], test_values[0])
TEST_REAL_SIMILAR(it->getIntensity(), test_values[1])
}
END_SECTION
START_SECTION(template<typename SpectrumType> void store(const String& filename, const MSSpectrum& spectrum) const)
// not implemented
TEST_EXCEPTION(Exception::NotImplemented, XMassFile().store(String(), MSSpectrum()))
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/QuadraticRegression_test.cpp | .cpp | 3,479 | 131 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Christian Ehrlich, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
///////////////////////////
#include <OpenMS/ML/REGRESSION/QuadraticRegression.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
using namespace Math;
START_TEST(QuadraticRegression, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
QuadraticRegression* ptr = nullptr;
QuadraticRegression* null_ptr = nullptr;
START_SECTION(QuadraticRegression())
{
ptr = new QuadraticRegression();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~QuadraticRegression())
{
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] = 5.5*i*i + 2*i + 4;
y_axis0[i] = 5.5*i*i + 2*i; // no intercept
weight[i]=1+i;
}
QuadraticRegression q_reg, q_reg2;
START_SECTION((template < typename Iterator > void computeRegression(Iterator x_begin, Iterator x_end, Iterator y_begin)))
{
q_reg.computeRegression(x_axis.begin(), x_axis.end(), y_axis.begin());
TEST_REAL_SIMILAR(q_reg.getA(), 4.0)
TEST_REAL_SIMILAR(q_reg.getB(), 2.0)
TEST_REAL_SIMILAR(q_reg.getC(), 5.5)
TEST_REAL_SIMILAR(q_reg.getChiSquared(), 0.0)
q_reg2.computeRegression(x_axis.begin(), x_axis.end(), y_axis0.begin());
TEST_REAL_SIMILAR(q_reg2.getA(), 0.0)
TEST_REAL_SIMILAR(q_reg2.getB(), 2.0)
TEST_REAL_SIMILAR(q_reg2.getC(), 5.5)
TEST_REAL_SIMILAR(q_reg2.getChiSquared(), 0.0)
}
END_SECTION
START_SECTION((template < typename Iterator > void computeRegressionWeighted(Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin)))
{
q_reg.computeRegressionWeighted(x_axis.begin(), x_axis.end(), y_axis.begin(), weight.begin());
TEST_REAL_SIMILAR(q_reg.getA(), 4.0)
TEST_REAL_SIMILAR(q_reg.getB(), 2.0)
TEST_REAL_SIMILAR(q_reg.getC(), 5.5)
TEST_REAL_SIMILAR(q_reg.getChiSquared(), 0.0)
q_reg2.computeRegressionWeighted(x_axis.begin(), x_axis.end(), y_axis0.begin(), weight.begin());
TEST_REAL_SIMILAR(q_reg2.getA(), 0.0)
TEST_REAL_SIMILAR(q_reg2.getB(), 2.0)
TEST_REAL_SIMILAR(q_reg2.getC(), 5.5)
TEST_REAL_SIMILAR(q_reg2.getChiSquared(), 0.0)
}
END_SECTION
START_SECTION((double eval(double x) const ))
{
double x = 100.0;
TEST_REAL_SIMILAR(q_reg.eval(x), x*x*5.5 + x*2 + 4)
}
END_SECTION
START_SECTION(static double eval(double A, double B, double C, double x))
{
double x = 100.0;
TEST_REAL_SIMILAR(QuadraticRegression::eval(4.0, 2.0, 5.5, x), x*x*5.5 + x*2 + 4)
}
END_SECTION
START_SECTION((double getA() const ))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((double getB() const ))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((double getC() const ))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((double getChiSquared() const ))
{
NOT_TESTABLE // tested above
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/InstrumentSettings_test.cpp | .cpp | 5,810 | 190 | // 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/InstrumentSettings.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(InstrumentSettings, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
InstrumentSettings* ptr = nullptr;
InstrumentSettings* nullPointer = nullptr;
START_SECTION((InstrumentSettings()))
ptr = new InstrumentSettings();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~InstrumentSettings()))
delete ptr;
END_SECTION
START_SECTION((IonSource::Polarity getPolarity() const))
InstrumentSettings tmp;
TEST_EQUAL(tmp.getPolarity(),IonSource::Polarity::POLNULL);
END_SECTION
START_SECTION((void setPolarity(IonSource::Polarity polarity)))
InstrumentSettings tmp;
tmp.setPolarity(IonSource::Polarity::NEGATIVE);
TEST_EQUAL(tmp.getPolarity(),IonSource::Polarity::NEGATIVE);
END_SECTION
START_SECTION((const std::vector< ScanWindow >& getScanWindows() const))
InstrumentSettings tmp;
TEST_EQUAL(tmp.getScanWindows().size(),0);
END_SECTION
START_SECTION((std::vector< ScanWindow >& getScanWindows()))
InstrumentSettings tmp;
tmp.getScanWindows().resize(1);
TEST_EQUAL(tmp.getScanWindows().size(),1);
END_SECTION
START_SECTION((void setScanWindows(std::vector< ScanWindow > scan_windows)))
InstrumentSettings tmp;
vector<ScanWindow> vec(17);
tmp.setScanWindows(vec);
TEST_EQUAL(tmp.getScanWindows().size(),17);
END_SECTION
START_SECTION((ScanMode getScanMode() const))
InstrumentSettings tmp;
TEST_EQUAL(tmp.getScanMode(),InstrumentSettings::ScanMode::UNKNOWN);
END_SECTION
START_SECTION((void setScanMode(ScanMode scan_mode)))
InstrumentSettings tmp;
tmp.setScanMode(InstrumentSettings::ScanMode::SIM);
TEST_EQUAL(tmp.getScanMode(),InstrumentSettings::ScanMode::SIM);
END_SECTION
START_SECTION((bool getZoomScan() const))
InstrumentSettings tmp;
TEST_EQUAL(tmp.getZoomScan(),false);
END_SECTION
START_SECTION((void setZoomScan(bool zoom_scan)))
InstrumentSettings tmp;
tmp.setZoomScan(true);
TEST_EQUAL(tmp.getZoomScan(),true);
END_SECTION
START_SECTION((InstrumentSettings(const InstrumentSettings& source)))
InstrumentSettings tmp;
tmp.setScanMode(InstrumentSettings::ScanMode::SIM);
tmp.getScanWindows().resize(1);
tmp.setPolarity(IonSource::Polarity::NEGATIVE);
tmp.setMetaValue("label",String("label"));
tmp.setZoomScan(true);
InstrumentSettings tmp2(tmp);
TEST_EQUAL(tmp2.getScanMode(),InstrumentSettings::ScanMode::SIM);
TEST_EQUAL(tmp2.getScanWindows().size(),1);
TEST_EQUAL(tmp2.getPolarity(),IonSource::Polarity::NEGATIVE);
TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label");
TEST_EQUAL(tmp2.getZoomScan(),true);
END_SECTION
START_SECTION((InstrumentSettings& operator= (const InstrumentSettings& source)))
InstrumentSettings tmp;
tmp.setScanMode(InstrumentSettings::ScanMode::SIM);
tmp.getScanWindows().resize(1);
tmp.setPolarity(IonSource::Polarity::NEGATIVE);
tmp.setMetaValue("label",String("label"));
tmp.setZoomScan(true);
InstrumentSettings tmp2;
tmp2 = tmp;
TEST_EQUAL(tmp2.getScanMode(),InstrumentSettings::ScanMode::SIM);
TEST_EQUAL(tmp2.getScanWindows().size(),1);
TEST_EQUAL(tmp2.getPolarity(),IonSource::Polarity::NEGATIVE);
TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label");
TEST_EQUAL(tmp2.getZoomScan(),true);
tmp2 = InstrumentSettings();
TEST_EQUAL(tmp2.getScanMode(),InstrumentSettings::ScanMode::UNKNOWN);
TEST_EQUAL(tmp2.getScanWindows().size(),0);
TEST_EQUAL(tmp2.getPolarity(),IonSource::Polarity::POLNULL);
TEST_EQUAL(tmp2.getMetaValue("label").isEmpty(), true);
TEST_EQUAL(tmp2.getZoomScan(),false);
END_SECTION
START_SECTION((bool operator== (const InstrumentSettings& rhs) const))
InstrumentSettings edit, empty;
TEST_EQUAL(edit==empty,true);
edit.setScanMode(InstrumentSettings::ScanMode::SIM);
TEST_EQUAL(edit==empty,false);
edit = empty;
edit.getScanWindows().resize(1);
TEST_EQUAL(edit==empty,false);
edit = empty;
edit.setPolarity(IonSource::Polarity::NEGATIVE);
TEST_EQUAL(edit==empty,false);
edit = empty;
edit.setMetaValue("label",String("label"));
TEST_EQUAL(edit==empty,false);
edit = empty;
edit.setZoomScan(true);
TEST_EQUAL(edit==empty,false);
END_SECTION
START_SECTION((bool operator!= (const InstrumentSettings& rhs) const))
InstrumentSettings edit, empty;
TEST_EQUAL(edit!=empty,false);
edit.setScanMode(InstrumentSettings::ScanMode::SIM);
TEST_EQUAL(edit!=empty,true);
edit = empty;
edit.getScanWindows().resize(1);
TEST_EQUAL(edit!=empty,true);
edit = empty;
edit.setPolarity(IonSource::Polarity::NEGATIVE);
TEST_EQUAL(edit!=empty,true);
edit = empty;
edit.setMetaValue("label",String("label"));
TEST_EQUAL(edit!=empty,true);
edit = empty;
edit.setZoomScan(true);
TEST_EQUAL(edit!=empty,true);
END_SECTION
START_SECTION((static StringList getAllNamesOfScanMode()))
StringList names = InstrumentSettings::getAllNamesOfScanMode();
TEST_EQUAL(names.size(), static_cast<size_t>(InstrumentSettings::ScanMode::SIZE_OF_SCANMODE));
TEST_EQUAL(names[static_cast<size_t>(InstrumentSettings::ScanMode::MS1SPECTRUM)], "MS1Spectrum");
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IMSAlphabetTextParser_test.cpp | .cpp | 2,000 | 84 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Stephan Aiche $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabetTextParser.h>
///////////////////////////
using namespace OpenMS;
using namespace ims;
using namespace std;
START_TEST(IMSAlphabetTextParser, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
IMSAlphabetTextParser* ptr = nullptr;
IMSAlphabetTextParser* null_ptr = nullptr;
START_SECTION(IMSAlphabetTextParser())
{
ptr = new IMSAlphabetTextParser();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IMSAlphabetTextParser())
{
delete ptr;
}
END_SECTION
IMSAlphabetParser<> * parser = new IMSAlphabetTextParser();
START_SECTION((virtual void parse(std::istream &is)))
{
String filename;
NEW_TMP_FILE(filename)
// just create the file
ofstream of;
of.open(filename.c_str());
of << "# a comment which should be ignored" << std::endl;
of << "A\t71.03711" << std::endl;
of << "R\t156.10111" << std::endl;
of.close();
ifstream ifs;
ifs.open(filename.c_str());
ABORT_IF(!ifs)
parser->parse(ifs);
ifs.close();
TEST_EQUAL(parser->getElements().empty(), false)
}
END_SECTION
START_SECTION((virtual ContainerType& getElements()))
{
TEST_EQUAL(parser->getElements().size(), 2)
TEST_REAL_SIMILAR(parser->getElements()["A"], 71.03711)
TEST_REAL_SIMILAR(parser->getElements()["R"], 156.10111)
}
END_SECTION
delete parser;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Colorizer_test.cpp | .cpp | 5,219 | 119 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CONCEPT/Colorizer.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(Colorizer, "$Id$")
// Test variables
int test_int = 15;
//string test_string = " !#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
// ANSI codes
string const redANSI = "\033[91m";
string const greenANSI = "\033[92m";
string const yellowANSI = "\033[93m";
string const blueANSI = "\033[94m";
string const magentaANSI = "\033[95m";
string const cyanANSI = "\033[96m";
string const resetColorANSI = "\033[39m";
START_SECTION(Colorizer(const ConsoleColor color))
{
Colorizer test(ConsoleColor::BLUE);
stringstream s;
s << "-" << test("test") << "-";
TEST_EQUAL(s.str(), String("-") + blueANSI + "test" + resetColorANSI + "-")
}
END_SECTION
START_SECTION(~Colorizer())
{
NOT_TESTABLE
}
END_SECTION
START_SECTION(Colorizer& operator()())
{
Colorizer test(ConsoleColor::BLUE);
stringstream s;
s << "-" << test() << "test-" << test_int;
TEST_EQUAL(s.str(), String("-") + blueANSI + "test-" + test_int)
}
END_SECTION
START_SECTION(template<typename T> Colorizer& operator()(T s))
{
Colorizer test(ConsoleColor::MAGENTA);
stringstream s;
s << "-" << test(test_int) << "test-" << test_int;
TEST_EQUAL(s.str(), String("-") + magentaANSI + test_int + resetColorANSI + "test-" + test_int)
}
END_SECTION
START_SECTION(Colorizer& undo())
{
Colorizer test(ConsoleColor::CYAN);
{
stringstream s;
s << "-" << test() << "test" << test_int << test.undo() << "nocol";
TEST_EQUAL(s.str(), String("-") + cyanANSI + "test" + test_int + resetColorANSI + "nocol")
}
// test double coloring + reset (using any Colorizer)
Colorizer yellow_test(ConsoleColor::YELLOW);
stringstream s;
s << "-" << test() << "test" << yellow_test() << test_int << yellow_test.undo() << "nocol";
TEST_EQUAL(s.str(), String("-") + cyanANSI + "test" + yellowANSI + test_int + resetColorANSI + "nocol")
}
END_SECTION
START_SECTION([EXTRA] visual inspection(only works when not redirecting cout/cerr to file))
{
std::cerr << "\n\n --- for COUT ---\n" << std::flush;
std::cout << red.undoAll();
std::cout << "\n-" << red("red inline text") << " -" << red() << " red to infinity " << red.undo();
std::cout << "\n-" << green("green inline text") << " -" << green() << " green to infinity " << green.undo();
std::cout << "\n-" << yellow("yellow inline text") << " -" << yellow() << " yellow to infinity " << yellow.undo();
std::cout << "\n-" << blue("blue inline text") << " -" << blue() << " blue to infinity " << blue.undo();
std::cout << "\n-" << magenta("magenta inline text") << " -" << magenta() << " magenta to infinity " << magenta.undo();
std::cout << "\n-" << cyan("cyan inline text") << " -" << cyan() << " cyan to infinity " << cyan.undo();
std::cout << "\n-" << invert("inverted inline text") << " -" << invert() << " invert to infinity " << invert.undo();
std::cout << "\n-" << bright("bright inline text") << " -" << bright() << " bright to infinity " << bright.undo();
std::cout << "\n-" << underline("underline inline text") << " -" << underline() << " underline to infinity " << underline.undo();
std::cout << "\n-" << underline() << bright() << green() <<" underlined, bright, green to infinity " << underline.undoAll();
std::cout << std::flush; // make sure the ANSI code made it to the stream
std::cerr << "\n\n --- for CERR ---\n";
std::cerr << red.undoAll();
std::cerr << "\n-" << red("red inline text") << " -" << red() << " red to infinity " << red.undo();
std::cerr << "\n-" << green("green inline text") << " -" << green() << " green to infinity " << green.undo();
std::cerr << "\n-" << yellow("yellow inline text") << " -" << yellow() << " yellow to infinity " << yellow.undo();
std::cerr << "\n-" << blue("blue inline text") << " -" << blue() << " blue to infinity " << blue.undo();
std::cerr << "\n-" << magenta("magenta inline text") << " -" << magenta() << " magenta to infinity " << magenta.undo();
std::cerr << "\n-" << cyan("cyan inline text") << " -" << cyan() << " cyan to infinity " << cyan.undo();
std::cerr << "\n-" << invert("inverted inline text") << " -" << invert() << " invert to infinity " << invert.undo();
std::cerr << "\n-" << bright("bright inline text") << " -" << bright() << " bright to infinity " << bright.undo();
std::cerr << "\n-" << underline("underline inline text") << " -" << underline() << " underline to infinity " << underline.undo();
std::cerr << "\n-" << underline() << bright() << green() << " underlined, bright, green to infinity " << underline.undoAll();
std::cerr << std::flush; // make sure the ANSI code made it to the stream
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/PTMXMLFile_test.cpp | .cpp | 2,088 | 68 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Chris Bauer $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/PTMXMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/PTMXMLHandler.h>
#include <vector>
///////////////////////////
START_TEST(PTMXMLFile, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using namespace std;
PTMXMLFile* ptr = nullptr;
PTMXMLFile* nullPointer = nullptr;
PTMXMLFile xml_file;
START_SECTION((PTMXMLFile()))
ptr = new PTMXMLFile();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((void load(const String& filename, std::map< String, std::pair< String, String > >& ptm_informations)))
map< String, pair< String, String > > ptm_informations;
xml_file.load(OPENMS_GET_TEST_DATA_PATH("PTMs.xml"), ptm_informations);
TEST_EQUAL(ptm_informations["TEST"].first, "N2O2-CH3")
TEST_EQUAL(ptm_informations["TEST"].second, "KLR")
END_SECTION
START_SECTION((void store(String filename, std::map< String, std::pair< String, String > > &ptm_informations) const))
map< String, pair< String, String > > ptm_informations;
xml_file.load(OPENMS_GET_TEST_DATA_PATH("PTMs.xml"), ptm_informations);
String temp_filename;
NEW_TMP_FILE(temp_filename)
xml_file.store(temp_filename, ptm_informations);
ptm_informations.clear();
xml_file.load(temp_filename, ptm_informations);
TEST_EQUAL(ptm_informations["TEST"].first, "N2O2-CH3")
TEST_EQUAL(ptm_informations["TEST"].second, "KLR")
END_SECTION
delete ptr;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/Biosaur2Algorithm_test.cpp | .cpp | 5,279 | 208 | // Copyright (c) 2002-present, OpenMS Inc.
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: $
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FEATUREFINDER/Biosaur2Algorithm.h>
///////////////////////////
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/Feature.h>
using namespace OpenMS;
using namespace std;
START_TEST(Biosaur2Algorithm, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
Biosaur2Algorithm* ptr = nullptr;
Biosaur2Algorithm* nullPointer = nullptr;
START_SECTION(Biosaur2Algorithm())
{
ptr = new Biosaur2Algorithm();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~Biosaur2Algorithm())
{
delete ptr;
}
END_SECTION
START_SECTION(void run(FeatureMap& feature_map))
{
// Test case 1: Isotope calibration bias check
// Create a synthetic dataset with a known isotope pattern
// We want to test if the calibration correctly picks the highest intensity peak
// when multiple peaks are within the tolerance window.
Biosaur2Algorithm algo;
MSExperiment exp;
// Create a few spectra
for (int i = 0; i < 10; ++i)
{
MSSpectrum spec;
spec.setRT(i * 1.0);
spec.setMSLevel(1);
// Monoisotopic peak at 1000.0
Peak1D p1;
p1.setMZ(1000.0);
p1.setIntensity(10000.0);
spec.push_back(p1);
// Isotope 1 at 1001.003355 (approx +1.003355 Da)
// We add a "noise" peak very close to it, but with lower intensity
// to see if the algorithm picks the correct one (higher intensity)
// or just the first one it encounters.
// Correct isotope peak
Peak1D p2;
p2.setMZ(1001.003355);
p2.setIntensity(6000.0); // High intensity
spec.push_back(p2);
// Distracting peak (noise) slightly shifted but within tolerance
// Let's say tolerance is 20ppm.
// 20 ppm at 1000 m/z is 0.02 Da.
// So we put a peak at 1001.003355 - 0.01 = 1000.993355
Peak1D p3;
p3.setMZ(1000.993355);
p3.setIntensity(100.0); // Low intensity
spec.push_back(p3);
exp.addSpectrum(spec);
}
algo.setMSData(exp);
Param p = algo.getParameters();
p.setValue("itol", 20.0); // 20 ppm tolerance
p.setValue("minmz", 900.0);
p.setValue("maxmz", 1100.0);
algo.setParameters(p);
FeatureMap fmap;
algo.run(fmap);
// We expect one feature
TEST_EQUAL(fmap.size(), 1);
if (!fmap.empty())
{
const Feature& f = fmap[0];
TEST_REAL_SIMILAR(f.getMZ(), 1000.0);
TEST_EQUAL(f.getCharge(), 1);
// Check if we have isotopes
// Biosaur2 stores convex hulls differently depending on "convex_hulls" parameter.
// Default is "bounding_box" which stores 1 hull.
// We can check n_isotopes meta value or switch to mass_traces mode.
TEST_EQUAL(f.getMetaValue("n_isotopes"), 2);
}
}
END_SECTION
START_SECTION(void setMSData(const MSExperiment& ms_data))
{
Biosaur2Algorithm algo;
MSExperiment exp;
MSSpectrum spec;
spec.setMSLevel(1);
exp.addSpectrum(spec);
algo.setMSData(exp);
TEST_EQUAL(algo.getMSData().size(), 1);
}
END_SECTION
START_SECTION(void setMSData(MSExperiment&& ms_data))
{
Biosaur2Algorithm algo;
MSExperiment exp;
MSSpectrum spec;
spec.setMSLevel(1);
exp.addSpectrum(spec);
algo.setMSData(std::move(exp));
TEST_EQUAL(algo.getMSData().size(), 1);
TEST_EQUAL(exp.size(), 0); // Should be moved
}
END_SECTION
START_SECTION(MSExperiment& getMSData())
{
Biosaur2Algorithm algo;
MSExperiment& exp = algo.getMSData();
TEST_EQUAL(exp.size(), 0);
MSSpectrum spec;
spec.setMSLevel(1);
exp.addSpectrum(spec);
TEST_EQUAL(algo.getMSData().size(), 1);
}
END_SECTION
START_SECTION(const MSExperiment& getMSData() const)
{
Biosaur2Algorithm algo;
const Biosaur2Algorithm& const_algo = algo;
TEST_EQUAL(const_algo.getMSData().size(), 0);
}
END_SECTION
START_SECTION(void run(FeatureMap& feature_map, std::vector<Hill>& hills, std::vector<PeptideFeature>& peptide_features))
{
Biosaur2Algorithm algo;
MSExperiment exp;
// Create a simple hill
for (int i = 0; i < 5; ++i)
{
MSSpectrum spec;
spec.setRT(i * 1.0);
spec.setMSLevel(1);
Peak1D p;
p.setMZ(500.0);
p.setIntensity(1000.0);
spec.push_back(p);
exp.addSpectrum(spec);
}
algo.setMSData(exp);
Param p = algo.getParameters();
p.setValue("minmz", 400.0);
p.setValue("maxmz", 600.0);
p.setValue("mini", 100.0);
algo.setParameters(p);
FeatureMap fmap;
std::vector<Biosaur2Algorithm::Hill> hills;
std::vector<Biosaur2Algorithm::PeptideFeature> features;
algo.run(fmap, hills, features);
TEST_EQUAL(hills.size() >= 1, true);
// We might not get a feature if it doesn't have isotopes or charge state,
// but we should at least get a hill.
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST | C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/IsotopeModel_test.cpp | .cpp | 9,582 | 236 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Clemens Groepl, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
///////////////////////////
#include <OpenMS/FEATUREFINDER/IsotopeModel.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <sstream>
///////////////////////////
START_TEST(IsotopeModel, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace OpenMS;
using std::stringstream;
// default ctor
IsotopeModel* ptr = nullptr;
IsotopeModel* nullPointer = nullptr;
START_SECTION((IsotopeModel()))
ptr = new IsotopeModel();
TEST_EQUAL(ptr->getName(), "IsotopeModel")
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
// destructor
START_SECTION((virtual ~IsotopeModel()))
delete ptr;
END_SECTION
// assignment operator
START_SECTION((virtual IsotopeModel& operator=(const IsotopeModel &source)))
IsotopeModel im1;
Param tmp;
tmp.setValue("charge", 3);
tmp.setValue("isotope:mode:GaussianSD",0.8);
tmp.setValue("statistics:mean", 670.5);
im1.setParameters(tmp);
IsotopeModel im2;
im2 = im1;
IsotopeModel im3;
im3.setParameters(tmp);
im1 = IsotopeModel();
TEST_EQUAL(im3.getParameters(), im2.getParameters())
END_SECTION
// copy ctor
START_SECTION((IsotopeModel(const IsotopeModel& source)))
IsotopeModel im1;
Param tmp;
tmp.setValue("charge", 3);
tmp.setValue("isotope:mode:GaussianSD",0.8);
tmp.setValue("statistics:mean", 670.5);
im1.setParameters(tmp);
IsotopeModel im2(im1);
IsotopeModel im3;
im3.setParameters(tmp);
im1 = IsotopeModel();
TEST_EQUAL(im3.getParameters(), im2.getParameters())
END_SECTION
START_SECTION([EXTRA] DefaultParamHandler::setParameters(...))
TOLERANCE_ABSOLUTE(0.001)
IsotopeModel im1;
Param tmp;
tmp.setValue("charge", 3);
tmp.setValue("isotope:mode:GaussianSD",0.8);
tmp.setValue("statistics:mean", 670.5);
im1.setParameters(tmp);
IsotopeModel 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
IsotopeModel 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
IsotopeModel im1;
TEST_EQUAL(im1.getCenter() == 0, true)
END_SECTION
START_SECTION( void setSamples(const EmpiricalFormula &formula) )
IsotopeModel im1;
Param tmp;
EmpiricalFormula ef("C66H129O3");
tmp.setValue("statistics:mean", ef.getAverageWeight() / 1);
tmp.setValue("interpolation_step", 0.03);
tmp.setValue("charge", 1);
tmp.setValue("isotope:maximum",100);
tmp.setValue("isotope:mode:mode","Gaussian");
tmp.setValue("isotope:mode:GaussianSD",0.15);
im1.setParameters(tmp);
im1.setSamples(ef);
{
double data[] = {0.000429512, 0.00093697, 0.00196383, 0.00395466, 0.00765145, 0.0142235, 0.0254037, 0.043593, 0.0718726, 0.113852, 0.173278, 0.253381, 0.355987, 0.480533, 0.623218, 0.776577, 0.929731, 1.06945, 1.18192, 1.25501, 1.28036, 1.25501, 1.18192, 1.06945, 0.929731, 0.776577, 0.623218, 0.480533, 0.355987, 0.253381, 0.173278, 0.113852, 0.0718726, 0.0439064, 0.0260875, 0.0156567, 0.0105376, 0.00953883, 0.0123444, 0.019477, 0.0318149, 0.0524539, 0.0830909, 0.126461, 0.184922, 0.259806, 0.350701, 0.454835, 0.566759, 0.678534, 0.7805, 0.862586, 0.915925, 0.934428, 0.915925, 0.862586, 0.7805, 0.678534, 0.566759, 0.454835, 0.350701, 0.259806, 0.184922, 0.126461, 0.0830909, 0.0524539, 0.0318149, 0.0186555, 0.0106322, 0.00611169, 0.00394849, 0.00348857, 0.00450454, 0.00682396, 0.01171, 0.0193065, 0.0305829, 0.0465459, 0.0680634, 0.0956255, 0.129081, 0.167409, 0.208604, 0.249745, 0.287275, 0.317488, 0.33712, 0.34393, 0.33712, 0.317488, 0.287275, 0.249745, 0.208604, 0.167409, 0.129081, 0.0956255, 0.0680634, 0.0465459, 0.0305829, 0.0193065, 0.0117385, 0.00688626, 0.00395131, 0.0023183, 0.00157108, 0.00147331, 0.00194089, 0.00289868, 0.00477912, 0.00757047, 0.011522, 0.0168484, 0.0236711, 0.0319527, 0.0414404, 0.0516379, 0.0618218, 0.071112, 0.0785909, 0.0834507, 0.0851365, 0.0834507, 0.0785909, 0.071112, 0.0618218, 0.0516379, 0.0414404, 0.0319527, 0.0236711, 0.0168484, 0.011522, 0.00757047, 0.00477912, 0.00290403, 0.00170087, 0.000970228, 0.000558009, 0.000358215, 0.000307651, 0.000378553, 0.000542686, 0.000894739, 0.00141733, 0.00215713, 0.00315433, 0.00443167, 0.00598213, 0.0077584, 0.00966757, 0.0115742, 0.0133135, 0.0147137, 0.0156235, 0.0159391, 0.0156235, 0.0147137, 0.0133135, 0.0115742, 0.00966757, 0.0077584, 0.00598213, 0.00443167, 0.00315433, 0.00215713, 0.00141733, 0.000894739, 0.000542686, 0.00031625, 0.000177068, 9.52526e-005, 4.92314e-005, 2.44476e-005, 1.16643e-005};
int size = sizeof( data ) / sizeof( data[0] );
std::vector<double> dpa2( data, &data[ size ] );
std::vector<Peak1D> dpa1;
im1.getSamples(dpa1);
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].getIntensity(),dpa2[i])
}
}
{
// lorentzian
tmp.setValue("isotope:mode:mode","Lorentzian");
tmp.setValue("isotope:mode:LorentzFWHM",0.05);
im1.setParameters(tmp);
im1.setSamples(ef);
double data[] = {0.0249619, 0.0291547, 0.0344977, 0.0414526, 0.0507371, 0.0635168, 0.0817848, 0.109176, 0.152888, 0.228787, 0.377365, 0.725701, 1.80202, 5.53034, 3.91171, 1.28304, 0.570747, 0.315088, 0.198245, 0.1358, 0.0986954, 0.0749089, 0.0587688, 0.0473237, 0.0389177, 0.0325645, 0.027647, 0, 0, 0, 0, 0, 0, 0.0182176, 0.0212776, 0.0251771, 0.0302528, 0.0370288, 0.0463557, 0.059688, 0.0796788, 0.111581, 0.166973, 0.275407, 0.52963, 1.31515, 4.03614, 2.85483, 0.936385, 0.416541, 0.229957, 0.144682, 0.0991093, 0.0720296, 0.0546698, 0.0428905, 0.0345377, 0.0284028, 0.0237661, 0.0201772, 0, 0, 0, 0, 0, 0, 0, 0.00670527, 0.00783155, 0.0092668, 0.011135, 0.013629, 0.0170619, 0.0219691, 0.029327, 0.041069, 0.061457, 0.101368, 0.194938, 0.48406, 1.48556, 1.05076, 0.344651, 0.153314, 0.0846392, 0.0532526, 0.0364787, 0.0265116, 0.0201221, 0.0157865, 0.0127121, 0.0104541, 0.00874748, 0.00742654, 0, 0, 0, 0, 0, 0, 0.00165982, 0.00193862, 0.0022939, 0.00275636, 0.00337373, 0.0042235, 0.00543822, 0.0072596, 0.0101662, 0.015213, 0.0250926, 0.048255, 0.119824, 0.367736, 0.260106, 0.0853148, 0.0379514, 0.0209516, 0.0131821, 0.00902993, 0.00656267, 0.00498101, 0.00390778, 0.00314675, 0.00258781, 0.00216535, 0.00183836, 0, 0, 0, 0, 0, 0, 0.000310749, 0.000362945, 0.000429461, 0.000516041, 0.000631624, 0.000790718, 0.00101813, 0.00135913, 0.0019033, 0.00284816, 0.00469779, 0.00903422, 0.0224333, 0.068847, 0.0486966, 0.0159725, 0.0071052, 0.00392252, 0.00246794, 0.00169057, 0.00122865, 0.000932537, 0.00073161, 0.00058913, 0.000484485, 0.000405393, 0.000344176};
int size = sizeof( data ) / sizeof( data[0] );
std::vector<double> dpa2( data, &data[ size ] );
std::vector<Peak1D> dpa1;
im1.getSamples(dpa1);
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].getIntensity(),dpa2[i])
}
}
END_SECTION
START_SECTION( void setOffset(CoordinateType offset) )
TOLERANCE_ABSOLUTE(0.1)
IsotopeModel im1;
Param tmp;
tmp.setValue("charge", 3);
tmp.setValue("isotope:mode:GaussianSD",0.8);
tmp.setValue("statistics:mean", 670.5);
im1.setParameters(tmp);
im1.setOffset( 673.5 );
IsotopeModel 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)
IsotopeModel im1;
Param tmp;
tmp.setValue("charge", 3);
tmp.setValue("isotope:mode:GaussianSD",0.8);
tmp.setValue("statistics:mean", 670.5);
im1.setParameters(tmp);
im1.setOffset( 673.5 );
IsotopeModel 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
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MultiplexDeltaMassesGenerator_test.cpp | .cpp | 3,494 | 82 | // 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/MultiplexDeltaMassesGenerator.h>
using namespace OpenMS;
START_TEST(MultiplexDeltaMassesGenerator, "$Id$")
std::map<String, double> label_mass_shift;
label_mass_shift.insert(std::make_pair("Arg6", 6.0201290268));
label_mass_shift.insert(std::make_pair("Arg10", 10.008268600));
label_mass_shift.insert(std::make_pair("Lys4", 4.0251069836));
label_mass_shift.insert(std::make_pair("Lys8", 8.0141988132));
// triple SILAC
String labels = "[][Lys4,Arg6][Lys8,Arg10]";
int missed_cleavages = 1;
MultiplexDeltaMassesGenerator* nullPointer = nullptr;
MultiplexDeltaMassesGenerator* ptr;
START_SECTION(MultiplexDeltaMassesGenerator(String labels, int missed_cleavages, std::map<String,double> label_mass_shift))
MultiplexDeltaMassesGenerator list(labels, missed_cleavages, label_mass_shift);
TEST_EQUAL(list.getDeltaMassesList().size(), 5);
ptr = new MultiplexDeltaMassesGenerator(labels, missed_cleavages, label_mass_shift);
TEST_NOT_EQUAL(ptr, nullPointer);
delete ptr;
END_SECTION
MultiplexDeltaMassesGenerator list(labels, missed_cleavages, label_mass_shift);
START_SECTION(std::vector<MultiplexDeltaMasses> getDeltaMassesList())
std::vector<MultiplexDeltaMasses> masses = list.getDeltaMassesList();
TEST_EQUAL(masses.size(), 5);
TEST_REAL_SIMILAR(masses[2].getDeltaMasses()[1].delta_mass, 8.0502139672);
TEST_REAL_SIMILAR(masses[4].getDeltaMasses()[2].delta_mass, 20.0165372);
END_SECTION
START_SECTION(std::vector<std::vector<String> > MultiplexDeltaMassesGenerator::getSamplesLabelsList())
std::vector<std::vector<String> > samples_labels = list.getSamplesLabelsList();
TEST_EQUAL(samples_labels.size(), 3);
TEST_EQUAL(samples_labels[1][0], "Lys4");
TEST_EQUAL(samples_labels[2][1], "Arg10");
END_SECTION
START_SECTION(void generateKnockoutDeltaMasses())
list.generateKnockoutDeltaMasses();
std::vector<MultiplexDeltaMasses> masses_knockout = list.getDeltaMassesList();
TEST_EQUAL(masses_knockout.size(), 21);
TEST_REAL_SIMILAR(masses_knockout[6].getDeltaMasses()[1].delta_mass, 8.0141988132);
TEST_REAL_SIMILAR(masses_knockout[19].getDeltaMasses()[1].delta_mass, 20.0165372);
TEST_EQUAL(masses_knockout[20].getDeltaMasses().size(), 1);
END_SECTION
START_SECTION(String MultiplexDeltaMassesGenerator::getLabelShort(String label))
TEST_EQUAL(list.getLabelShort("Label:13C(6)15N(2)"), "Lys8");
TEST_EQUAL(list.getLabelShort("Dimethyl:2H(6)13C(2)"), "Dimethyl8");
END_SECTION
START_SECTION(String MultiplexDeltaMassesGenerator::getLabelLong(String label))
TEST_EQUAL(list.getLabelLong("Lys8"), "Label:13C(6)15N(2)");
TEST_EQUAL(list.getLabelLong("Dimethyl8"), "Dimethyl:2H(6)13C(2)");
END_SECTION
START_SECTION(MultiplexDeltaMasses::LabelSet MultiplexDeltaMassesGenerator::extractLabelSet(AASequence sequence))
AASequence sequence = AASequence::fromString("LAPITSDPTEAAAVGAVEASFK(Label:13C(6)15N(2))");
MultiplexDeltaMasses::LabelSet label_set = list.extractLabelSet(sequence);
TEST_EQUAL(label_set.size(), 1);
TEST_EQUAL(*(label_set.begin()), "Lys8");
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MS2File_test.cpp | .cpp | 1,916 | 68 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/FORMAT/MS2File.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
///////////////////////////
START_TEST(MS2File, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
MS2File * ptr = nullptr;
MS2File* nullPointer = nullptr;
START_SECTION((MS2File()))
ptr = new MS2File;
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION((~MS2File()))
delete ptr;
END_SECTION
TOLERANCE_ABSOLUTE(0.01)
START_SECTION((template <typename MapType> void load(const String &filename, MapType & exp)))
MS2File file;
PeakMap exp;
file.load(OPENMS_GET_TEST_DATA_PATH("MS2File_test_spectra.ms2"), exp);
//test DocumentIdentifier addition
TEST_STRING_EQUAL(exp.getLoadedFilePath(), OPENMS_GET_TEST_DATA_PATH("MS2File_test_spectra.ms2"));
TEST_STRING_EQUAL(FileTypes::typeToName(exp.getLoadedFileType()), "ms2");
TEST_EQUAL(exp.size(), 2)
TEST_EQUAL(exp[0].size(), 4)
TEST_EQUAL(exp[1].size(), 4)
TEST_STRING_EQUAL(exp[0].getNativeID(), "index=0")
TEST_STRING_EQUAL(exp[1].getNativeID(), "index=1")
TEST_REAL_SIMILAR(exp[0].getPrecursors()[0].getMZ(), 444.44)
TEST_REAL_SIMILAR(exp[1].getPrecursors()[0].getMZ(), 555.555)
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/MSExperiment_test.cpp | .cpp | 88,048 | 2,963 | // 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, Tom Waschischeck $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/Peak2D.h>
#include <OpenMS/METADATA/DataProcessing.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
MSExperiment createPeakMapWithRTs(std::vector<double> RTs)
{
MSExperiment map;
MSSpectrum s;
for (auto rt : RTs)
{
s.setRT(rt);
map.addSpectrum(s);
}
return map;
}
MSExperiment setMSLevel(MSExperiment exp, std::vector<int> ms_levels)
{
for (size_t i = 0; i < ms_levels.size(); ++i)
{
exp[i].setMSLevel(ms_levels[i]);
}
return exp;
}
START_TEST(MSExperiment, "$Id$");
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
PeakMap* ptr = nullptr;
PeakMap* nullPointer = nullptr;
START_SECTION((MSExperiment()))
{
ptr = new PeakMap;
TEST_NOT_EQUAL(ptr, nullPointer);
}
END_SECTION
START_SECTION(([EXTRA]~MSExperiment()))
{
delete ptr;
}
END_SECTION
/////////////////////////////////////////////////////////////
// Copy constructor, move constructor, assignment operator, move assignment operator, equality
START_SECTION((MSExperiment(const MSExperiment& source)))
{
PeakMap tmp;
tmp.getContacts().resize(1);
tmp.getContacts()[0].setFirstName("Name");
tmp.resize(1);
PeakMap tmp2(tmp);
TEST_EQUAL(tmp2.getContacts().size(),1);
TEST_EQUAL(tmp2.getContacts()[0].getFirstName(),"Name");
TEST_EQUAL(tmp2.size(),1);
}
END_SECTION
START_SECTION((MSExperiment(const MSExperiment&& source)))
{
// Ensure that MSExperiment has a no-except move constructor (otherwise
// std::vector is inefficient and will copy instead of move).
// TODO: wont work for MSVS (yet)
#ifndef OPENMS_COMPILER_MSVC
TEST_EQUAL(noexcept(MSExperiment(std::declval<MSExperiment&&>())), true)
#endif
PeakMap tmp;
tmp.getContacts().resize(1);
tmp.getContacts()[0].setFirstName("Name");
tmp.resize(1);
//copy tmp so we can move one of them
PeakMap orig = tmp;
PeakMap tmp2(std::move(tmp));
TEST_EQUAL(tmp2.getContacts().size(),1);
TEST_EQUAL(tmp2.getContacts()[0].getFirstName(),"Name");
TEST_EQUAL(tmp2.size(),1);
// test move
TEST_EQUAL(tmp.size(),0);
}
END_SECTION
START_SECTION((MSExperiment& operator= (const MSExperiment& source)))
{
PeakMap tmp;
tmp.getContacts().resize(1);
tmp.getContacts()[0].setFirstName("Name");
tmp.resize(1);
Peak1D p;
p.setMZ(5.0);
tmp[0].push_back(p);
p.setMZ(10.0);
tmp[0].push_back(p);
tmp.updateRanges();
PeakMap tmp2;
tmp2 = tmp;
TEST_EQUAL(tmp2.getContacts().size(),1);
TEST_EQUAL(tmp2.getContacts()[0].getFirstName(),"Name");
TEST_EQUAL(tmp2.size(),1);
TEST_REAL_SIMILAR(tmp2.getMinMZ(),5.0);
TEST_REAL_SIMILAR(tmp2.getMaxMZ(),10.0);
tmp2 = PeakMap();
TEST_EQUAL(tmp2.getContacts().size(),0);
TEST_EQUAL(tmp2.size(),0);
}
END_SECTION
START_SECTION((MSExperiment& operator= (const MSExperiment&& source)))
{
PeakMap tmp;
tmp.getContacts().resize(1);
tmp.getContacts()[0].setFirstName("Name");
tmp.resize(1);
Peak1D p;
p.setMZ(5.0);
tmp[0].push_back(p);
p.setMZ(10.0);
tmp[0].push_back(p);
tmp.updateRanges();
//copy tmp so we can move one of them
PeakMap orig = tmp;
PeakMap tmp2 = std::move(tmp);
TEST_EQUAL(tmp2, orig); // should be equal to the original
TEST_EQUAL(tmp2.getContacts().size(),1);
TEST_EQUAL(tmp2.getContacts()[0].getFirstName(),"Name");
TEST_EQUAL(tmp2.size(),1);
TEST_REAL_SIMILAR(tmp2.getMinMZ(),5.0);
TEST_REAL_SIMILAR(tmp2.getMaxMZ(),10.0);
// test move
TEST_EQUAL(tmp.size(),0);
tmp2 = PeakMap(); // use rvalue assignment
TEST_EQUAL(tmp2.getContacts().size(),0);
TEST_EQUAL(tmp2.size(),0);
}
END_SECTION
START_SECTION((bool operator== (const MSExperiment& rhs) const))
{
PeakMap edit,empty;
TEST_TRUE(edit == empty);
edit.getContacts().resize(1);
TEST_EQUAL(edit==empty, false);
edit = empty;
edit.resize(1);
TEST_EQUAL(edit==empty, false);
}
END_SECTION
START_SECTION((bool operator!= (const MSExperiment& rhs) const))
{
PeakMap edit,empty;
TEST_EQUAL(edit!=empty, false);
edit.getContacts().resize(1);
TEST_FALSE(edit == empty);
edit = empty;
edit.resize(1);
TEST_FALSE(edit == empty);
}
END_SECTION
START_SECTION((template<class Container> void get2DData(Container& cont) const))
{
PeakMap exp;
PeakMap::SpectrumType spec;
PeakMap::PeakType peak;
// first spectrum (MS)
spec.setRT(11.1);
spec.setMSLevel(1);
peak.getPosition()[0] = 5;
peak.setIntensity(47.11f);
spec.push_back(peak);
peak.getPosition()[0] = 10;
peak.setIntensity(48.11f);
spec.push_back(peak);
peak.getPosition()[0] = 15;
spec.push_back(peak);
exp.addSpectrum(spec);
// second spectrum (MS/MS)
spec.clear(true);
spec.setRT(11.5);
spec.setMSLevel(2);
peak.getPosition()[0] = 6;
spec.push_back(peak);
peak.getPosition()[0] = 11;
spec.push_back(peak);
exp.addSpectrum(spec);
// third spectrum (MS)
spec.clear(true);
spec.setRT(12.2);
spec.setMSLevel(1);
peak.getPosition()[0] = 20;
spec.push_back(peak);
peak.getPosition()[0] = 25;
spec.push_back(peak);
exp.addSpectrum(spec);
// forth spectrum (MS/MS)
spec.clear(true);
spec.setRT(12.5);
spec.setMSLevel(2);
peak.getPosition()[0] = 21;
spec.push_back(peak);
peak.getPosition()[0] = 26;
spec.push_back(peak);
peak.getPosition()[0] = 31;
spec.push_back(peak);
exp.addSpectrum(spec);
//Convert
std::vector<Peak2D> a;
exp.get2DData(a);
//Tests
TEST_EQUAL(a.size(),5);
TEST_REAL_SIMILAR(a[0].getRT(),11.1);
TEST_REAL_SIMILAR(a[0].getMZ(),5);
TEST_REAL_SIMILAR(a[0].getIntensity(),47.11);
TEST_REAL_SIMILAR(a[1].getRT(),11.1);
TEST_REAL_SIMILAR(a[1].getMZ(),10);
TEST_REAL_SIMILAR(a[1].getIntensity(),48.11);
TEST_REAL_SIMILAR(a[2].getRT(),11.1);
TEST_REAL_SIMILAR(a[2].getMZ(),15);
TEST_REAL_SIMILAR(a[3].getRT(),12.2);
TEST_REAL_SIMILAR(a[3].getMZ(),20);
TEST_REAL_SIMILAR(a[4].getRT(),12.2);
TEST_REAL_SIMILAR(a[4].getMZ(),25);
//Convert
std::vector<Peak2D> list;
exp.get2DData(list);
//Tests
TEST_EQUAL(list.size(),5);
std::vector<Peak2D>::const_iterator it = list.begin();
TEST_REAL_SIMILAR(it->getRT(),11.1);
TEST_REAL_SIMILAR(it->getMZ(),5);
TEST_REAL_SIMILAR(it->getIntensity(),47.11);
++it;
TEST_REAL_SIMILAR(it->getRT(),11.1);
TEST_REAL_SIMILAR(it->getMZ(),10);
TEST_REAL_SIMILAR(it->getIntensity(),48.11);
++it;
TEST_REAL_SIMILAR(it->getRT(),11.1);
TEST_REAL_SIMILAR(it->getMZ(),15);
++it;
TEST_REAL_SIMILAR(it->getRT(),12.2);
TEST_REAL_SIMILAR(it->getMZ(),20);
++it;
TEST_REAL_SIMILAR(it->getRT(),12.2);
TEST_REAL_SIMILAR(it->getMZ(),25);
}
END_SECTION
START_SECTION((template <class Container> void set2DData(const Container& cont, const StringList& store_metadata_names = StringList())))
{
NOT_TESTABLE // tested below
}
END_SECTION
START_SECTION((template <bool add_mass_traces, class Container> void set2DData(const Container& cont, const StringList& store_metadata_names = StringList())))
{
PeakMap exp;
// create sample data
std::vector<Peak2D> input;
Peak2D p1(Peak2D::PositionType(2.0, 3.0), 1.0);
input.push_back(p1);
Peak2D p2(Peak2D::PositionType(5.0, 6.0), 4.0);
input.push_back(p2);
Peak2D p3(Peak2D::PositionType(8.5, 9.5), 7.5);
input.push_back(p3);
exp.set2DData(input);
// retrieve data again and check for changes
std::vector<Peak2D> output;
exp.get2DData(output);
TEST_EQUAL(output==input,true);
//////////////////////////////////////////////////////////////////////////
// test if meta values are added as floatDataArrays in MSSpectra
std::vector<RichPeak2D> inputr;
RichPeak2D pr1(RichPeak2D::PositionType(2.0, 3.0), 1.0);
pr1.setMetaValue("meta1", 111.1);
inputr.push_back(pr1);
RichPeak2D pr2(RichPeak2D::PositionType(5.0, 6.0), 4.0);
inputr.push_back(pr2);
RichPeak2D pr3(RichPeak2D::PositionType(8.5, 9.5), 7.5);
pr3.setMetaValue("meta3", 333.3);
inputr.push_back(pr3);
// create float data arrays for these two meta values (missing values in data will be set to NaN)
exp.set2DData(inputr, ListUtils::create<String>("meta1,meta3"));
TEST_EQUAL(exp.getNrSpectra(), 3);
// retrieve data again and check for changes
std::vector<Peak2D> outputr;
exp.get2DData(outputr);
TEST_TRUE(outputr == input); // we compare to non-meta output, since floatdata is not converted back to metavalues
// check for meta data
TEST_EQUAL(exp[0].getFloatDataArrays().size(), 2);
TEST_EQUAL(exp[0].getFloatDataArrays()[0][0], 111.1);
TEST_EQUAL(exp[1].getFloatDataArrays().size(), 2); // present but all NaN
TEST_EQUAL(exp[2].getFloatDataArrays().size(), 2);
TEST_EQUAL(exp[2].getFloatDataArrays()[1][0], 333.3);
///////////////////////////////////////
// test adding of mass traces
FeatureMap fm, fm2, fm_out;
Feature f1;
f1.setIntensity(7.5f);
f1.setRT(8.5);
f1.setMZ(9.5);
Feature f2;
f2.setIntensity(17.5f);
f2.setRT(18.5);
f2.setMZ(19.5);
fm.push_back(f1);
fm.push_back(f2);
fm2 = fm; // copy without meta values (get2DData will not have them)
fm.back().setMetaValue(Constants::UserParam::NUM_OF_MASSTRACES, 2);
fm.back().setMetaValue("masstrace_intensity_0", 11.0f);
fm.back().setMetaValue("masstrace_intensity_1", 12.0f);
fm.back().setCharge(2);
exp.set2DData<true>(fm);
exp.get2DData(fm_out);
Feature f2_x = f2;
f2_x.setIntensity(11.0f);
f2_x.setMZ(f2_x.getMZ() + Constants::C13C12_MASSDIFF_U/2*0);
fm2.back() = (f2_x); // replace
f2_x.setIntensity(12.0f);
f2_x.setMZ(f2_x.getMZ() + Constants::C13C12_MASSDIFF_U/2*1);
fm2.push_back(f2_x); // add +1Th trace
TEST_EQUAL(fm_out.size(), fm2.size());
//std::cout << fm_out[1] << "\n\n" << fm2[1] << std::endl;
//std::cout << fm_out.back() << "\n\n" << fm2.back() << std::endl;
TEST_EQUAL(fm_out==fm2,true);
// test precondition (input sorted by RT)
input.push_back(p1);
TEST_PRECONDITION_VIOLATED(exp.set2DData(input));
}
END_SECTION
START_SECTION(([EXTRA] PeakMap()))
{
PeakMap tmp;
tmp.resize(1);
tmp[0].resize(1);
tmp[0][0].getPosition()[0] = 47.11;
TEST_REAL_SIMILAR(tmp[0][0].getPosition()[0],47.11)
}
END_SECTION
START_SECTION((const std::vector<UInt>& getMSLevels() const))
{
PeakMap tmp;
TEST_EQUAL(tmp.getMSLevels().size(),0)
}
END_SECTION
START_SECTION((UInt64 getSize() const ))
{
PeakMap tmp;
TEST_EQUAL(tmp.getSize(),0)
}
END_SECTION
START_SECTION((const MSExperiment::RangeManagerType& MSExperiment::getRange() const))
{
PeakMap tmp;
TEST_EQUAL(tmp.combinedRanges().hasRange() == HasRangeType::NONE, true)
}
END_SECTION
START_SECTION((virtual void updateRanges()))
{
PeakMap tmp;
MSSpectrum s;
Peak1D p;
s.setMSLevel(1);
s.setRT(30.0);
p.getPosition()[0] = 5.0;
p.setIntensity(-5.0f);
s.push_back(p);
s.setDriftTime(99);
tmp.addSpectrum(s);
s.clear(true);
s.setMSLevel(1);
s.setRT(40.0);
p.getPosition()[0] = 7.0;
p.setIntensity(-7.0f);
s.push_back(p);
s.setDriftTime(99);
tmp.addSpectrum(s);
s.clear(true);
s.setMSLevel(3);
s.setRT(45.0);
p.getPosition()[0] = 9.0;
p.setIntensity(-10.0f);
s.push_back(p);
s.setDriftTime(199);
tmp.addSpectrum(s);
s.clear(true);
s.setMSLevel(3);
s.setRT(50.0);
p.getPosition()[0] = 10.0;
p.setIntensity(-9.0f);
s.push_back(p);
s.setDriftTime(66);
tmp.addSpectrum(s);
tmp.updateRanges();
tmp.updateRanges(); //second time to check the initialization
TEST_REAL_SIMILAR(tmp.getMinMZ(),5.0)
TEST_REAL_SIMILAR(tmp.getMaxMZ(),10.0)
TEST_REAL_SIMILAR(tmp.getMinIntensity(), -10.0)
TEST_REAL_SIMILAR(tmp.getMaxIntensity(), -5.0)
TEST_REAL_SIMILAR(tmp.getMinRT(),30.0)
TEST_REAL_SIMILAR(tmp.getMaxRT(),50.0)
TEST_EQUAL(tmp.getMSLevels().size(),2)
TEST_EQUAL(tmp.getMSLevels()[0],1)
TEST_EQUAL(tmp.getMSLevels()[1],3)
TEST_EQUAL(tmp.getSize(),4)
tmp.updateRanges();
TEST_REAL_SIMILAR(tmp.getMinMZ(),5.0)
TEST_REAL_SIMILAR(tmp.getMaxMZ(),10.0)
TEST_REAL_SIMILAR(tmp.getMinIntensity(), -10.0)
TEST_REAL_SIMILAR(tmp.getMaxIntensity(), -5.0)
TEST_REAL_SIMILAR(tmp.getMinRT(),30.0)
TEST_REAL_SIMILAR(tmp.getMaxRT(),50.0)
TEST_REAL_SIMILAR(tmp.combinedRanges().getMinMZ(), 5.0)
TEST_REAL_SIMILAR(tmp.combinedRanges().getMaxMZ(), 10.0)
TEST_REAL_SIMILAR(tmp.combinedRanges().getMinRT(), 30.0)
TEST_REAL_SIMILAR(tmp.combinedRanges().getMaxRT(), 50.0)
TEST_REAL_SIMILAR(tmp.combinedRanges().getMinMobility(), 66)
TEST_REAL_SIMILAR(tmp.combinedRanges().getMaxMobility(), 199)
TEST_EQUAL(tmp.getMSLevels().size(),2)
TEST_EQUAL(tmp.getMSLevels()[0],1)
TEST_EQUAL(tmp.getMSLevels()[1],3)
TEST_EQUAL(tmp.getSize(),4)
// Store initial MS levels
std::vector<UInt> initial_ms_levels = tmp.getMSLevels();
// MS1
for (int l = 0; l < 2; ++l)
{
TEST_REAL_SIMILAR(tmp.spectrumRanges().byMSLevel(1).getMinMZ(),5.0)
TEST_REAL_SIMILAR(tmp.spectrumRanges().byMSLevel(1).getMaxMZ(),7.0)
TEST_REAL_SIMILAR(tmp.spectrumRanges().byMSLevel(1).getMinIntensity(), -7.0)
TEST_REAL_SIMILAR(tmp.spectrumRanges().byMSLevel(1).getMaxIntensity(), -5.0)
TEST_REAL_SIMILAR(tmp.spectrumRanges().byMSLevel(1).getMinRT(),30.0)
TEST_REAL_SIMILAR(tmp.spectrumRanges().byMSLevel(1).getMaxRT(),40.0)
TEST_REAL_SIMILAR(tmp.spectrumRanges().byMSLevel(1).getMinMobility(), 99)
TEST_REAL_SIMILAR(tmp.spectrumRanges().byMSLevel(1).getMaxMobility(), 99)
// Verify MS levels remain unchanged
TEST_EQUAL(tmp.getMSLevels() == initial_ms_levels, true)
TEST_EQUAL(tmp.getSize(),4)
}
// test with only one peak
PeakMap tmp2;
MSSpectrum s2;
Peak1D p2;
s2.setRT(30.0);
p2.getPosition()[0] = 5.0;
p2.setIntensity(-5.0f);
s2.push_back(p2);
s2.setDriftTime(99);
tmp2.addSpectrum(s2);
tmp2.updateRanges();
// check the overall ranges
TEST_REAL_SIMILAR(tmp2.getMinMZ(),5.0)
TEST_REAL_SIMILAR(tmp2.getMaxMZ(),5.0)
TEST_REAL_SIMILAR(tmp2.getMinIntensity(), -5.0)
TEST_REAL_SIMILAR(tmp2.getMaxIntensity(), -5.0)
TEST_REAL_SIMILAR(tmp2.getMinRT(),30.0)
TEST_REAL_SIMILAR(tmp2.getMaxRT(),30.0)
TEST_REAL_SIMILAR(tmp2.getMinMobility(), 99)
TEST_REAL_SIMILAR(tmp2.getMaxMobility(), 99)
// check the spectra specific ranges
TEST_REAL_SIMILAR(tmp2.spectrumRanges().getMinMZ(),5.0)
TEST_REAL_SIMILAR(tmp2.spectrumRanges().getMaxMZ(),5.0)
TEST_REAL_SIMILAR(tmp2.spectrumRanges().getMinIntensity(), -5.0)
TEST_REAL_SIMILAR(tmp2.spectrumRanges().getMaxIntensity(), -5.0)
TEST_REAL_SIMILAR(tmp2.spectrumRanges().getMinRT(),30.0)
TEST_REAL_SIMILAR(tmp2.spectrumRanges().getMaxRT(),30.0)
TEST_REAL_SIMILAR(tmp2.spectrumRanges().getMinMobility(), 99)
TEST_REAL_SIMILAR(tmp2.spectrumRanges().getMaxMobility(), 99)
// test ranges with a chromatogram
MSChromatogram chrom1, chrom2;
ChromatogramPeak cp1, cp2, cp3;
cp1.setRT(0.3);
cp1.setIntensity(10.0f);
cp2.setRT(0.2);
cp2.setIntensity(10.2f);
cp3.setRT(0.1);
cp3.setIntensity(10.4f);
Product prod1;
prod1.setMZ(100.0);
chrom1.setProduct(prod1);
chrom1.push_back(cp1);
chrom1.push_back(cp2);
Product prod2;
prod2.setMZ(80.0);
chrom2.setProduct(prod2);
chrom2.push_back(cp2);
chrom2.push_back(cp3);
vector<MSChromatogram> chroms;
chroms.push_back(chrom1);
chroms.push_back(chrom2);
tmp2.setChromatograms(chroms);
tmp2.updateRanges();
// test the overall ranges
TEST_REAL_SIMILAR(tmp2.getMinMZ(), 5.0)
TEST_REAL_SIMILAR(tmp2.getMaxMZ(), 100.0)
TEST_REAL_SIMILAR(tmp2.getMinIntensity(), -5.0)
TEST_REAL_SIMILAR(tmp2.getMaxIntensity(), 10.4)
TEST_REAL_SIMILAR(tmp2.getMinRT(), 0.1)
TEST_REAL_SIMILAR(tmp2.getMaxRT(), 30.0) // overall range still 30
// test the chromatogram ranges
TEST_REAL_SIMILAR(tmp2.chromatogramRanges().getMinMZ(), 80.0)
TEST_REAL_SIMILAR(tmp2.chromatogramRanges().getMaxMZ(), 100.0)
TEST_REAL_SIMILAR(tmp2.chromatogramRanges().getMinIntensity(), 10.0)
TEST_REAL_SIMILAR(tmp2.chromatogramRanges().getMaxIntensity(), 10.4)
TEST_REAL_SIMILAR(tmp2.chromatogramRanges().getMinRT(), 0.1)
TEST_REAL_SIMILAR(tmp2.chromatogramRanges().getMaxRT(), 0.3) // chromatogram range 0.1-0.3
}
END_SECTION
START_SECTION((void updateRanges(Int ms_level)))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((ConstAreaIterator areaEndConst() const))
{
NOT_TESTABLE
}
END_SECTION
PeakMap exp_area;
{ // create some data for testing area iterator
std::vector< Peak2D> plist;
plist.push_back(Peak2D({-1.0, 2.0}, 0));
plist.push_back(Peak2D({1.0, 2.0}, 0));
plist.push_back(Peak2D({1.0, 3.0}, 0));
plist.push_back(Peak2D({2.0, 10.0}, 0));
plist.push_back(Peak2D({2.0, 11.0}, 0));
plist.push_back(Peak2D({2.0, 12.0}, 0));
exp_area.set2DData(plist);
int dt{0};
for (auto& spec : exp_area.getSpectra())
{
spec.setDriftTime(dt++);
}
}
START_SECTION((ConstAreaIterator areaBeginConst(CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz) const))
{
const auto& exp = exp_area;
PeakMap::ConstAreaIterator it = exp.areaBeginConst(0,15,0,11);
TEST_EQUAL(it->getPosition()[0],2.0)
it++;
TEST_EQUAL(it->getPosition()[0],3.0)
it++;
TEST_EQUAL(it->getPosition()[0],10.0)
it++;
TEST_EQUAL(it->getPosition()[0],11.0)
it++;
TEST_EQUAL(it==exp.areaEndConst(),true)
TEST_PRECONDITION_VIOLATED(exp.areaBeginConst(15,0,0,15))
TEST_PRECONDITION_VIOLATED(exp.areaBeginConst(0,15,15,0))
TEST_PRECONDITION_VIOLATED(exp.areaBeginConst(15,0,15,0))
}
END_SECTION
START_SECTION(MSExperiment::ConstAreaIterator MSExperiment::areaBeginConst(const RangeManagerType& range) const)
{
MSExperiment::RangeManagerType rm;
(RangeRT&)rm = RangeBase(0, 2);
(RangeMZ&)rm = RangeBase(3, 11);
const auto& exp = exp_area;
PeakMap::ConstAreaIterator it = exp.areaBeginConst(rm);
TEST_EQUAL(it->getPosition()[0], 3.0)
++it;
TEST_EQUAL(it->getPosition()[0], 10.0)
++it;
TEST_EQUAL(it->getPosition()[0], 11.0)
++it;
TEST_EQUAL(it == exp.areaEndConst(), true)
// add mobility as constraint
(RangeMobility&)rm = RangeBase(2, 2);
it = exp.areaBeginConst(rm);
TEST_EQUAL(it->getPosition()[0], 10.0)
++it;
TEST_EQUAL(it->getPosition()[0], 11.0)
++it;
TEST_EQUAL(it == exp.areaEndConst(), true)
}
END_SECTION
START_SECTION((AreaIterator areaEnd()))
{
NOT_TESTABLE
}
END_SECTION
START_SECTION((AreaIterator areaBegin(CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz)))
{
auto exp = exp_area;
PeakMap::AreaIterator it = exp.areaBegin(0,15,0,11);
TEST_EQUAL(it->getPosition()[0],2.0)
it->getPosition()[0] = 4711.0;
TEST_EQUAL(it->getPosition()[0],4711.0)
++it;
TEST_EQUAL(it->getPosition()[0],3.0)
++it;
TEST_EQUAL(it->getPosition()[0],10.0)
++it;
TEST_EQUAL(it->getPosition()[0],11.0)
++it;
TEST_EQUAL(it==exp.areaEnd(),true)
TEST_PRECONDITION_VIOLATED(exp.areaBegin(15,0,0,15))
TEST_PRECONDITION_VIOLATED(exp.areaBegin(0,15,15,0))
TEST_PRECONDITION_VIOLATED(exp.areaBegin(15,0,15,0))
}
END_SECTION
START_SECTION(MSExperiment::AreaIterator MSExperiment::areaBegin(const RangeManagerType& range))
{
MSExperiment::RangeManagerType rm;
(RangeRT&)rm = RangeBase(0, 2);
(RangeMZ&)rm = RangeBase(3, 11);
auto exp = exp_area;
PeakMap::AreaIterator it = exp.areaBegin(rm);
TEST_EQUAL(it->getPosition()[0], 3.0)
++it;
TEST_EQUAL(it->getPosition()[0], 10.0)
++it;
TEST_EQUAL(it->getPosition()[0], 11.0)
++it;
TEST_EQUAL(it == exp.areaEnd(), true)
// add mobility as constraint
(RangeMobility&)rm = RangeBase(2, 2);
it = exp.areaBegin(rm);
TEST_EQUAL(it->getPosition()[0], 10.0)
++it;
TEST_EQUAL(it->getPosition()[0], 11.0)
++it;
TEST_EQUAL(it == exp.areaEnd(), true)
}
END_SECTION
START_SECTION((Iterator RTBegin(CoordinateType rt)))
{
PeakMap tmp = createPeakMapWithRTs({30, 40, 45, 50});
PeakMap::Iterator it;
it = tmp.RTBegin(20.0);
TEST_REAL_SIMILAR(it->getRT(),30.0)
it = tmp.RTBegin(30.0);
TEST_REAL_SIMILAR(it->getRT(),30.0)
it = tmp.RTBegin(31.0);
TEST_REAL_SIMILAR(it->getRT(),40.0)
TEST_TRUE(tmp.RTBegin(55.0) == tmp.end())
}
END_SECTION
START_SECTION((Iterator RTEnd(CoordinateType rt)))
{
PeakMap tmp = createPeakMapWithRTs({30, 40, 45, 50});
PeakMap::Iterator it;
it = tmp.RTEnd(20.0);
TEST_REAL_SIMILAR(it->getRT(),30.0)
it = tmp.RTEnd(30.0);
TEST_REAL_SIMILAR(it->getRT(),40.0)
it = tmp.RTEnd(31.0);
TEST_REAL_SIMILAR(it->getRT(),40.0)
TEST_TRUE(tmp.RTEnd(55.0) == tmp.end())
}
END_SECTION
START_SECTION(ConstIterator getClosestSpectrumInRT(const double RT) const)
{
const PeakMap tmp = createPeakMapWithRTs({30, 40, 45, 50});
PeakMap::ConstIterator it;
it = tmp.getClosestSpectrumInRT(-200.0);
TEST_TRUE(it == tmp.cbegin());
it = tmp.getClosestSpectrumInRT(20.0);
TEST_TRUE(it == tmp.cbegin());
it = tmp.getClosestSpectrumInRT(31.0);
TEST_TRUE(it == tmp.cbegin());
it = tmp.getClosestSpectrumInRT(34.9);
TEST_TRUE(it == tmp.cbegin());
it = tmp.getClosestSpectrumInRT(39);
TEST_TRUE(it == tmp.cbegin() + 1);
it = tmp.getClosestSpectrumInRT(41);
TEST_TRUE(it == tmp.cbegin() + 1);
it = tmp.getClosestSpectrumInRT(42.4);
TEST_TRUE(it == tmp.cbegin() + 1);
it = tmp.getClosestSpectrumInRT(44);
TEST_TRUE(it == tmp.cbegin() + 2);
it = tmp.getClosestSpectrumInRT(47);
TEST_TRUE(it == tmp.cbegin() + 2);
it = tmp.getClosestSpectrumInRT(47.6);
TEST_TRUE(it == tmp.cbegin() + 3);
it = tmp.getClosestSpectrumInRT(51);
TEST_TRUE(it == tmp.cbegin() + 3);
it = tmp.getClosestSpectrumInRT(5100000);
TEST_TRUE(it == tmp.cbegin() + 3);
const PeakMap tmp_empty;
it = tmp_empty.getClosestSpectrumInRT(47.6);
TEST_TRUE(it == tmp_empty.cend());
}
END_SECTION
START_SECTION(Iterator getClosestSpectrumInRT(const double RT))
{
// minimal version of the above, just to see if iterator types are correct
PeakMap tmp = createPeakMapWithRTs({30, 40, 45, 50});
PeakMap::Iterator it;
it = tmp.getClosestSpectrumInRT(-200.0);
TEST_TRUE(it == tmp.begin());
PeakMap tmp_empty;
it = tmp_empty.getClosestSpectrumInRT(47.6);
TEST_TRUE(it == tmp_empty.end());
}
END_SECTION
START_SECTION(ConstIterator getClosestSpectrumInRT(const double RT, UInt ms_level) const)
{
const PeakMap tmp = setMSLevel(createPeakMapWithRTs({30, 31, 32, 40, 41, 50, 60, 61}), {1, 2, 2, 1, 2, 1, 1, 2});
PeakMap::ConstIterator it;
it = tmp.getClosestSpectrumInRT(-200.0, 0); // MS-level 0 does not exist --> cend()
TEST_TRUE(it == tmp.cend());
it = tmp.getClosestSpectrumInRT(-200.0, 1);
TEST_TRUE(it == tmp.cbegin());
it = tmp.getClosestSpectrumInRT(-200.0, 2);
TEST_TRUE(it == tmp.cbegin() + 1);
it = tmp.getClosestSpectrumInRT(20.0, 1);
TEST_TRUE(it == tmp.cbegin());
it = tmp.getClosestSpectrumInRT(31.0, 1);
TEST_TRUE(it == tmp.cbegin());
it = tmp.getClosestSpectrumInRT(34.9, 1);
TEST_TRUE(it == tmp.cbegin());
it = tmp.getClosestSpectrumInRT(20.0, 2);
TEST_TRUE(it == tmp.cbegin() + 1);
it = tmp.getClosestSpectrumInRT(31.0, 2);
TEST_TRUE(it == tmp.cbegin() + 1);
it = tmp.getClosestSpectrumInRT(31.4, 2);
TEST_TRUE(it == tmp.cbegin() + 1);
it = tmp.getClosestSpectrumInRT(39, 1);
TEST_TRUE(it == tmp.cbegin() + 3);
it = tmp.getClosestSpectrumInRT(41, 1);
TEST_TRUE(it == tmp.cbegin() + 3);
it = tmp.getClosestSpectrumInRT(42.4, 1);
TEST_TRUE(it == tmp.cbegin() + 3);
it = tmp.getClosestSpectrumInRT(45.5, 1);
TEST_TRUE(it == tmp.cbegin() + 5);
it = tmp.getClosestSpectrumInRT(49, 1);
TEST_TRUE(it == tmp.cbegin() + 5);
it = tmp.getClosestSpectrumInRT(54.5, 1);
TEST_TRUE(it == tmp.cbegin() + 5);
it = tmp.getClosestSpectrumInRT(55.1, 1);
TEST_TRUE(it == tmp.cbegin() + 6);
it = tmp.getClosestSpectrumInRT(59.1, 1);
TEST_TRUE(it == tmp.cbegin() + 6);
it = tmp.getClosestSpectrumInRT(5100000, 1);
TEST_TRUE(it == tmp.cbegin() + 6);
it = tmp.getClosestSpectrumInRT(58, 2);
TEST_TRUE(it == tmp.cbegin() + 7);
it = tmp.getClosestSpectrumInRT(63, 2);
TEST_TRUE(it == tmp.cbegin() + 7);
it = tmp.getClosestSpectrumInRT(5100000, 2);
TEST_TRUE(it == tmp.cbegin() + 7);
const PeakMap tmp_empty;
it = tmp_empty.getClosestSpectrumInRT(47.6, 1);
TEST_TRUE(it == tmp_empty.cend());
}
END_SECTION
START_SECTION(Iterator getClosestSpectrumInRT(const double RT, UInt ms_level))
{
// minimal version of the above, just to see if iterator types are correct
PeakMap tmp = setMSLevel(createPeakMapWithRTs({30, 31, 32, 40, 41, 50, 60, 61}), {1, 2, 2, 1, 2, 1, 1, 2});
PeakMap::Iterator it;
it = tmp.getClosestSpectrumInRT(-200.0, 0); // MS-level 0 does not exist --> cend()
TEST_TRUE(it == tmp.cend());
it = tmp.getClosestSpectrumInRT(-200.0, 1);
TEST_TRUE(it == tmp.cbegin());
it = tmp.getClosestSpectrumInRT(-200.0, 2);
TEST_TRUE(it == tmp.cbegin() + 1);
PeakMap tmp_empty;
it = tmp_empty.getClosestSpectrumInRT(47.6, 1);
TEST_TRUE(it == tmp_empty.cend());
}
END_SECTION
START_SECTION((Iterator IMBegin(CoordinateType im)))
{
PeakMap tmp;
MSSpectrum s;
s.setDriftTime(30.0);
tmp.addSpectrum(s);
s.setDriftTime(40.0);
tmp.addSpectrum(s);
s.setDriftTime(45.0);
tmp.addSpectrum(s);
s.setDriftTime(50.0);
tmp.addSpectrum(s);
PeakMap::ConstIterator it;
it = tmp.IMBegin(20.0);
TEST_REAL_SIMILAR(it->getDriftTime(), 30.0)
it = tmp.IMBegin(30.0);
TEST_REAL_SIMILAR(it->getDriftTime(), 30.0)
it = tmp.IMBegin(31.0);
TEST_REAL_SIMILAR(it->getDriftTime(), 40.0)
TEST_EQUAL(tmp.IMBegin(55.0) == tmp.end(), true)
}
END_SECTION
START_SECTION((Iterator IMEnd(CoordinateType rt)))
{
PeakMap tmp;
MSSpectrum s;
s.setDriftTime(30.0);
tmp.addSpectrum(s);
s.setDriftTime(40.0);
tmp.addSpectrum(s);
s.setDriftTime(45.0);
tmp.addSpectrum(s);
s.setDriftTime(50.0);
tmp.addSpectrum(s);
PeakMap::ConstIterator it;
it = tmp.IMEnd(20.0);
TEST_REAL_SIMILAR(it->getDriftTime(), 30.0)
it = tmp.IMEnd(30.0);
TEST_REAL_SIMILAR(it->getDriftTime(), 40.0)
it = tmp.IMEnd(31.0);
TEST_REAL_SIMILAR(it->getDriftTime(), 40.0)
TEST_EQUAL(tmp.IMEnd(55.0) == tmp.end(), true)
}
END_SECTION
START_SECTION((ConstIterator RTBegin(CoordinateType rt) const))
{
PeakMap tmp;
MSSpectrum s;
s.setRT(30.0);
tmp.addSpectrum(s);
s.setRT(40.0);
tmp.addSpectrum(s);
s.setRT(45.0);
tmp.addSpectrum(s);
s.setRT(50.0);
tmp.addSpectrum(s);
PeakMap::Iterator it;
it = tmp.RTBegin(20.0);
TEST_REAL_SIMILAR(it->getRT(),30.0)
it = tmp.RTBegin(30.0);
TEST_REAL_SIMILAR(it->getRT(),30.0)
it = tmp.RTBegin(31.0);
TEST_REAL_SIMILAR(it->getRT(),40.0)
TEST_EQUAL(tmp.RTBegin(55.0) == tmp.end(), true)
}
END_SECTION
START_SECTION((ConstIterator RTEnd(CoordinateType rt) const))
{
PeakMap tmp;
MSSpectrum s;
s.setRT(30.0);
tmp.addSpectrum(s);
s.setRT(40.0);
tmp.addSpectrum(s);
s.setRT(45.0);
tmp.addSpectrum(s);
s.setRT(50.0);
tmp.addSpectrum(s);
PeakMap::Iterator it;
it = tmp.RTEnd(20.0);
TEST_REAL_SIMILAR(it->getRT(),30.0)
it = tmp.RTEnd(30.0);
TEST_REAL_SIMILAR(it->getRT(),40.0)
it = tmp.RTEnd(31.0);
TEST_REAL_SIMILAR(it->getRT(),40.0)
TEST_EQUAL(tmp.RTBegin(55.0) == tmp.end(), true)
}
END_SECTION
START_SECTION((void sortSpectra(bool sort_mz = true)))
{
std::vector< Peak2D> plist;
Peak2D p1;
p1.getPosition()[0] = 1.0;
p1.getPosition()[1] = 5.0;
plist.push_back(p1);
Peak2D p2;
p2.getPosition()[0] = 1.0;
p2.getPosition()[1] = 3.0;
plist.push_back(p2);
Peak2D p3;
p3.getPosition()[0] = 2.0;
p3.getPosition()[1] = 14.0;
plist.push_back(p3);
Peak2D p4;
p4.getPosition()[0] = 2.0;
p4.getPosition()[1] = 11.0;
plist.push_back(p4);
PeakMap exp;
exp.set2DData(plist);
exp.sortSpectra(true);
TEST_REAL_SIMILAR(exp[0][0].getMZ(),3.0);
TEST_REAL_SIMILAR(exp[0][1].getMZ(),5.0);
TEST_REAL_SIMILAR(exp[1][0].getMZ(),11.0);
TEST_REAL_SIMILAR(exp[1][1].getMZ(),14.0);
}
END_SECTION
START_SECTION(bool isSorted(bool check_mz = true ) const)
{
//make test dataset
PeakMap exp;
exp.resize(2);
exp[0].setRT(1.0);
exp[1].setRT(2.0);
Peak1D p;
p.setIntensity(1.0);
p.setMZ(1000.0);
exp[0].push_back(p);
exp[1].push_back(p);
p.setIntensity(1.0);
p.setMZ(1001.0);
exp[0].push_back(p);
exp[1].push_back(p);
p.setIntensity(1.0);
p.setMZ(1002.0);
exp[0].push_back(p);
exp[1].push_back(p);
//test with identical RTs
TEST_EQUAL(exp.isSorted(false),true)
TEST_EQUAL(exp.isSorted(),true)
//test with acending RTs
exp[0].setRT(1.0);
exp[1].setRT(2.0);
TEST_EQUAL(exp.isSorted(false),true)
TEST_EQUAL(exp.isSorted(),true)
//test with a reversed spectrum
reverse(exp[0].begin(),exp[0].end());
TEST_EQUAL(exp.isSorted(false),true)
TEST_EQUAL(exp.isSorted(),false)
//test with reversed RTs
reverse(exp.begin(),exp.end());
TEST_EQUAL(exp.isSorted(false),false)
TEST_EQUAL(exp.isSorted(),false)
}
END_SECTION
START_SECTION((void reset()))
{
std::vector< Peak2D> plist;
Peak2D p;
p.getPosition()[0] = 1.0;
p.getPosition()[1] = 5.0;
plist.push_back(p);
p.getPosition()[0] = 2.0;
p.getPosition()[1] = 3.0;
plist.push_back(p);
PeakMap exp;
exp.set2DData(plist);
exp.updateRanges();
exp.reset();
TEST_EQUAL(exp.empty(),true);
}
END_SECTION
START_SECTION((const ExperimentalSettings& getExperimentalSettings() const))
{
PeakMap exp;
exp.setComment("test");
TEST_EQUAL(exp.getExperimentalSettings().getComment(),"test");
}
END_SECTION
START_SECTION((ExperimentalSettings& getExperimentalSettings()))
{
PeakMap exp;
exp.getExperimentalSettings().setComment("test");
TEST_EQUAL(exp.getExperimentalSettings().getComment(),"test");
}
END_SECTION
START_SECTION((MSExperiment& operator=(const ExperimentalSettings &source)))
{
PeakMap exp,exp2;
exp.getExperimentalSettings().setComment("test");
exp2 = exp.getExperimentalSettings();
TEST_EQUAL(exp2.getExperimentalSettings().getComment(),"test");
}
END_SECTION
START_SECTION((ConstIterator getPrecursorSpectrum(ConstIterator iterator) const))
{
PeakMap exp;
exp.resize(10);
exp[0].setMSLevel(1);
exp[1].setMSLevel(2);
exp[2].setMSLevel(1);
exp[3].setMSLevel(2);
exp[4].setMSLevel(2);
TEST_EQUAL(exp.getPrecursorSpectrum(exp.begin())==exp.end(),true)
TEST_EQUAL(exp.getPrecursorSpectrum(exp.begin()+1)==exp.begin(),true)
TEST_EQUAL(exp.getPrecursorSpectrum(exp.begin()+2)==exp.end(),true)
TEST_EQUAL(exp.getPrecursorSpectrum(exp.begin()+3)==exp.begin()+2,true)
TEST_EQUAL(exp.getPrecursorSpectrum(exp.begin()+4)==exp.begin()+2,true)
TEST_EQUAL(exp.getPrecursorSpectrum(exp.end())==exp.end(),true)
exp[0].setMSLevel(2);
exp[1].setMSLevel(1);
exp[2].setMSLevel(1);
exp[3].setMSLevel(1);
exp[4].setMSLevel(1);
TEST_EQUAL(exp.getPrecursorSpectrum(exp.begin())==exp.end(),true)
TEST_EQUAL(exp.getPrecursorSpectrum(exp.begin()+1)==exp.end(),true)
TEST_EQUAL(exp.getPrecursorSpectrum(exp.begin()+2)==exp.end(),true)
TEST_EQUAL(exp.getPrecursorSpectrum(exp.begin()+3)==exp.end(),true)
TEST_EQUAL(exp.getPrecursorSpectrum(exp.begin()+4)==exp.end(),true)
TEST_EQUAL(exp.getPrecursorSpectrum(exp.end())==exp.end(),true)
}
END_SECTION
START_SECTION((int getPrecursorSpectrum(int zero_based_index) const))
{
PeakMap exp;
exp.resize(10);
exp[0].setMSLevel(1);
exp[1].setMSLevel(2);
exp[2].setMSLevel(1);
exp[3].setMSLevel(2);
exp[4].setMSLevel(2);
TEST_EQUAL(exp.getPrecursorSpectrum(0) == -1,true)
TEST_EQUAL(exp.getPrecursorSpectrum(1) == 0,true)
TEST_EQUAL(exp.getPrecursorSpectrum(2) == -1,true)
TEST_EQUAL(exp.getPrecursorSpectrum(3) == 2,true)
TEST_EQUAL(exp.getPrecursorSpectrum(4) == 2,true)
exp[0].setMSLevel(2);
exp[1].setMSLevel(1);
exp[2].setMSLevel(1);
exp[3].setMSLevel(1);
exp[4].setMSLevel(1);
TEST_EQUAL(exp.getPrecursorSpectrum(0) == -1,true)
TEST_EQUAL(exp.getPrecursorSpectrum(1) == -1,true)
TEST_EQUAL(exp.getPrecursorSpectrum(2) == -1,true)
TEST_EQUAL(exp.getPrecursorSpectrum(3) == -1,true)
TEST_EQUAL(exp.getPrecursorSpectrum(4) == -1,true)
}
END_SECTION
START_SECTION((ConstIterator getFirstProductSpectrum(ConstIterator iterator) const))
{
PeakMap exp;
exp.resize(5);
// Set MS levels
exp[0].setMSLevel(1);
exp[1].setMSLevel(2);
exp[2].setMSLevel(1);
exp[3].setMSLevel(2);
exp[4].setMSLevel(2);
// Set NativeIDs
exp[0].setNativeID("scan=1");
exp[1].setNativeID("scan=2");
exp[2].setNativeID("scan=3");
exp[3].setNativeID("scan=4");
exp[4].setNativeID("scan=5");
// Set up the 'spectrum_ref' in the precursors of the product spectra
Precursor precursor1;
precursor1.setMetaValue("spectrum_ref", "scan=1"); // Reference to exp[0]
exp[1].getPrecursors().push_back(precursor1);
Precursor precursor2;
precursor2.setMetaValue("spectrum_ref", "scan=3"); // Reference to exp[2]
exp[3].getPrecursors().push_back(precursor2);
Precursor precursor3;
precursor3.setMetaValue("spectrum_ref", "scan=3"); // Another reference to exp[2]
exp[4].getPrecursors().push_back(precursor3);
// Test getFirstProductSpectrum
// From exp[0], expect to get exp[1] as the first product spectrum
TEST_EQUAL(exp.getFirstProductSpectrum(exp.begin()) == exp.begin() + 1, true)
// From exp[1], expect to get spectra_.end() since there is no higher MS level
TEST_EQUAL(exp.getFirstProductSpectrum(exp.begin() + 1) == exp.end(), true)
// From exp[2], expect to get exp[3] as the first product spectrum
TEST_EQUAL(exp.getFirstProductSpectrum(exp.begin() + 2) == exp.begin() + 3, true)
// From exp[3], expect to get spectra_.end() since there is no higher MS level
TEST_EQUAL(exp.getFirstProductSpectrum(exp.begin() + 3) == exp.end(), true)
// From exp[4], expect to get spectra_.end()
TEST_EQUAL(exp.getFirstProductSpectrum(exp.begin() + 4) == exp.end(), true)
// Test when iterator is spectra_.end()
TEST_EQUAL(exp.getFirstProductSpectrum(exp.end()) == exp.end(), true)
// Now change the MS levels to only MS1 spectra
for (Size i = 0; i < exp.size(); ++i)
{
exp[i].setMSLevel(1);
}
// Test again with only MS1 spectra
TEST_EQUAL(exp.getFirstProductSpectrum(exp.begin()) == exp.end(), true)
TEST_EQUAL(exp.getFirstProductSpectrum(exp.begin() + 1) == exp.end(), true)
TEST_EQUAL(exp.getFirstProductSpectrum(exp.begin() + 2) == exp.end(), true)
TEST_EQUAL(exp.getFirstProductSpectrum(exp.begin() + 3) == exp.end(), true)
TEST_EQUAL(exp.getFirstProductSpectrum(exp.begin() + 4) == exp.end(), true)
}
END_SECTION
START_SECTION((int getFirstProductSpectrum(int zero_based_index) const))
{
PeakMap exp;
exp.resize(5);
// Set MS levels
exp[0].setMSLevel(1);
exp[1].setMSLevel(2);
exp[2].setMSLevel(1);
exp[3].setMSLevel(2);
exp[4].setMSLevel(2);
// Set NativeIDs
exp[0].setNativeID("scan=1");
exp[1].setNativeID("scan=2");
exp[2].setNativeID("scan=3");
exp[3].setNativeID("scan=4");
exp[4].setNativeID("scan=5");
// Set up the 'spectrum_ref' in the precursors of the product spectra
Precursor precursor1;
precursor1.setMetaValue("spectrum_ref", "scan=1"); // Reference to exp[0]
exp[1].getPrecursors().push_back(precursor1);
Precursor precursor2;
precursor2.setMetaValue("spectrum_ref", "scan=3"); // Reference to exp[2]
exp[3].getPrecursors().push_back(precursor2);
Precursor precursor3;
precursor3.setMetaValue("spectrum_ref", "scan=3"); // Another reference to exp[2]
exp[4].getPrecursors().push_back(precursor3);
// Test getFirstProductSpectrum
// From index 0, expect to get index 1
TEST_EQUAL(exp.getFirstProductSpectrum(0) == 1, true)
// From index 1, expect to get -1 (no higher MS level with reference)
TEST_EQUAL(exp.getFirstProductSpectrum(1) == -1, true)
// From index 2, expect to get index 3
TEST_EQUAL(exp.getFirstProductSpectrum(2) == 3, true)
// From index 3, expect to get -1
TEST_EQUAL(exp.getFirstProductSpectrum(3) == -1, true)
// From index 4, expect to get -1
TEST_EQUAL(exp.getFirstProductSpectrum(4) == -1, true)
// Now change the MS levels to only MS1 spectra
for (Size i = 0; i < exp.size(); ++i)
{
exp[i].setMSLevel(1);
}
// Test again with only MS1 spectra
TEST_EQUAL(exp.getFirstProductSpectrum(0) == -1, true)
TEST_EQUAL(exp.getFirstProductSpectrum(1) == -1, true)
TEST_EQUAL(exp.getFirstProductSpectrum(2) == -1, true)
TEST_EQUAL(exp.getFirstProductSpectrum(3) == -1, true)
TEST_EQUAL(exp.getFirstProductSpectrum(4) == -1, true)
}
END_SECTION
START_SECTION((bool clearMetaDataArrays()))
{
PeakMap exp;
exp.resize(5);
exp[0].getFloatDataArrays().resize(5);
exp[0].getIntegerDataArrays().resize(5);
exp[0].getStringDataArrays().resize(5);
exp.clearMetaDataArrays();
TEST_EQUAL(exp[0].getFloatDataArrays().size(),0)
TEST_EQUAL(exp[0].getIntegerDataArrays().size(),0)
TEST_EQUAL(exp[0].getStringDataArrays().size(),0)
}
END_SECTION
START_SECTION((void swap(MSExperiment &from)))
{
PeakMap exp1, exp2;
exp1.setComment("stupid comment");
exp1.resize(1);
exp1[0].setMSLevel(2);
exp1[0].resize(2);
exp1[0][0].setIntensity(0.5f);
exp1[0][1].setIntensity(1.7f);
exp1.updateRanges();
exp1.swap(exp2);
TEST_EQUAL(exp1.getComment(),"")
TEST_EQUAL(exp1.size(),0)
TEST_EQUAL(exp1.combinedRanges().hasRange() == HasRangeType::NONE, true)
TEST_EQUAL(exp1.getMSLevels().size(),0)
TEST_EQUAL(exp1.getSize(),0);
TEST_EQUAL(exp2.getComment(),"stupid comment")
TEST_EQUAL(exp2.size(),1)
TEST_REAL_SIMILAR(exp2.getMinIntensity(), 0.5)
TEST_EQUAL(exp2.getMSLevels().size(),1)
TEST_EQUAL(exp2.getSize(),2);
}
END_SECTION
START_SECTION(void clear(bool clear_meta_data))
{
PeakMap edit;
edit.getSample().setName("bla");
edit.resize(5);
edit.updateRanges();
edit.setMetaValue("label",String("bla"));
vector<MSChromatogram > tmp;
tmp.resize(5);
edit.setChromatograms(tmp);
edit.clear(false);
TEST_EQUAL(edit.size(),0)
TEST_EQUAL(edit == MSExperiment(),false)
edit.clear(true);
TEST_EQUAL(edit.empty(),true)
TEST_EQUAL(edit == MSExperiment(),true)
}
END_SECTION
START_SECTION(bool MSExperiment::isIMFrame() const)
{
PeakMap tmp;
MSSpectrum s;
constexpr double rt_all = 1;
s.setRT(rt_all);
s.setDriftTime(30.0);
tmp.addSpectrum(s);
s.setDriftTime(40.0);
tmp.addSpectrum(s);
s.setDriftTime(45.0);
tmp.addSpectrum(s);
s.setDriftTime(50.0);
tmp.addSpectrum(s);
TEST_TRUE(tmp.isIMFrame())
tmp[3].setRT(2); // changing RT ...
TEST_FALSE(tmp.isIMFrame());
tmp[3].setRT(rt_all); // undo
tmp[2].setDriftTime(tmp[1].getDriftTime()); // duplicate drift time
TEST_FALSE(tmp.isIMFrame());
tmp[3].setRT(2); // changing RT ...
tmp[2].setDriftTime(tmp[1].getDriftTime()); // duplicate drift time
TEST_FALSE(tmp.isIMFrame());
}
END_SECTION
START_SECTION((void sortChromatograms(bool sort_rt=true)))
{
PeakMap exp;
MSChromatogram chrom1, chrom2;
ChromatogramPeak p1, p2, p3;
p1.setRT(0.3);
p1.setIntensity(10.0f);
p2.setRT(0.2);
p2.setIntensity(10.2f);
p3.setRT(0.1);
p3.setIntensity(10.4f);
Product prod1;
prod1.setMZ(100.0);
chrom1.setProduct(prod1);
chrom1.push_back(p1);
chrom1.push_back(p2);
Product prod2;
prod2.setMZ(80.0);
chrom2.setProduct(prod2);
chrom2.push_back(p2);
chrom2.push_back(p3);
vector<MSChromatogram > chroms;
chroms.push_back(chrom1);
chroms.push_back(chrom2);
exp.setChromatograms(chroms);
TEST_EQUAL(exp.getChromatograms().size(), 2)
TEST_REAL_SIMILAR(exp.getChromatograms()[0].getMZ(), 100.0)
TEST_REAL_SIMILAR(exp.getChromatograms()[1].getMZ(), 80.0)
// first sort without rt
exp.sortChromatograms(false);
TEST_REAL_SIMILAR(exp.getChromatograms()[0].getMZ(), 80.0)
TEST_REAL_SIMILAR(exp.getChromatograms()[1].getMZ(), 100.0)
TEST_REAL_SIMILAR(exp.getChromatograms()[1][0].getRT(), 0.3)
TEST_REAL_SIMILAR(exp.getChromatograms()[1][1].getRT(), 0.2)
// now also sort rt
exp.sortChromatograms();
TEST_REAL_SIMILAR(exp.getChromatograms()[0].getMZ(), 80.0)
TEST_REAL_SIMILAR(exp.getChromatograms()[1].getMZ(), 100.0)
TEST_REAL_SIMILAR(exp.getChromatograms()[1][0].getRT(), 0.2)
TEST_REAL_SIMILAR(exp.getChromatograms()[1][1].getRT(), 0.3)
}
END_SECTION
START_SECTION((void setChromatograms(const std::vector< MSChromatogram > &chromatograms)))
{
PeakMap exp;
MSChromatogram chrom1, chrom2;
ChromatogramPeak p1, p2, p3;
p1.setRT(0.1);
p1.setIntensity(10.0f);
p2.setRT(0.2);
p2.setIntensity(10.2f);
p3.setRT(0.3);
p3.setIntensity(10.4f);
chrom1.push_back(p1);
chrom1.push_back(p2);
chrom2.push_back(p2);
chrom2.push_back(p3);
vector<MSChromatogram > chroms;
chroms.push_back(chrom1);
chroms.push_back(chrom2);
exp.setChromatograms(chroms);
TEST_EQUAL(exp.getChromatograms().size(), 2)
TEST_EQUAL(exp.getChromatograms()[0] == chrom1, true)
TEST_EQUAL(exp.getChromatograms()[1] == chrom2, true)
}
END_SECTION
START_SECTION((void addChromatogram(const MSChromatogram &chromatogram)))
{
PeakMap exp;
MSChromatogram chrom1, chrom2;
ChromatogramPeak p1, p2, p3;
p1.setRT(0.1);
p1.setIntensity(10.0f);
p2.setRT(0.2);
p2.setIntensity(10.2f);
p3.setRT(0.3);
p3.setIntensity(10.4f);
chrom1.push_back(p1);
chrom1.push_back(p2);
chrom2.push_back(p2);
chrom2.push_back(p3);
TEST_EQUAL(exp.getChromatograms().size(), 0)
exp.addChromatogram(chrom1);
TEST_EQUAL(exp.getChromatograms().size(), 1)
TEST_EQUAL(exp.getChromatograms()[0] == chrom1, true)
exp.addChromatogram(chrom2);
TEST_EQUAL(exp.getChromatograms().size(), 2)
TEST_EQUAL(exp.getChromatograms()[0] == chrom1, true)
TEST_EQUAL(exp.getChromatograms()[1] == chrom2, true)
}
END_SECTION
START_SECTION((const std::vector<MSChromatogram >& getChromatograms() const))
{
NOT_TESTABLE // tested above
}
END_SECTION
START_SECTION((std::vector<MSChromatogram >& getChromatograms()))
{
PeakMap exp;
vector<MSChromatogram > chromatograms(2);
exp.getChromatograms().swap(chromatograms);
TEST_EQUAL(exp.getChromatograms().size(), 2);
TEST_EQUAL(chromatograms.size(), 0);
exp.getChromatograms().swap(chromatograms);
TEST_EQUAL(exp.getChromatograms().size(), 0);
TEST_EQUAL(chromatograms.size(), 2);
}
END_SECTION
START_SECTION((const MSChromatogram calculateTIC(float rt_bin_size=0) const))
{
MSChromatogram chrom;
// Dummy peakmap
PeakMap exp;
exp.resize(4);
Peak1D p;
// MS spectrum at RT = 0
p.setMZ(5.0);
p.setIntensity(3);
exp[0].push_back(p);
p.setMZ(10.0);
p.setIntensity(5);
exp[0].push_back(p);
exp[0].setMSLevel(1);
exp[0].setRT(0);
// MS spectrum at RT = 2
p.setMZ(5.0);
p.setIntensity(2);
exp[1].push_back(p);
exp[1].setMSLevel(1);
exp[1].setRT(2);
// MSMS spectrum at RT = 2
p.setMZ(5.0);
p.setIntensity(0.5);
exp[2].push_back(p);
exp[2].setMSLevel(2);
exp[2].setRT(2);
// MS spectrum at RT = 5
p.setMZ(5.0);
p.setIntensity(2.0);
exp[3].push_back(p);
p.setMZ(10.0);
p.setIntensity(3.0);
exp[3].push_back(p);
p.setMZ(15.0);
p.setIntensity(4.0);
exp[3].push_back(p);
exp[3].setMSLevel(1);
exp[3].setRT(5);
exp.updateRanges();
// empty MSExperiment
MSExperiment exp2;
chrom = exp2.calculateTIC();
TEST_EQUAL(chrom.empty(),true);
// no binning
chrom = exp.calculateTIC();
ABORT_IF(chrom.size() != 3);
TEST_EQUAL(chrom[0].getIntensity(),8);
TEST_EQUAL(chrom[1].getIntensity(),2);
TEST_EQUAL(chrom[2].getIntensity(),9);
// bin size smaller than highest RT
chrom = exp.calculateTIC(2.0);
ABORT_IF(chrom.size() != 4);
TEST_EQUAL(chrom[0].getIntensity(),8);
TEST_EQUAL(chrom[1].getIntensity(),2);
// Intensity at RT = 5 in between new data points at 4.0 and 6.0
TEST_EQUAL(chrom[2].getIntensity(),4.5);
TEST_EQUAL(chrom[3].getIntensity(),4.5);
// bin size bigger than highest RT
chrom = exp.calculateTIC(6.0);
ABORT_IF(chrom.size() != 2);
// Intensities at RT = 2 and RT = 5 in between new data points at 0.0 and 6.0
TEST_REAL_SIMILAR(chrom[0].getIntensity(),8.0 + 2.0* 4.0/6.0 + 9 * 1.0/6.0);
TEST_REAL_SIMILAR(chrom[1].getIntensity(),2.0* 2.0/6.0 + 9 * 5.0/6.0);
// negative bin size
chrom = exp.calculateTIC(-1.0);
// should be like no bin size was given
ABORT_IF(chrom.size() != 3);
TEST_EQUAL(chrom[0].getIntensity(),8);
TEST_EQUAL(chrom[1].getIntensity(),2);
TEST_EQUAL(chrom[2].getIntensity(),9);
}
END_SECTION
START_SECTION( std::ostream& operator<<(std::ostream& os, const MSExperiment& chrom))
{
PeakMap tmp;
tmp.getContacts().resize(1);
tmp.getContacts()[0].setFirstName("Name");
tmp.resize(1);
Peak1D p;
p.setMZ(5.0);
tmp[0].push_back(p);
p.setMZ(10.77);
tmp[0].push_back(p);
MSChromatogram a;
MSChromatogram::PeakType peak;
peak.getPosition()[0] = 47.11;
a.push_back(peak);
tmp.addChromatogram(a);
std::ostringstream os;
os << tmp;
TEST_EQUAL(String(os.str()).hasSubstring("MSEXPERIMENT BEGIN"), true);
TEST_EQUAL(String(os.str()).hasSubstring("MSSPECTRUM BEGIN"), true);
TEST_EQUAL(String(os.str()).hasSubstring("MSCHROMATOGRAM BEGIN"), true);
TEST_EQUAL(String(os.str()).hasSubstring("47.11"), true);
TEST_EQUAL(String(os.str()).hasSubstring("10.77"), true);
}
END_SECTION
START_SECTION((template<class MzReductionFunctionType> std::vector<std::vector<MSExperiment::CoordinateType>> aggregate(const std::vector<std::pair<RangeMZ, RangeRT>>& mz_rt_ranges, unsigned int ms_level, MzReductionFunctionType func_mz_reduction) const))
{
// Create test experiment with known data
PeakMap exp;
exp.resize(4);
// First spectrum (MS1) at RT=1.0
exp[0] = MSSpectrum{
{100.0, 1000.0},
{200.0, 2000.0},
{300.0, 3000.0}
};
exp[0].setRT(1.0);
exp[0].setMSLevel(1);
// Second spectrum (MS2) at RT=2.0
exp[1] = MSSpectrum{
{150.0, 1500.0},
{250.0, 2500.0}
};
exp[1].setRT(2.0);
exp[1].setMSLevel(2);
// Third spectrum (MS1) at RT=3.0
exp[2] = MSSpectrum{
{100.0, 1100.0},
{200.0, 2100.0},
{300.0, 3100.0}
};
exp[2].setRT(3.0);
exp[2].setMSLevel(1);
// Fourth spectrum (MS1) at RT=4.0
exp[3] = MSSpectrum{
{100.0, 1200.0},
{200.0, 2200.0},
{300.0, 3200.0}
};
exp[3].setRT(4.0);
exp[3].setMSLevel(1);
exp.updateRanges();
// Test: Normal case - MS1 spectra
{
std::vector<std::pair<RangeMZ, RangeRT>> ranges;
// Range 1: covers first peak of first and third spectrum
ranges.push_back(std::make_pair(
RangeMZ(90.0, 110.0),
RangeRT(0.0, 3.5)
));
// Range 2: covers second peak of all MS1 spectra
ranges.push_back(std::make_pair(
RangeMZ(190.0, 210.0),
RangeRT(0.0, 5.0)
));
// Simple intensity reduction function
auto result = exp.aggregate(ranges, 1,
[](MSSpectrum::ConstIterator begin_it, MSSpectrum::ConstIterator /*end_it*/)->double // return first intensity of peaks in m/z range
{
return begin_it->getIntensity();
});
// Check results
TEST_EQUAL(result.size(), 2);
// Check Range 1 results
TEST_EQUAL(result[0].size(), 2); // Should cover 2 spectra
TEST_EQUAL(result[0][0], 1000.0); // First spectrum intensity
TEST_EQUAL(result[0][1], 1100.0); // Third spectrum intensity
// Check Range 2 results
TEST_EQUAL(result[1].size(), 3); // Should cover 3 spectra
TEST_EQUAL(result[1][0], 2000.0); // First spectrum intensity
TEST_EQUAL(result[1][1], 2100.0); // Third spectrum intensity
TEST_EQUAL(result[1][2], 2200.0); // Fourth spectrum intensity
}
// Test 4: MS2 spectra
{
std::vector<std::pair<RangeMZ, RangeRT>> ranges;
ranges.push_back(std::make_pair(
RangeMZ(140.0, 160.0),
RangeRT(1.5, 2.5)
));
auto result = exp.aggregate(ranges, 2,
[](const MSSpectrum::ConstIterator begin_it, const MSSpectrum::ConstIterator /*end_it*/)->double // return first intensity of peaks in m/z range
{
return begin_it->getIntensity();
});
TEST_EQUAL(result.size(), 1);
TEST_EQUAL(result[0].size(), 1);
TEST_EQUAL(result[0][0], 1500.0);
}
// Test 5: Complex reduction function (average intensity)
{
std::vector<std::pair<RangeMZ, RangeRT>> ranges;
ranges.push_back(std::make_pair(
RangeMZ(90.0, 310.0), // Covers all peaks
RangeRT(0.0, 5.0) // Covers all spectra
));
// mean intensity in m/z range
auto result = exp.aggregate(ranges, 1,
[](const MSSpectrum::ConstIterator begin_it, const MSSpectrum::ConstIterator end_it)
{
if (begin_it == end_it) return 0.0; // Check for empty range before accumulation
double acc = std::accumulate(begin_it, end_it, 0.0,
[](double a, const Peak1D& b) { return a + b.getIntensity(); });
return acc / static_cast<double>(std::distance(begin_it, end_it));
});
TEST_EQUAL(result.size(), 1);
TEST_EQUAL(result[0].size(), 3);
TEST_REAL_SIMILAR(result[0][0], 2000.0); // Average of first spectrum
TEST_REAL_SIMILAR(result[0][1], 2100.0); // Average of third spectrum
TEST_REAL_SIMILAR(result[0][2], 2200.0); // Average of fourth spectrum
}
}
END_SECTION
START_SECTION((void get2DPeakDataPerSpectrum(CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz, Size ms_level, std::vector<float>& rt, std::vector<std::vector<float>>& mz, std::vector<std::vector<float>>& intensity) const))
{
MSExperiment exp;
// Create test spectra using initializer lists
MSSpectrum s1{
{100.0, 1000.0},
{200.0, 2000.0}
};
s1.setRT(1.0);
s1.setMSLevel(1);
MSSpectrum s2{
{150.0, 1500.0},
{250.0, 2500.0}
};
s2.setRT(2.0);
s2.setMSLevel(1);
MSSpectrum s3{
{175.0, 1750.0}
};
s3.setRT(3.0);
s3.setMSLevel(2);
exp.addSpectrum(s1);
exp.addSpectrum(s2);
exp.addSpectrum(s3);
// Test 1: Full range, MS level 1
{
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity;
exp.get2DPeakDataPerSpectrum(0.0, 4.0, 0.0, 300.0, 1, rt, mz, intensity);
TEST_EQUAL(rt.size(), 2)
TEST_EQUAL(mz.size(), 2)
TEST_EQUAL(intensity.size(), 2)
// Check first spectrum
TEST_REAL_SIMILAR(rt[0], 1.0)
TEST_EQUAL(mz[0].size(), 2)
TEST_REAL_SIMILAR(mz[0][0], 100.0)
TEST_REAL_SIMILAR(mz[0][1], 200.0)
TEST_REAL_SIMILAR(intensity[0][0], 1000.0)
TEST_REAL_SIMILAR(intensity[0][1], 2000.0)
// Check second spectrum
TEST_REAL_SIMILAR(rt[1], 2.0)
TEST_EQUAL(mz[1].size(), 2)
TEST_REAL_SIMILAR(mz[1][0], 150.0)
TEST_REAL_SIMILAR(mz[1][1], 250.0)
TEST_REAL_SIMILAR(intensity[1][0], 1500.0)
TEST_REAL_SIMILAR(intensity[1][1], 2500.0)
}
// Test 2: Limited RT range
{
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity;
exp.get2DPeakDataPerSpectrum(1.5, 2.5, 0.0, 300.0, 1, rt, mz, intensity);
TEST_EQUAL(rt.size(), 1)
TEST_EQUAL(mz.size(), 1)
TEST_EQUAL(intensity.size(), 1)
TEST_REAL_SIMILAR(rt[0], 2.0)
}
// Test 3: Limited MZ range
{
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity;
exp.get2DPeakDataPerSpectrum(0.0, 4.0, 120.0, 180.0, 1, rt, mz, intensity);
TEST_EQUAL(rt.size(), 1)
TEST_EQUAL(mz.size(), 1)
TEST_EQUAL(intensity.size(), 1)
TEST_REAL_SIMILAR(rt[0], 2.0)
TEST_EQUAL(mz[0].size(), 1)
TEST_REAL_SIMILAR(mz[0][0], 150.0)
}
// Test 4: MS level 2
{
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity;
exp.get2DPeakDataPerSpectrum(0.0, 4.0, 0.0, 300.0, 2, rt, mz, intensity);
TEST_EQUAL(rt.size(), 1)
TEST_EQUAL(mz.size(), 1)
TEST_EQUAL(intensity.size(), 1)
TEST_REAL_SIMILAR(rt[0], 3.0)
TEST_EQUAL(mz[0].size(), 1)
TEST_REAL_SIMILAR(mz[0][0], 175.0)
TEST_REAL_SIMILAR(intensity[0][0], 1750.0)
}
// Test 5: Empty range
{
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity;
exp.get2DPeakDataPerSpectrum(5.0, 6.0, 0.0, 300.0, 1, rt, mz, intensity);
TEST_EQUAL(rt.empty(), true)
TEST_EQUAL(mz.empty(), true)
TEST_EQUAL(intensity.empty(), true)
}
}
END_SECTION
START_SECTION((void get2DPeakDataIMPerSpectrum(CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz, Size ms_level, std::vector<float>& rt, std::vector<std::vector<float>>& mz, std::vector<std::vector<float>>& intensity, std::vector<std::vector<float>>& ion_mobility) const))
{
MSExperiment exp;
// Create test spectra with ion mobility data
MSSpectrum s1{
{100.0, 1000.0},
{200.0, 2000.0}
};
s1.setRT(1.0);
s1.setMSLevel(1);
DataArrays::FloatDataArray im1;
im1.setName(Constants::UserParam::ION_MOBILITY);
im1.push_back(0.8f); // IM value for first peak
im1.push_back(1.2f); // IM value for second peak
im1.setMetaValue("unit", "millisecond");
s1.getFloatDataArrays().push_back(im1);
MSSpectrum s2{
{150.0, 1500.0},
{250.0, 2500.0}
};
s2.setRT(2.0);
s2.setMSLevel(1);
DataArrays::FloatDataArray im2;
im2.setName(Constants::UserParam::ION_MOBILITY);
im2.push_back(1.5f); // IM value for first peak
im2.push_back(2.0f); // IM value for second peak
im2.setMetaValue("unit", "millisecond");
s2.getFloatDataArrays().push_back(im2);
MSSpectrum s3{
{175.0, 1750.0}
};
s3.setRT(3.0);
s3.setMSLevel(2);
DataArrays::FloatDataArray im3;
im3.setName(Constants::UserParam::ION_MOBILITY);
im3.push_back(1.8f); // IM value for single peak
im3.setMetaValue("unit", "millisecond");
s3.getFloatDataArrays().push_back(im3);
exp.addSpectrum(s1);
exp.addSpectrum(s2);
exp.addSpectrum(s3);
// Test 1: Full range, MS level 1
{
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity, ion_mobility;
exp.get2DPeakDataIMPerSpectrum(0.0, 4.0, 0.0, 300.0, 1, rt, mz, intensity, ion_mobility);
TEST_EQUAL(rt.size(), 2)
TEST_EQUAL(mz.size(), 2)
TEST_EQUAL(intensity.size(), 2)
TEST_EQUAL(ion_mobility.size(), 2)
// Check first spectrum
TEST_REAL_SIMILAR(rt[0], 1.0)
TEST_EQUAL(mz[0].size(), 2)
TEST_REAL_SIMILAR(mz[0][0], 100.0)
TEST_REAL_SIMILAR(mz[0][1], 200.0)
TEST_REAL_SIMILAR(intensity[0][0], 1000.0)
TEST_REAL_SIMILAR(intensity[0][1], 2000.0)
TEST_REAL_SIMILAR(ion_mobility[0][0], 0.8)
TEST_REAL_SIMILAR(ion_mobility[0][1], 1.2)
// Check second spectrum
TEST_REAL_SIMILAR(rt[1], 2.0)
TEST_EQUAL(mz[1].size(), 2)
TEST_REAL_SIMILAR(mz[1][0], 150.0)
TEST_REAL_SIMILAR(mz[1][1], 250.0)
TEST_REAL_SIMILAR(intensity[1][0], 1500.0)
TEST_REAL_SIMILAR(intensity[1][1], 2500.0)
TEST_REAL_SIMILAR(ion_mobility[1][0], 1.5)
TEST_REAL_SIMILAR(ion_mobility[1][1], 2.0)
}
// Test 2: Limited RT range
{
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity, ion_mobility;
exp.get2DPeakDataIMPerSpectrum(1.5, 2.5, 0.0, 300.0, 1, rt, mz, intensity, ion_mobility);
TEST_EQUAL(rt.size(), 1)
TEST_EQUAL(mz.size(), 1)
TEST_EQUAL(intensity.size(), 1)
TEST_EQUAL(ion_mobility.size(), 1)
TEST_REAL_SIMILAR(rt[0], 2.0)
TEST_EQUAL(ion_mobility[0].size(), 2)
TEST_REAL_SIMILAR(ion_mobility[0][0], 1.5)
TEST_REAL_SIMILAR(ion_mobility[0][1], 2.0)
}
// Test 3: Limited MZ range
{
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity, ion_mobility;
exp.get2DPeakDataIMPerSpectrum(0.0, 4.0, 120.0, 180.0, 1, rt, mz, intensity, ion_mobility);
TEST_EQUAL(rt.size(), 1)
TEST_EQUAL(mz.size(), 1)
TEST_EQUAL(intensity.size(), 1)
TEST_EQUAL(ion_mobility.size(), 1)
TEST_REAL_SIMILAR(rt[0], 2.0)
TEST_EQUAL(mz[0].size(), 1)
TEST_REAL_SIMILAR(mz[0][0], 150.0)
TEST_REAL_SIMILAR(ion_mobility[0][0], 1.5)
}
// Test 4: MS level 2
{
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity, ion_mobility;
exp.get2DPeakDataIMPerSpectrum(0.0, 4.0, 0.0, 300.0, 2, rt, mz, intensity, ion_mobility);
TEST_EQUAL(rt.size(), 1)
TEST_EQUAL(mz.size(), 1)
TEST_EQUAL(intensity.size(), 1)
TEST_EQUAL(ion_mobility.size(), 1)
TEST_REAL_SIMILAR(rt[0], 3.0)
TEST_EQUAL(mz[0].size(), 1)
TEST_REAL_SIMILAR(mz[0][0], 175.0)
TEST_REAL_SIMILAR(intensity[0][0], 1750.0)
TEST_REAL_SIMILAR(ion_mobility[0][0], 1.8)
}
// Test 5: Empty range
{
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity, ion_mobility;
exp.get2DPeakDataIMPerSpectrum(5.0, 6.0, 0.0, 300.0, 1, rt, mz, intensity, ion_mobility);
TEST_EQUAL(rt.empty(), true)
TEST_EQUAL(mz.empty(), true)
TEST_EQUAL(intensity.empty(), true)
TEST_EQUAL(ion_mobility.empty(), true)
}
// Test 6: Spectrum without ion mobility data
{
MSExperiment exp_no_im;
MSSpectrum s_no_im{
{100.0, 1000.0},
{200.0, 2000.0}
};
s_no_im.setRT(1.0);
s_no_im.setMSLevel(1);
exp_no_im.addSpectrum(s_no_im);
std::vector<float> rt;
std::vector<std::vector<float>> mz, intensity, ion_mobility;
exp_no_im.get2DPeakDataIMPerSpectrum(0.0, 4.0, 0.0, 300.0, 1, rt, mz, intensity, ion_mobility);
TEST_EQUAL(rt.size(), 1)
TEST_EQUAL(mz.size(), 1)
TEST_EQUAL(intensity.size(), 1)
TEST_EQUAL(ion_mobility.size(), 1)
TEST_EQUAL(ion_mobility[0].size(), 2)
TEST_REAL_SIMILAR(ion_mobility[0][0], -1.0) // Should return -1.0 for missing IM data
TEST_REAL_SIMILAR(ion_mobility[0][1], -1.0)
}
}
END_SECTION
START_SECTION((void get2DPeakData(CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz, std::vector<float>& rt, std::vector<float>& mz, std::vector<float>& intensity) const))
{
MSExperiment exp;
// Create test spectra
MSSpectrum s1{
{100.0, 1000.0},
{200.0, 2000.0}
};
s1.setRT(1.0);
s1.setMSLevel(1);
MSSpectrum s2{
{150.0, 1500.0},
{250.0, 2500.0}
};
s2.setRT(2.0);
s2.setMSLevel(1);
exp.addSpectrum(s1);
exp.addSpectrum(s2);
// Test 1: Full range
{
std::vector<float> rt, mz, intensity;
exp.get2DPeakData(0.0, 4.0, 0.0, 300.0, 1, rt, mz, intensity);
TEST_EQUAL(rt.size(), 4)
TEST_EQUAL(mz.size(), 4)
TEST_EQUAL(intensity.size(), 4)
// Check all peaks in order
TEST_REAL_SIMILAR(rt[0], 1.0)
TEST_REAL_SIMILAR(mz[0], 100.0)
TEST_REAL_SIMILAR(intensity[0], 1000.0)
TEST_REAL_SIMILAR(rt[1], 1.0)
TEST_REAL_SIMILAR(mz[1], 200.0)
TEST_REAL_SIMILAR(intensity[1], 2000.0)
TEST_REAL_SIMILAR(rt[2], 2.0)
TEST_REAL_SIMILAR(mz[2], 150.0)
TEST_REAL_SIMILAR(intensity[2], 1500.0)
TEST_REAL_SIMILAR(rt[3], 2.0)
TEST_REAL_SIMILAR(mz[3], 250.0)
TEST_REAL_SIMILAR(intensity[3], 2500.0)
}
// Test 2: Limited RT range
{
std::vector<float> rt, mz, intensity;
exp.get2DPeakData(1.5, 2.5, 0.0, 300.0, 1, rt, mz, intensity);
TEST_EQUAL(rt.size(), 2)
TEST_EQUAL(mz.size(), 2)
TEST_EQUAL(intensity.size(), 2)
TEST_REAL_SIMILAR(rt[0], 2.0)
TEST_REAL_SIMILAR(mz[0], 150.0)
TEST_REAL_SIMILAR(intensity[0], 1500.0)
}
// Test 3: Limited MZ range
{
std::vector<float> rt, mz, intensity;
exp.get2DPeakData(0.0, 4.0, 120.0, 180.0, 1, rt, mz, intensity);
TEST_EQUAL(rt.size(), 1)
TEST_EQUAL(mz.size(), 1)
TEST_EQUAL(intensity.size(), 1)
TEST_REAL_SIMILAR(rt[0], 2.0)
TEST_REAL_SIMILAR(mz[0], 150.0)
TEST_REAL_SIMILAR(intensity[0], 1500.0)
}
// Test 4: Empty range
{
std::vector<float> rt, mz, intensity;
exp.get2DPeakData(5.0, 6.0, 0.0, 300.0, 1, rt, mz, intensity);
TEST_EQUAL(rt.empty(), true)
TEST_EQUAL(mz.empty(), true)
TEST_EQUAL(intensity.empty(), true)
}
}
END_SECTION
START_SECTION((std::vector<std::vector<MSExperiment::CoordinateType>> aggregateFromMatrix(const Matrix<double>& ranges, unsigned int ms_level, const std::string& mz_agg) const))
{
// Create test experiment with known data
MSExperiment exp;
exp.resize(4);
// First spectrum (MS1) at RT=1.0
exp[0] = MSSpectrum{
{100.0, 1000.0},
{200.0, 2000.0},
{300.0, 3000.0}
};
exp[0].setRT(1.0);
exp[0].setMSLevel(1);
// Second spectrum (MS2) at RT=2.0
exp[1] = MSSpectrum{
{150.0, 1500.0},
{250.0, 2500.0}
};
exp[1].setRT(2.0);
exp[1].setMSLevel(2);
// Third spectrum (MS1) at RT=3.0
exp[2] = MSSpectrum{
{100.0, 1100.0},
{200.0, 2100.0},
{300.0, 3100.0}
};
exp[2].setRT(3.0);
exp[2].setMSLevel(1);
// Fourth spectrum (MS1) at RT=4.0
exp[3] = MSSpectrum{
{100.0, 1200.0},
{200.0, 2200.0},
{300.0, 3200.0}
};
exp[3].setRT(4.0);
exp[3].setMSLevel(1);
exp.updateRanges();
// Test 1: Sum aggregation for MS1 spectra
{
Matrix<double> ranges(2, 4); // two rt-mz ranges, four columns with min_mz, max_mz, min_rt, max_rt
// Range 1: m/z 90-110, RT 0-3.5 (covers first and third spectra)
ranges(0, 0) = 90.0; ranges(0, 1) = 110.0;
ranges(0, 2) = 0.0; ranges(0, 3) = 3.5;
// Range 2: m/z 190-210, RT 0-5.0 (covers first, third, and fourth spectra)
ranges(1, 0) = 190.0; ranges(1, 1) = 210.0;
ranges(1, 2) = 0.0; ranges(1, 3) = 5.0;
auto result = exp.aggregateFromMatrix(ranges, 1, "sum");
// Check results
TEST_EQUAL(result.size(), 2);
// Check Range 1 results
TEST_EQUAL(result[0].size(), 2); // Should cover 2 spectra (1 and 3)
TEST_EQUAL(result[0][0], 1000.0); // First spectrum intensity RT = 1.0
TEST_EQUAL(result[0][1], 1100.0); // Third spectrum intensity RT = 3.0
// Check Range 2 results
TEST_EQUAL(result[1].size(), 3); // Should cover 3 spectra (1, 3, and 4)
TEST_EQUAL(result[1][0], 2000.0); // First spectrum intensity
TEST_EQUAL(result[1][1], 2100.0); // Third spectrum intensity
TEST_EQUAL(result[1][2], 2200.0); // Fourth spectrum intensity
}
// Test 2: Max aggregation for MS1 spectra
{
Matrix<double> ranges(1, 4);
// Range: m/z 100-300, RT 1-4 (covers first, third, and fourth spectra)
ranges(0,0) = 100.0; ranges(0,1) = 300.0;
ranges(0,2) = 1.0; ranges(0,3) = 4.0;
auto result = exp.aggregateFromMatrix(ranges, 1, "max");
// Check results
TEST_EQUAL(result.size(), 1);
TEST_EQUAL(result[0].size(), 3);
TEST_EQUAL(result[0][0], 3000.0); // First spectrum max intensity in range
TEST_EQUAL(result[0][1], 3100.0); // Third spectrum max intensity in range
TEST_EQUAL(result[0][2], 3200.0); // Fourth spectrum max intensity in range
}
// Test 3: Min aggregation for MS1 spectra
{
Matrix<double> ranges(1, 4);
// Range: m/z 100-300, RT 1-4 (covers first, third, and fourth spectra)
ranges(0,0) = 100.0; ranges(0,1) = 300.0;
ranges(0,2) = 1.0; ranges(0,3) = 4.0;
auto result = exp.aggregateFromMatrix(ranges, 1, "min");
// Check results
TEST_EQUAL(result.size(), 1);
TEST_EQUAL(result[0].size(), 3);
TEST_EQUAL(result[0][0], 1000.0); // First spectrum min intensity in range
TEST_EQUAL(result[0][1], 1100.0); // Third spectrum min intensity in range
TEST_EQUAL(result[0][2], 1200.0); // Fourth spectrum min intensity in range
}
// Test 4: Mean aggregation for MS1 spectra
{
Matrix<double> ranges(1, 4);
// Range: m/z 100-300, RT 0-5 (covers all MS1 spectra)
ranges(0,0) = 100.0; ranges(0,1) = 300.0;
ranges(0,2) = 0.0; ranges(0,3) = 5.0;
auto result = exp.aggregateFromMatrix(ranges, 1, "mean");
// Check results
TEST_EQUAL(result.size(), 1);
TEST_EQUAL(result[0].size(), 3);
TEST_REAL_SIMILAR(result[0][0], 2000.0); // First spectrum mean intensity
TEST_REAL_SIMILAR(result[0][1], 2100.0); // Third spectrum mean intensity
TEST_REAL_SIMILAR(result[0][2], 2200.0); // Fourth spectrum mean intensity
}
// Test 5: Invalid aggregation function
{
Matrix<double> ranges(1, 4);
ranges(0,0) = 100.0; ranges(0,1) = 200.0;
ranges(0,2) = 1.0; ranges(0,3) = 2.0;
TEST_EXCEPTION(Exception::InvalidValue, exp.aggregateFromMatrix(ranges, 1, "invalid_agg"));
}
// Test 6: Invalid matrix dimensions (not 4 columns)
{
Matrix<double> ranges(1, 3);
ranges(0,0) = 100.0; ranges(0,1) = 200.0; ranges(0,2) = 1.0;
TEST_EXCEPTION(Exception::InvalidParameter, exp.aggregateFromMatrix(ranges, 1, "sum"));
}
// Test 7: Empty ranges matrix
{
Matrix<double> ranges(0, 4); // 0 rows, 4 columns
auto result = exp.aggregateFromMatrix(ranges, 1, "sum");
TEST_EQUAL(result.size(), 0); // Expect an empty result
}
// Test 8: No matching spectra for given ms_level
{
Matrix<double> ranges(1, 4);
ranges(0,0) = 100.0; ranges(0,1) = 300.0;
ranges(0,2) = 0.0; ranges(0,3) = 5.0;
auto result = exp.aggregateFromMatrix(ranges, 3, "sum"); // No spectra with MS level 3
// Failed to extract anything -> empty vector
TEST_EQUAL(result.size(), 0);
}
}
END_SECTION
START_SECTION((std::vector<MSChromatogram> extractXICsFromMatrix(const Matrix<double>& ranges, unsigned int ms_level, const std::string& mz_agg) const))
{
// Create test experiment with known data
MSExperiment exp;
exp.resize(4);
// First spectrum (MS1) at RT=1.0
exp[0] = MSSpectrum{
{100.0, 1000.0},
{200.0, 2000.0},
{300.0, 3000.0}
};
exp[0].setRT(1.0);
exp[0].setMSLevel(1);
// Second spectrum (MS2) at RT=2.0
exp[1] = MSSpectrum{
{150.0, 1500.0},
{250.0, 2500.0}
};
exp[1].setRT(2.0);
exp[1].setMSLevel(2);
// Third spectrum (MS1) at RT=3.0
exp[2] = MSSpectrum{
{100.0, 1100.0},
{200.0, 2100.0},
{300.0, 3100.0}
};
exp[2].setRT(3.0);
exp[2].setMSLevel(1);
// Fourth spectrum (MS1) at RT=4.0
exp[3] = MSSpectrum{
{100.0, 1200.0},
{200.0, 2200.0},
{300.0, 3200.0}
};
exp[3].setRT(4.0);
exp[3].setMSLevel(1);
exp.updateRanges();
// Test 1: Sum aggregation for MS1 spectra
{
Matrix<double> ranges(2, 4);
// Range 1: m/z 90-110, RT 0-3.5 (covers first and third spectra)
ranges(0,0) = 90.0; ranges(0,1) = 110.0;
ranges(0,2) = 0.0; ranges(0,3) = 3.5;
// Range 2: m/z 190-210, RT 0-5.0 (covers first, third, and fourth spectra)
ranges(1,0) = 190.0; ranges(1,1) = 210.0;
ranges(1,2) = 0.0; ranges(1,3) = 5.0;
unsigned int ms_level = 1;
std::string mz_agg = "sum";
auto result = exp.extractXICsFromMatrix(ranges, ms_level, mz_agg);
// Check results
TEST_EQUAL(result.size(), 2);
// Check Range 1 results
TEST_EQUAL(result[0].size(), 2); // Should cover 2 spectra
TEST_REAL_SIMILAR(result[0][0].getIntensity(), 1000.0); // First spectrum intensity
TEST_REAL_SIMILAR(result[0][1].getIntensity(), 1100.0); // Third spectrum intensity
// Check Range 2 results
TEST_EQUAL(result[1].size(), 3); // Should cover 3 spectra
TEST_REAL_SIMILAR(result[1][0].getIntensity(), 2000.0); // First spectrum intensity
TEST_REAL_SIMILAR(result[1][1].getIntensity(), 2100.0); // Third spectrum intensity
TEST_REAL_SIMILAR(result[1][2].getIntensity(), 2200.0); // Fourth spectrum intensity
}
}
END_SECTION
START_SECTION((void get2DPeakDataIM(CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz, Size ms_level, std::vector<float>& rt, std::vector<float>& mz, std::vector<float>& intensity, std::vector<float>& ion_mobility) const))
{
MSExperiment exp;
// Create test spectra with ion mobility data
MSSpectrum s1{
{100.0, 1000.0},
{200.0, 2000.0}
};
s1.setRT(1.0);
s1.setMSLevel(1);
DataArrays::FloatDataArray im1;
im1.setName(Constants::UserParam::ION_MOBILITY);
im1.push_back(0.8f);
im1.push_back(1.2f);
im1.setMetaValue("unit", "millisecond");
s1.getFloatDataArrays().push_back(im1);
MSSpectrum s2{
{150.0, 1500.0},
{250.0, 2500.0}
};
s2.setRT(2.0);
s2.setMSLevel(1);
DataArrays::FloatDataArray im2;
im2.setName(Constants::UserParam::ION_MOBILITY);
im2.push_back(1.5f);
im2.push_back(2.0f);
im2.setMetaValue("unit", "millisecond");
s2.getFloatDataArrays().push_back(im2);
exp.addSpectrum(s1);
exp.addSpectrum(s2);
// Test 1: Full range, MS level 1
{
std::vector<float> rt, mz, intensity, ion_mobility;
exp.get2DPeakDataIM(0.0, 4.0, 0.0, 300.0, 1, rt, mz, intensity, ion_mobility);
TEST_EQUAL(rt.size(), 4)
TEST_EQUAL(mz.size(), 4)
TEST_EQUAL(intensity.size(), 4)
TEST_EQUAL(ion_mobility.size(), 4)
// Check all peaks in order
TEST_REAL_SIMILAR(rt[0], 1.0)
TEST_REAL_SIMILAR(mz[0], 100.0)
TEST_REAL_SIMILAR(intensity[0], 1000.0)
TEST_REAL_SIMILAR(ion_mobility[0], 0.8)
TEST_REAL_SIMILAR(rt[1], 1.0)
TEST_REAL_SIMILAR(mz[1], 200.0)
TEST_REAL_SIMILAR(intensity[1], 2000.0)
TEST_REAL_SIMILAR(ion_mobility[1], 1.2)
TEST_REAL_SIMILAR(rt[2], 2.0)
TEST_REAL_SIMILAR(mz[2], 150.0)
TEST_REAL_SIMILAR(intensity[2], 1500.0)
TEST_REAL_SIMILAR(ion_mobility[2], 1.5)
TEST_REAL_SIMILAR(rt[3], 2.0)
TEST_REAL_SIMILAR(mz[3], 250.0)
TEST_REAL_SIMILAR(intensity[3], 2500.0)
TEST_REAL_SIMILAR(ion_mobility[3], 2.0)
}
// Test 2: Limited RT range
{
std::vector<float> rt, mz, intensity, ion_mobility;
exp.get2DPeakDataIM(1.5, 2.5, 0.0, 300.0, 1, rt, mz, intensity, ion_mobility);
TEST_EQUAL(rt.size(), 2)
TEST_EQUAL(mz.size(), 2)
TEST_EQUAL(intensity.size(), 2)
TEST_EQUAL(ion_mobility.size(), 2)
TEST_REAL_SIMILAR(rt[0], 2.0)
TEST_REAL_SIMILAR(mz[0], 150.0)
TEST_REAL_SIMILAR(intensity[0], 1500.0)
TEST_REAL_SIMILAR(ion_mobility[0], 1.5)
}
// Test 3: Spectrum without ion mobility data
{
MSExperiment exp_no_im;
MSSpectrum s_no_im{
{100.0, 1000.0},
{200.0, 2000.0}
};
s_no_im.setRT(1.0);
s_no_im.setMSLevel(1);
exp_no_im.addSpectrum(s_no_im);
std::vector<float> rt, mz, intensity, ion_mobility;
exp_no_im.get2DPeakDataIM(0.0, 4.0, 0.0, 300.0, 1, rt, mz, intensity, ion_mobility);
TEST_EQUAL(rt.size(), 2)
TEST_EQUAL(mz.size(), 2)
TEST_EQUAL(intensity.size(), 2)
TEST_EQUAL(ion_mobility.size(), 2)
TEST_REAL_SIMILAR(ion_mobility[0], -1.0) // Should return -1.0 for missing IM data
TEST_REAL_SIMILAR(ion_mobility[1], -1.0)
}
}
END_SECTION
START_SECTION((template<class MzReductionFunctionType> std::vector<MSChromatogram> extractXICs(const std::vector<std::pair<RangeMZ, RangeRT>>& mz_rt_ranges, unsigned int ms_level, MzReductionFunctionType func_mz_reduction = SumIntensityReduction()) const))
{
// Create test experiment with known data
PeakMap exp;
exp.resize(4);
// First spectrum (MS1) at RT=1.0
exp[0] = MSSpectrum{
{100.0, 1000.0},
{200.0, 2000.0},
{300.0, 3000.0}
};
exp[0].setRT(1.0);
exp[0].setMSLevel(1);
// Second spectrum (MS2) at RT=2.0
exp[1] = MSSpectrum{
{150.0, 1500.0},
{250.0, 2500.0}
};
exp[1].setRT(2.0);
exp[1].setMSLevel(2);
// Third spectrum (MS1) at RT=3.0
exp[2] = MSSpectrum{
{100.0, 1100.0},
{200.0, 2100.0},
{300.0, 3100.0}
};
exp[2].setRT(3.0);
exp[2].setMSLevel(1);
// Fourth spectrum (MS1) at RT=4.0
exp[3] = MSSpectrum{
{100.0, 1200.0},
{200.0, 2200.0},
{300.0, 3200.0}
};
exp[3].setRT(4.0);
exp[3].setMSLevel(1);
// Update the ranges of the experiment
exp.updateRanges();
// Test 1: Normal case - MS1 spectra using default reduction function
{
std::vector<std::pair<RangeMZ, RangeRT>> ranges;
// Range 1: covers first peak of all MS1 spectra
ranges.push_back(std::make_pair(
RangeMZ(90.0, 110.0),
RangeRT(0.0, 5.0)
));
// Range 2: covers second peak of all MS1 spectra
ranges.push_back(std::make_pair(
RangeMZ(190.0, 210.0),
RangeRT(0.0, 5.0)
));
// Use default reduction function (SumIntensityReduction)
auto chromatograms = exp.extractXICs(ranges, 1);
// Check results
TEST_EQUAL(chromatograms.size(), 2);
// Check Range 1 chromatogram
TEST_EQUAL(chromatograms[0].size(), 3); // Should cover 3 spectra
TEST_REAL_SIMILAR(chromatograms[0][0].getRT(), 1.0);
TEST_REAL_SIMILAR(chromatograms[0][0].getIntensity(), 1000.0);
TEST_REAL_SIMILAR(chromatograms[0][1].getRT(), 3.0);
TEST_REAL_SIMILAR(chromatograms[0][1].getIntensity(), 1100.0);
TEST_REAL_SIMILAR(chromatograms[0][2].getRT(), 4.0);
TEST_REAL_SIMILAR(chromatograms[0][2].getIntensity(), 1200.0);
// Check m/z value of the chromatogram
TEST_REAL_SIMILAR(chromatograms[0].getProduct().getMZ(), (90.0 + 110.0) / 2.0);
// Check Range 2 chromatogram
TEST_EQUAL(chromatograms[1].size(), 3); // Should cover 3 spectra
TEST_REAL_SIMILAR(chromatograms[1][0].getRT(), 1.0);
TEST_REAL_SIMILAR(chromatograms[1][0].getIntensity(), 2000.0);
TEST_REAL_SIMILAR(chromatograms[1][1].getRT(), 3.0);
TEST_REAL_SIMILAR(chromatograms[1][1].getIntensity(), 2100.0);
TEST_REAL_SIMILAR(chromatograms[1][2].getRT(), 4.0);
TEST_REAL_SIMILAR(chromatograms[1][2].getIntensity(), 2200.0);
// Check m/z value of the chromatogram
TEST_REAL_SIMILAR(chromatograms[1].getProduct().getMZ(), (190.0 + 210.0) / 2.0);
}
// Test 2: MS2 spectra
{
std::vector<std::pair<RangeMZ, RangeRT>> ranges;
ranges.push_back(std::make_pair(
RangeMZ(140.0, 160.0),
RangeRT(1.5, 2.5)
));
auto chromatograms = exp.extractXICs(ranges, 2);
TEST_EQUAL(chromatograms.size(), 1);
TEST_EQUAL(chromatograms[0].size(), 1);
TEST_REAL_SIMILAR(chromatograms[0][0].getRT(), 2.0);
TEST_REAL_SIMILAR(chromatograms[0][0].getIntensity(), 1500.0);
// Check m/z value of the chromatogram
TEST_REAL_SIMILAR(chromatograms[0].getProduct().getMZ(), (140.0 + 160.0) / 2.0);
}
// Test 3: Custom reduction function (average intensity)
{
std::vector<std::pair<RangeMZ, RangeRT>> ranges;
ranges.push_back(std::make_pair(
RangeMZ(90.0, 310.0), // Covers all peaks
RangeRT(0.0, 5.0) // Covers all spectra
));
// Mean intensity in m/z range
auto chromatograms = exp.extractXICs(ranges, 1,
[](MSSpectrum::ConstIterator begin_it, MSSpectrum::ConstIterator end_it) -> double
{
if (begin_it == end_it) return 0.0;
double acc = std::accumulate(begin_it, end_it, 0.0,
[](double a, const Peak1D& b) { return a + b.getIntensity(); });
return acc / static_cast<double>(std::distance(begin_it, end_it));
});
TEST_EQUAL(chromatograms.size(), 1);
TEST_EQUAL(chromatograms[0].size(), 3);
TEST_REAL_SIMILAR(chromatograms[0][0].getRT(), 1.0);
TEST_REAL_SIMILAR(chromatograms[0][0].getIntensity(), 2000.0); // Average of [1000, 2000, 3000]
TEST_REAL_SIMILAR(chromatograms[0][1].getRT(), 3.0);
TEST_REAL_SIMILAR(chromatograms[0][1].getIntensity(), 2100.0); // Average of [1100, 2100, 3100]
TEST_REAL_SIMILAR(chromatograms[0][2].getRT(), 4.0);
TEST_REAL_SIMILAR(chromatograms[0][2].getIntensity(), 2200.0); // Average of [1200, 2200, 3200]
// Check m/z value of the chromatogram
TEST_REAL_SIMILAR(chromatograms[0].getProduct().getMZ(), (90.0 + 310.0) / 2.0);
}
}
END_SECTION
/////////////////////////////////////////////////////////////
// Tests for dual-range system
/////////////////////////////////////////////////////////////
START_SECTION((const SpectrumRangeManagerType& spectrumRanges() const))
{
// Create experiment with spectra only
MSExperiment exp;
MSSpectrum s;
Peak1D p;
// Add MS1 spectrum
s.setMSLevel(1);
s.setRT(30.0);
p.getPosition()[0] = 100.0;
p.setIntensity(1000.0f);
s.push_back(p);
exp.addSpectrum(s);
// Add MS2 spectrum
s.clear(true);
s.setMSLevel(2);
s.setRT(35.0);
p.getPosition()[0] = 200.0;
p.setIntensity(2000.0f);
s.push_back(p);
exp.addSpectrum(s);
// Update ranges
exp.updateRanges();
// Test general access to spectrum ranges
TEST_REAL_SIMILAR(exp.spectrumRanges().getMinMZ(), 100.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMaxMZ(), 200.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMinIntensity(), 1000.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMaxIntensity(), 2000.0);
// Test MS level-specific ranges
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(1).getMinMZ(), 100.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(1).getMaxMZ(), 100.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(1).getMinIntensity(), 1000.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(1).getMaxIntensity(), 1000.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(2).getMinMZ(), 200.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(2).getMaxMZ(), 200.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(2).getMinIntensity(), 2000.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(2).getMaxIntensity(), 2000.0);
}
END_SECTION
START_SECTION((const ChromatogramRangeManagerType& chromatogramRanges() const))
{
// Create experiment with chromatograms only
MSExperiment exp;
MSChromatogram chrom;
ChromatogramPeak cp;
// Add first chromatogram
cp.setRT(10.0);
cp.setIntensity(500.0f);
chrom.push_back(cp);
cp.setRT(20.0);
cp.setIntensity(1500.0f);
chrom.push_back(cp);
chrom.setMetaValue("product_mz", 305.0);
exp.addChromatogram(chrom);
// Add second chromatogram
chrom.clear(true);
cp.setRT(15.0);
cp.setIntensity(800.0f);
chrom.push_back(cp);
cp.setRT(25.0);
cp.setIntensity(1800.0f);
chrom.push_back(cp);
chrom.setMetaValue("product_mz", 405.0);
exp.addChromatogram(chrom);
// Update ranges
exp.updateRanges();
// Test chromatogram ranges
TEST_REAL_SIMILAR(exp.chromatogramRanges().getMinRT(), 10.0);
TEST_REAL_SIMILAR(exp.chromatogramRanges().getMaxRT(), 25.0);
TEST_REAL_SIMILAR(exp.chromatogramRanges().getMinIntensity(), 500.0);
TEST_REAL_SIMILAR(exp.chromatogramRanges().getMaxIntensity(), 1800.0);
}
END_SECTION
START_SECTION((void updateRanges()))
{
// Test case 1: Empty experiment
{
MSExperiment exp;
exp.updateRanges();
// Check that all ranges are empty
TEST_TRUE(exp.spectrumRanges().hasRange() == HasRangeType::NONE);
TEST_TRUE(exp.chromatogramRanges().hasRange() == HasRangeType::NONE);
TEST_TRUE(exp.combinedRanges().hasRange() == HasRangeType::NONE);
}
// Test case 2: Experiment with only spectra
{
MSExperiment exp;
MSSpectrum s;
Peak1D p;
// Add MS1 spectrum
s.setMSLevel(1);
s.setRT(30.0);
p.getPosition()[0] = 100.0;
p.setIntensity(1000.0f);
s.push_back(p);
exp.addSpectrum(s);
exp.updateRanges();
// Check spectrum ranges are correct
TEST_EQUAL(exp.spectrumRanges().hasRange(), HasRangeType::SOME);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMinMZ(), 100.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMaxMZ(), 100.0);
// Check chromatogram ranges are empty
TEST_EQUAL(exp.chromatogramRanges().hasRange(), HasRangeType::NONE);
// Check combined ranges match spectrum ranges
TEST_EQUAL(exp.combinedRanges().hasRange(), HasRangeType::SOME);
TEST_REAL_SIMILAR(exp.combinedRanges().getMinMZ(), 100.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMaxMZ(), 100.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMinRT(), 30.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMaxRT(), 30.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMinIntensity(), 1000.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMaxIntensity(), 1000.0);
}
// Test case 3: Experiment with only chromatograms
{
MSExperiment exp;
MSChromatogram chrom;
ChromatogramPeak cp;
cp.setRT(10.0);
cp.setIntensity(500.0f);
chrom.push_back(cp);
cp.setRT(20.0);
cp.setIntensity(1500.0f);
chrom.push_back(cp);
chrom.setMetaValue("product_mz", 305.0);
exp.addChromatogram(chrom);
exp.updateRanges();
// Check spectrum ranges are empty
TEST_EQUAL(exp.spectrumRanges().hasRange(), HasRangeType::NONE);
// Check chromatogram ranges are correct
TEST_EQUAL(exp.chromatogramRanges().hasRange(), HasRangeType::ALL);
TEST_REAL_SIMILAR(exp.chromatogramRanges().getMinRT(), 10.0);
TEST_REAL_SIMILAR(exp.chromatogramRanges().getMaxRT(), 20.0);
// Check combined ranges match chromatogram ranges
TEST_EQUAL(exp.combinedRanges().hasRange(), HasRangeType::SOME);
TEST_REAL_SIMILAR(exp.combinedRanges().getMinRT(), 10.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMaxRT(), 20.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMinIntensity(), 500.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMaxIntensity(), 1500.0);
}
// Test case 4: Experiment with both spectra and chromatograms
{
MSExperiment exp;
// Add spectrum
MSSpectrum s;
Peak1D p;
s.setMSLevel(1);
s.setRT(30.0);
p.getPosition()[0] = 100.0;
p.setIntensity(1000.0f);
s.push_back(p);
exp.addSpectrum(s);
// Add chromatogram
MSChromatogram chrom;
ChromatogramPeak cp;
cp.setRT(10.0);
cp.setIntensity(500.0f);
chrom.push_back(cp);
cp.setRT(20.0);
cp.setIntensity(1500.0f);
chrom.push_back(cp);
chrom.setMetaValue("product_mz", 305.0);
exp.addChromatogram(chrom);
exp.updateRanges();
// Check spectrum ranges are correct
TEST_EQUAL(exp.spectrumRanges().hasRange(), HasRangeType::SOME);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMinMZ(), 100.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMaxMZ(), 100.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMinIntensity(), 1000.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMaxIntensity(), 1000.0);
// Check chromatogram ranges are correct
TEST_EQUAL(exp.chromatogramRanges().hasRange(), HasRangeType::ALL);
TEST_REAL_SIMILAR(exp.chromatogramRanges().getMinRT(), 10.0);
TEST_REAL_SIMILAR(exp.chromatogramRanges().getMaxRT(), 20.0);
TEST_REAL_SIMILAR(exp.chromatogramRanges().getMinIntensity(), 500.0);
TEST_REAL_SIMILAR(exp.chromatogramRanges().getMaxIntensity(), 1500.0);
// Check combined ranges encompass both spectrum and chromatogram ranges
TEST_EQUAL(exp.combinedRanges().hasRange(), HasRangeType::SOME);
TEST_REAL_SIMILAR(exp.combinedRanges().getMinMZ(), 0.0); // TODO: Why 0? precursor m/z not set?
TEST_REAL_SIMILAR(exp.combinedRanges().getMaxMZ(), 100.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMinRT(), 10.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMaxRT(), 30.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMinIntensity(), 500.0);
TEST_REAL_SIMILAR(exp.combinedRanges().getMaxIntensity(), 1500.0);
}
// Create experiment with multiple MS levels
MSExperiment exp;
MSSpectrum s;
Peak1D p;
// Add MS1 spectrum
s.setMSLevel(1);
s.setRT(30.0);
p.getPosition()[0] = 100.0;
p.setIntensity(1000.0f);
s.push_back(p);
exp.addSpectrum(s);
// Add MS2 spectrum
s.clear(true);
s.setMSLevel(2);
s.setRT(35.0);
p.getPosition()[0] = 200.0;
p.setIntensity(2000.0f);
s.push_back(p);
exp.addSpectrum(s);
// Add MS3 spectrum
s.clear(true);
s.setMSLevel(3);
s.setRT(40.0);
p.getPosition()[0] = 300.0;
p.setIntensity(3000.0f);
s.push_back(p);
exp.addSpectrum(s);
// Now update all ranges
exp.updateRanges();
// Check all MS levels have correct ranges
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(1).getMinMZ(), 100.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(1).getMaxMZ(), 100.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(2).getMinMZ(), 200.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(2).getMaxMZ(), 200.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(3).getMinMZ(), 300.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().byMSLevel(3).getMaxMZ(), 300.0);
// Check general ranges reflect all spectra
TEST_REAL_SIMILAR(exp.spectrumRanges().getMinMZ(), 100.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMaxMZ(), 300.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMinIntensity(), 1000.0);
TEST_REAL_SIMILAR(exp.spectrumRanges().getMaxIntensity(), 3000.0);
}
END_SECTION
START_SECTION((Backward compatibility tests))
{
// Create experiment with both spectra and chromatograms
MSExperiment exp;
// Add spectrum
MSSpectrum s;
Peak1D p;
s.setMSLevel(1);
s.setRT(30.0);
p.getPosition()[0] = 100.0;
p.setIntensity(1000.0f);
s.push_back(p);
s.setDriftTime(50.0);
exp.addSpectrum(s);
// Add chromatogram
MSChromatogram chrom;
ChromatogramPeak cp;
cp.setRT(10.0);
cp.setIntensity(500.0f);
chrom.push_back(cp);
cp.setRT(20.0);
cp.setIntensity(1500.0f);
chrom.push_back(cp);
chrom.setMetaValue("product_mz", 305.0);
exp.addChromatogram(chrom);
exp.updateRanges();
// Test backward compatibility methods
TEST_REAL_SIMILAR(exp.getMinRT(), 10.0);
TEST_REAL_SIMILAR(exp.getMaxRT(), 30.0);
TEST_REAL_SIMILAR(exp.getMinMZ(), 0.0); // TODO: Why 0? precursor m/z not set?
TEST_REAL_SIMILAR(exp.getMaxMZ(), 100.0);
TEST_REAL_SIMILAR(exp.getMinIntensity(), 500.0);
TEST_REAL_SIMILAR(exp.getMaxIntensity(), 1500.0);
TEST_REAL_SIMILAR(exp.getMinMobility(), 50.0);
TEST_REAL_SIMILAR(exp.getMaxMobility(), 50.0);
// Verify that backward compatibility methods access combined ranges
TEST_REAL_SIMILAR(exp.getMinRT(), exp.combinedRanges().getMinRT());
TEST_REAL_SIMILAR(exp.getMaxRT(), exp.combinedRanges().getMaxRT());
TEST_REAL_SIMILAR(exp.getMinMZ(), exp.combinedRanges().getMinMZ());
TEST_REAL_SIMILAR(exp.getMaxMZ(), exp.combinedRanges().getMaxMZ());
TEST_REAL_SIMILAR(exp.getMinIntensity(), exp.combinedRanges().getMinIntensity());
TEST_REAL_SIMILAR(exp.getMaxIntensity(), exp.combinedRanges().getMaxIntensity());
TEST_REAL_SIMILAR(exp.getMinMobility(), exp.combinedRanges().getMinMobility());
TEST_REAL_SIMILAR(exp.getMaxMobility(), exp.combinedRanges().getMaxMobility());
}
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/FeatureOverlapFilter_test.cpp | .cpp | 17,194 | 530 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Marc Sturm, Chris Bielow, Clemens Groepl $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
#include <OpenMS/PROCESSING/FEATURE/FeatureOverlapFilter.h>
#include <OpenMS/CONCEPT/Constants.h>
///////////////////////////
using namespace std;
using namespace OpenMS;
///////////////////////////
// Helper function to create a simple feature with position, intensity, and charge
Feature createTestFeature(double rt, double mz, double intensity, int charge = 2)
{
Feature f;
f.setRT(rt);
f.setMZ(mz);
f.setIntensity(intensity);
f.setCharge(charge);
// Add a simple convex hull for the feature
std::vector<ConvexHull2D> hulls(1);
hulls[0].addPoint(DPosition<2>(rt - 1.0, mz - 0.01));
hulls[0].addPoint(DPosition<2>(rt + 1.0, mz - 0.01));
hulls[0].addPoint(DPosition<2>(rt + 1.0, mz + 0.01));
hulls[0].addPoint(DPosition<2>(rt - 1.0, mz + 0.01));
f.setConvexHulls(hulls);
return f;
}
/////////////////////////////////////////////////////////////
START_TEST(FeatureOverlapFilter, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
START_SECTION((Filter FeatureMap))
//feature with convex hulls
Feature feature1;
feature1.getPosition()[0] = 5.25;
feature1.getPosition()[1] = 1.5;
feature1.setIntensity(0.5f);
feature1.setOverallQuality(8);
std::vector< ConvexHull2D > hulls(1);
hulls[0].addPoint(DPosition<2>(-1.0,2.0));
hulls[0].addPoint(DPosition<2>(4.0,1.2));
hulls[0].addPoint(DPosition<2>(5.0,3.123));
feature1.setConvexHulls(hulls);
Feature feature2;
feature2.getPosition()[0] = 5.25;
feature2.getPosition()[1] = 1.5;
feature2.setIntensity(0.5f);
feature2.setOverallQuality(10);
std::vector< ConvexHull2D > hulls2(1);
hulls2[0].addPoint(DPosition<2>(-1.0,2.0));
hulls2[0].addPoint(DPosition<2>(4.0,1.2));
hulls2[0].addPoint(DPosition<2>(5.5,3.123));
feature2.setConvexHulls(hulls2);
Feature feature3;
feature3.getPosition()[0] = 5.25;
feature3.getPosition()[1] = 1.5;
feature3.setIntensity(0.5f);
feature3.setOverallQuality(7);
std::vector< ConvexHull2D > hulls3(1);
hulls3[0].addPoint(DPosition<2>(4.5,2.0));
hulls3[0].addPoint(DPosition<2>(10,1.2));
hulls3[0].addPoint(DPosition<2>(10,3.123));
feature3.setConvexHulls(hulls3);
Feature feature4;
feature4.getPosition()[0] = 20.;
feature4.getPosition()[1] = 10.;
feature4.setIntensity(0.5f);
feature4.setOverallQuality(7);
std::vector< ConvexHull2D > hulls4(1);
hulls4[0].addPoint(DPosition<2>(20,5));
hulls4[0].addPoint(DPosition<2>(22,10));
hulls4[0].addPoint(DPosition<2>(22,14));
feature4.setConvexHulls(hulls4);
Feature feature5;
feature5.getPosition()[0] = 20.;
feature5.getPosition()[1] = 11.;
feature5.setIntensity(0.5f);
feature5.setOverallQuality(0.);
std::vector< ConvexHull2D > hulls5(1);
hulls5[0].addPoint(DPosition<2>(20,12.));
hulls5[0].addPoint(DPosition<2>(21,16.));
hulls5[0].addPoint(DPosition<2>(21,18.));
feature5.setConvexHulls(hulls5);
FeatureMap fmap;
fmap.emplace_back(feature1);
fmap.emplace_back(feature2);
fmap.emplace_back(feature3);
fmap.emplace_back(feature4);
fmap.emplace_back(feature5);
fmap.updateRanges();
for (auto& f : fmap)
{
f.ensureUniqueId();
}
FeatureOverlapFilter::filter(fmap,
[](const Feature& left, const Feature& right){ return left.getOverallQuality() > right.getOverallQuality(); },
[](const Feature&, const Feature&) { return true; },
false);
TEST_EQUAL(fmap[0].getOverallQuality(), 10)
TEST_EQUAL(fmap[1].getOverallQuality(), 7)
END_SECTION
START_SECTION(mergeOverlappingFeatures - basic merging with SUM intensity)
{
FeatureMap fmap;
// Two overlapping features (within 5.0 RT and 0.05 mz tolerance)
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
Feature f2 = createTestFeature(102.0, 500.02, 500.0, 2); // within tolerance
// One non-overlapping feature
Feature f3 = createTestFeature(200.0, 600.0, 800.0, 2);
fmap.push_back(f1);
fmap.push_back(f2);
fmap.push_back(f3);
for (auto& f : fmap) f.ensureUniqueId();
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, false,
MergeIntensityMode::SUM, true);
// Should have 2 features: one merged (f1+f2) and one separate (f3)
TEST_EQUAL(fmap.size(), 2)
// Find the merged feature (higher intensity, should be sum of 1000 + 500 = 1500)
bool found_merged = false;
bool found_separate = false;
for (const auto& f : fmap)
{
if (std::abs(f.getIntensity() - 1500.0) < 0.01)
{
found_merged = true;
// Check meta values were written
TEST_EQUAL(f.metaValueExists("merged_centroid_rts"), true)
TEST_EQUAL(f.metaValueExists("merged_centroid_mzs"), true)
std::vector<double> merged_rts = f.getMetaValue("merged_centroid_rts");
TEST_EQUAL(merged_rts.size(), 2)
}
if (std::abs(f.getIntensity() - 800.0) < 0.01)
{
found_separate = true;
// Non-merged feature should not have merge meta values
TEST_EQUAL(f.metaValueExists("merged_centroid_rts"), false)
}
}
TEST_EQUAL(found_merged, true)
TEST_EQUAL(found_separate, true)
}
END_SECTION
START_SECTION(mergeOverlappingFeatures - MAX intensity mode)
{
FeatureMap fmap;
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
Feature f2 = createTestFeature(102.0, 500.02, 500.0, 2);
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, false,
MergeIntensityMode::MAX, true);
TEST_EQUAL(fmap.size(), 1)
// MAX mode should keep 1000.0 (the maximum)
TEST_REAL_SIMILAR(fmap[0].getIntensity(), 1000.0)
}
END_SECTION
START_SECTION(mergeOverlappingFeatures - require_same_charge)
{
FeatureMap fmap;
// Two features at same position but different charges
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
Feature f2 = createTestFeature(101.0, 500.01, 500.0, 3); // different charge
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
// With require_same_charge=true, features should NOT merge
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, false,
MergeIntensityMode::SUM, true);
TEST_EQUAL(fmap.size(), 2)
// Reset and test with require_same_charge=false
fmap.clear();
f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
f2 = createTestFeature(101.0, 500.01, 500.0, 3);
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, false, false,
MergeIntensityMode::SUM, true);
// With require_same_charge=false, features SHOULD merge
TEST_EQUAL(fmap.size(), 1)
TEST_REAL_SIMILAR(fmap[0].getIntensity(), 1500.0)
}
END_SECTION
START_SECTION(mergeOverlappingFeatures - require_same_im with FAIMS_CV)
{
FeatureMap fmap;
// Two features with different FAIMS CV values
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
f1.setMetaValue(Constants::UserParam::FAIMS_CV, -45.0);
Feature f2 = createTestFeature(101.0, 500.01, 500.0, 2);
f2.setMetaValue(Constants::UserParam::FAIMS_CV, -60.0); // different CV
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
// With require_same_im=true, features should NOT merge (different CVs)
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, true,
MergeIntensityMode::SUM, true);
TEST_EQUAL(fmap.size(), 2)
// Reset and test with require_same_im=false
fmap.clear();
f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
f1.setMetaValue(Constants::UserParam::FAIMS_CV, -45.0);
f2 = createTestFeature(101.0, 500.01, 500.0, 2);
f2.setMetaValue(Constants::UserParam::FAIMS_CV, -60.0);
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, false,
MergeIntensityMode::SUM, true);
// With require_same_im=false, features SHOULD merge
TEST_EQUAL(fmap.size(), 1)
TEST_REAL_SIMILAR(fmap[0].getIntensity(), 1500.0)
// Check FAIMS CV values were collected
TEST_EQUAL(fmap[0].metaValueExists("merged_centroid_IMs"), true)
std::vector<double> merged_ims = fmap[0].getMetaValue("merged_centroid_IMs");
TEST_EQUAL(merged_ims.size(), 2)
TEST_EQUAL(fmap[0].getMetaValue("FAIMS_merge_count"), 2)
}
END_SECTION
START_SECTION(mergeOverlappingFeatures - require_same_im with same FAIMS_CV)
{
FeatureMap fmap;
// Two features with same FAIMS CV values
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
f1.setMetaValue(Constants::UserParam::FAIMS_CV, -45.0);
Feature f2 = createTestFeature(101.0, 500.01, 500.0, 2);
f2.setMetaValue(Constants::UserParam::FAIMS_CV, -45.0); // same CV
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
// With require_same_im=true, features SHOULD merge (same CVs)
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, true,
MergeIntensityMode::SUM, true);
TEST_EQUAL(fmap.size(), 1)
TEST_REAL_SIMILAR(fmap[0].getIntensity(), 1500.0)
}
END_SECTION
START_SECTION(mergeOverlappingFeatures - features without FAIMS_CV)
{
FeatureMap fmap;
// Two features without FAIMS CV (should merge when require_same_im=true)
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
Feature f2 = createTestFeature(101.0, 500.01, 500.0, 2);
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
// Both without FAIMS_CV should be treated as same group
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, true,
MergeIntensityMode::SUM, true);
TEST_EQUAL(fmap.size(), 1)
TEST_REAL_SIMILAR(fmap[0].getIntensity(), 1500.0)
// No FAIMS CV meta values should be present
TEST_EQUAL(fmap[0].metaValueExists("merged_centroid_IMs"), false)
TEST_EQUAL(fmap[0].metaValueExists("FAIMS_merge_count"), false)
}
END_SECTION
START_SECTION(mergeOverlappingFeatures - mixed FAIMS_CV presence with require_same_im)
{
FeatureMap fmap;
// One feature with FAIMS CV, one without
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
f1.setMetaValue(Constants::UserParam::FAIMS_CV, -45.0);
Feature f2 = createTestFeature(101.0, 500.01, 500.0, 2);
// f2 has no FAIMS_CV
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
// With require_same_im=true, features should NOT merge (one has CV, one doesn't)
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, true,
MergeIntensityMode::SUM, true);
TEST_EQUAL(fmap.size(), 2)
}
END_SECTION
START_SECTION(mergeOverlappingFeatures - write_meta_values=false)
{
FeatureMap fmap;
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
f1.setMetaValue(Constants::UserParam::FAIMS_CV, -45.0);
Feature f2 = createTestFeature(101.0, 500.01, 500.0, 2);
f2.setMetaValue(Constants::UserParam::FAIMS_CV, -60.0);
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
// With write_meta_values=false, no merge tracking meta values should be written
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, false,
MergeIntensityMode::SUM, false);
TEST_EQUAL(fmap.size(), 1)
TEST_REAL_SIMILAR(fmap[0].getIntensity(), 1500.0)
// No meta values should be present
TEST_EQUAL(fmap[0].metaValueExists("merged_centroid_rts"), false)
TEST_EQUAL(fmap[0].metaValueExists("merged_centroid_mzs"), false)
TEST_EQUAL(fmap[0].metaValueExists("merged_centroid_IMs"), false)
TEST_EQUAL(fmap[0].metaValueExists("FAIMS_merge_count"), false)
}
END_SECTION
START_SECTION(mergeOverlappingFeatures - no merge when outside tolerance)
{
FeatureMap fmap;
// Two features outside the tolerance
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
Feature f2 = createTestFeature(110.0, 500.0, 500.0, 2); // 10 seconds apart (> 5.0 tolerance)
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, false,
MergeIntensityMode::SUM, true);
// Features should NOT merge (outside RT tolerance)
TEST_EQUAL(fmap.size(), 2)
}
END_SECTION
START_SECTION(mergeOverlappingFeatures - multiple features merging)
{
FeatureMap fmap;
// Three features that should all merge together
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
Feature f2 = createTestFeature(101.0, 500.01, 500.0, 2);
Feature f3 = createTestFeature(102.0, 500.02, 300.0, 2);
fmap.push_back(f1);
fmap.push_back(f2);
fmap.push_back(f3);
for (auto& f : fmap) f.ensureUniqueId();
FeatureOverlapFilter::mergeOverlappingFeatures(fmap, 5.0, 0.05, true, false,
MergeIntensityMode::SUM, true);
TEST_EQUAL(fmap.size(), 1)
// All three intensities summed
TEST_REAL_SIMILAR(fmap[0].getIntensity(), 1800.0)
// Check all three positions were collected
std::vector<double> merged_rts = fmap[0].getMetaValue("merged_centroid_rts");
TEST_EQUAL(merged_rts.size(), 3)
}
END_SECTION
START_SECTION(mergeFAIMSFeatures - only merges features with different FAIMS_CV)
{
FeatureMap fmap;
// Two FAIMS features with DIFFERENT CVs - should merge
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
f1.setMetaValue(Constants::UserParam::FAIMS_CV, -45.0);
Feature f2 = createTestFeature(101.0, 500.01, 500.0, 2);
f2.setMetaValue(Constants::UserParam::FAIMS_CV, -60.0); // Different CV
// Two non-FAIMS features at same location - should NOT merge
Feature f3 = createTestFeature(100.5, 500.005, 800.0, 2);
Feature f4 = createTestFeature(101.5, 500.015, 400.0, 2);
fmap.push_back(f1);
fmap.push_back(f2);
fmap.push_back(f3);
fmap.push_back(f4);
for (auto& f : fmap) f.ensureUniqueId();
FeatureOverlapFilter::mergeFAIMSFeatures(fmap, 5.0, 0.05);
// Should have 3 features: 1 merged FAIMS + 2 separate non-FAIMS
TEST_EQUAL(fmap.size(), 3)
// Check that FAIMS features were merged
int faims_count = 0;
int non_faims_count = 0;
for (const auto& f : fmap)
{
if (f.metaValueExists("merged_centroid_IMs") || f.metaValueExists(Constants::UserParam::FAIMS_CV))
{
faims_count++;
if (f.metaValueExists("merged_centroid_IMs"))
{
// This is the merged feature
TEST_REAL_SIMILAR(f.getIntensity(), 1500.0)
}
}
else
{
non_faims_count++;
}
}
TEST_EQUAL(faims_count, 1) // One merged FAIMS feature
TEST_EQUAL(non_faims_count, 2) // Two untouched non-FAIMS features
}
END_SECTION
START_SECTION(mergeFAIMSFeatures - does NOT merge features with same FAIMS_CV)
{
FeatureMap fmap;
// Two FAIMS features with SAME CV - should NOT merge (different analytes)
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
f1.setMetaValue(Constants::UserParam::FAIMS_CV, -45.0);
Feature f2 = createTestFeature(101.0, 500.01, 500.0, 2);
f2.setMetaValue(Constants::UserParam::FAIMS_CV, -45.0); // Same CV
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
FeatureOverlapFilter::mergeFAIMSFeatures(fmap, 5.0, 0.05);
// Should still have 2 features - same CV features are not merged
TEST_EQUAL(fmap.size(), 2)
TEST_REAL_SIMILAR(fmap[0].getIntensity(), 1000.0)
TEST_REAL_SIMILAR(fmap[1].getIntensity(), 500.0)
// Neither should have merge meta values
TEST_EQUAL(fmap[0].metaValueExists("merged_centroid_IMs"), false)
TEST_EQUAL(fmap[1].metaValueExists("merged_centroid_IMs"), false)
}
END_SECTION
START_SECTION(mergeFAIMSFeatures - no-op on non-FAIMS data)
{
FeatureMap fmap;
// Two non-FAIMS features at same location
Feature f1 = createTestFeature(100.0, 500.0, 1000.0, 2);
Feature f2 = createTestFeature(101.0, 500.01, 500.0, 2);
fmap.push_back(f1);
fmap.push_back(f2);
for (auto& f : fmap) f.ensureUniqueId();
FeatureOverlapFilter::mergeFAIMSFeatures(fmap, 5.0, 0.05);
// Should still have 2 features - no merging on non-FAIMS data
TEST_EQUAL(fmap.size(), 2)
TEST_REAL_SIMILAR(fmap[0].getIntensity(), 1000.0)
TEST_REAL_SIMILAR(fmap[1].getIntensity(), 500.0)
}
END_SECTION
END_TEST
| C++ |
3D | OpenMS/OpenMS | src/tests/class_tests/openms/source/StopWatch_test.cpp | .cpp | 7,103 | 238 | // 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 $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/SYSTEM/StopWatch.h>
#include <chrono>
/////////////////////////////////////////////////////////////
using namespace OpenMS;
void wait(double seconds)
{
auto start = std::chrono::system_clock::now();
while (true)
{
double s = std::chrono::duration<double>(std::chrono::system_clock::now() - start).count();
if (s > seconds) break;
};
}
START_TEST(StopWatch, "$Id$")
/////////////////////////////////////////////////////////////
START_SECTION((StopWatch& operator = (const StopWatch& stop_watch)))
NOT_TESTABLE; // tested below
END_SECTION
START_SECTION((StopWatch()))
NOT_TESTABLE; // tested below
END_SECTION
START_SECTION((StopWatch(const StopWatch& stop_watch)))
StopWatch s1, s2;
s1.start();
wait(0.01);
TEST_FALSE(s1 == s2) // before stop
s1.stop();
TEST_FALSE(s1 == s2)
s2 = s1;
TEST_TRUE(s1 == s2)
StopWatch s3(s1);
TEST_TRUE(s1 == s3)
StopWatch s4;
s1.reset();
TEST_TRUE(s1 == s4)
s1.start();
s2.start();
wait(0.01);
s1.stop();
wait(0.01);
s2.stop();
TEST_FALSE(s1 == s2)
TEST_EQUAL(s1 <= s2, true)
TEST_EQUAL(s2 >= s1, true)
END_SECTION
START_SECTION((bool isRunning() const))
StopWatch w;
TEST_EQUAL(w.isRunning(), false);
w.start();
TEST_EQUAL(w.isRunning(), true);
w.stop();
TEST_EQUAL(w.isRunning(), false);
END_SECTION
START_SECTION((bool operator != (const StopWatch& stop_watch) const))
NOT_TESTABLE; // tested above
END_SECTION
START_SECTION((bool operator < (const StopWatch& stop_watch) const))
NOT_TESTABLE; // since we do not have control over system time...
END_SECTION
START_SECTION((bool operator <= (const StopWatch& stop_watch) const))
NOT_TESTABLE; // tested above
END_SECTION
START_SECTION((bool operator == (const StopWatch& stop_watch) const))
NOT_TESTABLE; // tested above
END_SECTION
START_SECTION((bool operator > (const StopWatch& stop_watch) const))
NOT_TESTABLE; // since we do not have control over system time...
END_SECTION
START_SECTION((bool operator >= (const StopWatch& stop_watch) const))
NOT_TESTABLE; // tested above
END_SECTION
START_SECTION((bool start()))
StopWatch s1;
s1.start();
TEST_EXCEPTION(Exception::Precondition, s1.start()); // cannot start twice
END_SECTION
START_SECTION((bool stop()))
const double t_wait = 0.2;
const double t_wait_more = 0.1;
StopWatch s, s_nostop, s_reset, s_resume;
s.start();
s_nostop.start();
s_reset.start();
s_resume.resume();
wait(t_wait);
s.stop();
s_resume.stop();
TEST_EXCEPTION(Exception::Precondition, s.stop()); // cannot stop twice
TEST_EQUAL(s.getClockTime() > 0.1, true)
TEST_EQUAL(s.getClockTime() < 0.3, true)
double t1 = s.getCPUTime();
double t2 = s.getClockTime();
double t3 = s.getSystemTime();
double t4 = s.getUserTime();
s_reset.reset();
TEST_EQUAL(s_reset.isRunning(), true); // keeps on running
s_resume.resume();
// wait some more
wait(t_wait_more);
// ... and see if time is still the old one
TEST_EQUAL(s.getCPUTime(), t1)
TEST_EQUAL(s.getClockTime(), t2)
TEST_EQUAL(s.getSystemTime(), t3)
TEST_EQUAL(s.getUserTime(), t4)
TEST_EQUAL(s.getCPUTime(), t1)
TEST_EQUAL(s.getCPUTime() > t_wait / 2, true) // waiting costs CPU time in our implementation... just not sure how much...
TEST_EQUAL(s.getClockTime() > t_wait * 0.95, true) // and must consume wall time
TEST_EQUAL(s.getClockTime() < t_wait * 3, true) // be a bit more loose if e.g. a VM is busy
std::cout << "Usertime: " << s.getUserTime() << "\n";
#ifdef OPENMS_WINDOWSPLATFORM
// workaround for Windows-CI on VMs which report usertime = 0 ...
TEST_EQUAL(s.getUserTime() >= 0, true)// and some user time
#else
TEST_EQUAL(s.getUserTime() > t_wait / 2, true)// and some user time
#endif
TEST_EQUAL(s.getUserTime() < t_wait * 2, true)
std::cout << "Systemtime: " << s.getSystemTime() << "\n";
TEST_EQUAL(s.getSystemTime() < t_wait * 2, true)// and usually quite few system time
// (not guaranteed on VMs, therefore do a trivial check)
// the watch that never stopped should be ahead...
TEST_EQUAL(s.getCPUTime() < s_nostop.getCPUTime(), true)
TEST_EQUAL(s.getClockTime() < s_nostop.getClockTime(), true)
std::cout << "compare: " << s.getUserTime() << " <> " << s_nostop.getUserTime() << "\n";
#ifdef OPENMS_WINDOWSPLATFORM
// workaround for Windows-CI on VMs which report usertime = 0 ...
TEST_EQUAL(s.getUserTime() <= s_nostop.getUserTime(), true)
#else
TEST_EQUAL(s.getUserTime() < s_nostop.getUserTime(), true)
#endif
TEST_EQUAL(s.getSystemTime() <= s_nostop.getSystemTime(), true)
s.reset(); // was stopped, so remains stopped
TEST_EQUAL(s.isRunning(), false);
TEST_EQUAL(s == StopWatch(), true);
// kept on running the whole time after reset above .. should accumulate time
TEST_EQUAL(s_reset.getCPUTime() > 0, true);
// don't stop the timer.. just keep running and query on the fly
TEST_EQUAL(s_resume.getCPUTime() > (t_wait_more + t_wait) / 2, true) // waiting costs CPU time in our implementation... just not sure how much...
TEST_EQUAL(s_resume.getClockTime() > (t_wait_more + t_wait) * 0.95, true) // must consume wall time
END_SECTION
START_SECTION((void clear()))
StopWatch s;
s.start();
s.clear();
TEST_EQUAL(s.isRunning(), false);
TEST_EQUAL(s == StopWatch(), true);
END_SECTION
START_SECTION((void reset()))
NOT_TESTABLE; // done above to save Test time
END_SECTION
START_SECTION((void resume()))
StopWatch s1;
s1.start();
TEST_EXCEPTION(Exception::Precondition, s1.resume()); // cannot start twice
END_SECTION
START_SECTION((double getCPUTime() const ))
NOT_TESTABLE; // done above
END_SECTION
START_SECTION((double getClockTime() const ))
NOT_TESTABLE; // done above
END_SECTION
START_SECTION((double getSystemTime() const ))
NOT_TESTABLE; // done above
END_SECTION
START_SECTION((double getUserTime() const ))
NOT_TESTABLE; // done above
END_SECTION
START_SECTION((virtual ~StopWatch()))
NOT_TESTABLE; // done above
END_SECTION
START_SECTION((static String toString(double time)))
TEST_EQUAL(StopWatch::toString(0), "0.00 s")
TEST_EQUAL(StopWatch::toString(1), "1.00 s")
TEST_EQUAL(StopWatch::toString(1.5), "1.50 s")
TEST_EQUAL(StopWatch::toString(100.5), "01:40 m")
TEST_EQUAL(StopWatch::toString(3600*24*5 + 3600*9 + 5), "5d 09:00:05 h")
TEST_EQUAL(StopWatch::toString(160.5), "02:40 m")
TEST_EQUAL(StopWatch::toString(3600*23 + 160.5), "23:02:40 h")
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.