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/openms/source/QC/TIC.cpp | .cpp | 3,155 | 106 | // 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/PROCESSING/RESAMPLING/LinearResamplerAlign.h>
#include <OpenMS/FORMAT/MzTab.h>
#include <OpenMS/QC/TIC.h>
using namespace std;
namespace OpenMS
{
TIC::Result TIC::compute(const MSExperiment& exp, float bin_size, UInt ms_level)
{
TIC::Result result;
MSChromatogram tic = exp.calculateTIC(bin_size, ms_level);
if (!tic.empty())
{
for (const auto& p : tic)
{
result.intensities.push_back(p.getIntensity());
result.retention_times.push_back(p.getRT());
}
UInt max_int = *max_element(result.intensities.begin(), result.intensities.end());
for (const auto& i : result.intensities)
{
if (max_int != 0)
{
result.relative_intensities.push_back((double)i / max_int * 100);
}
else
{
result.relative_intensities.push_back(0.0);
}
}
result.area = result.intensities[0];
for (size_t i = 1; i < result.intensities.size(); ++i)
{
result.area += result.intensities[i];
if (result.intensities[i] > result.intensities[i - 1] * 10) // detect 10x jumps between two subsequent scans
{
++result.jump;
}
if (result.intensities[i] < result.intensities[i - 1] / 10) // detect 10x falls between two subsequent scans
{
++result.fall;
}
}
}
return result;
}
bool TIC::Result::operator==(const Result& rhs) const
{
return intensities == rhs.intensities && retention_times == rhs.retention_times && area == rhs.area && fall == rhs.fall && jump == rhs.jump;
}
/// Returns the name of the metric
const String& TIC::getName() const
{
return name_;
}
/// Returns required file input i.e. MzML.
/// This is encoded as a bit in a Status object.
QCBase::Status TIC::requirements() const
{
return QCBase::Status(QCBase::Requires::RAWMZML);
}
void TIC::addMetaDataMetricsToMzTab(OpenMS::MzTabMetaData& meta, vector<TIC::Result>& tics)
{
// Adding TIC information to meta data
for (Size i = 0; i < tics.size(); ++i)
{
if (tics[i].intensities.empty())
{
continue; // no MS1 spectra
}
MzTabParameter tic {};
tic.setCVLabel("total ion current");
tic.setAccession("MS:1000285");
tic.setName("TIC_" + String(i + 1));
String value("[");
value += String(tics[i].retention_times[0], false) + ", " + String((UInt64)tics[i].intensities[0]);
for (Size j = 1; j < tics[i].intensities.size(); ++j)
{
value += ", " + String(tics[i].retention_times[j], false) + ", " + String((UInt64)tics[i].intensities[j]);
}
value += "]";
tic.setValue(value);
meta.custom[meta.custom.size()] = tic;
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/QC/MQEvidenceExporter.cpp | .cpp | 12,696 | 326 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow$
// $Authors: Valentin Noske, Vincent Musch$
// --------------------------------------------------------------------------
#include <OpenMS/QC/MQEvidenceExporter.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <QtCore/QDir>
#include <cmath> // isnan
#include <fstream>
#include <vector>
using namespace OpenMS;
MQEvidence::MQEvidence(const String& path)
{
if (path.empty())
{
return;
}
filename_ = path + "/evidence.txt";
try
{
QString evi_path = QString::fromStdString(path);
QDir().mkpath(evi_path);
file_ = std::fstream(filename_, std::fstream::out);
}
catch (...)
{
OPENMS_LOG_FATAL_ERROR << filename_ << " wasn’t created" << std::endl;
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "out_evd");
}
exportHeader_();
}
MQEvidence::~MQEvidence()
{
file_.close();
}
void MQEvidence::exportHeader_()
{
file_ << "Sequence" << "\t";
file_ << "Length" << "\t";
file_ << "Modifications" << "\t";
file_ << "Modified sequence" << "\t";
// file_ << "Oxidation (M) Probabilities" << "\t"; not supported by OpenMS
// file_ << "Oxidation (M) Score Diffs" << "\t"; not supported by OpenMS
file_ << "Acetyl (Protein N-term)" << "\t";
file_ << "Oxidation (M)" << "\t";
file_ << "Missed cleavages" << "\t";
file_ << "Proteins" << "\t";
file_ << "Leading Proteins" << "\t";
file_ << "Leading Razor Protein" << "\t";
file_ << "Gene Names" << "\t";
file_ << "Protein Names" << "\t";
file_ << "Type" << "\t";
file_ << "Raw file" << "\t";
// file_ << "Fraction" << "\t"; not in this workflow
file_ << "MS/MS m/z" << "\t";
file_ << "Charge" << "\t";
file_ << "m/z" << "\t";
file_ << "Mass" << "\t";
file_ << "Resolution" << "\t";
file_ << "Uncalibrated - Calibrated m/z [ppm]" << "\t";
file_ << "Uncalibrated - Calibrated m/z [Da]" << "\t";
file_ << "Mass Error [ppm]" << "\t";
file_ << "Mass Error [Da]" << "\t";
file_ << "Uncalibrated Mass Error [ppm]" << "\t";
file_ << "Uncalibrated Mass Error [Da]" << "\t";
// file_ << "Max intensity m/z 0" << "\t";
file_ << "Retention time" << "\t";
file_ << "Retention length" << "\t";
file_ << "Calibrated retention time" << "\t";
file_ << "Calibrated retention time start" << "\t";
file_ << "Calibrated retention time finish" << "\t";
file_ << "Retention time calibration" << "\t";
file_ << "Match time difference" << "\t";
file_ << "Match m/z difference" << "\t";
file_ << "Match q-value" << "\t";
file_ << "Match score" << "\t";
file_ << "Number of data points" << "\t";
// file_ << "Number of scans" << "\t"; not practical to implement
file_ << "Number of isotopic peaks" << "\t";
// file_ << "PIF" << "\t"; not practical to implement
file_ << "Fraction of total spectrum" << "\t";
file_ << "Base peak fraction" << "\t";
file_ << "PEP" << "\t";
file_ << "MS/MS Count" << "\t";
file_ << "MS/MS Scan Number" << "\t";
file_ << "Score" << "\t";
file_ << "Delta score" << "\t";
// file_ << "Combinatorics" << "\t"; not supported by OpenMS
file_ << "Intensity" << "\t";
/*file_ << "Reporter intensity 0" << "\t"; not supported by the given data
file_ << "Reporter intensity 1" << "\t";
file_ << "Reporter intensity 2" << "\t";
file_ << "Reporter intensity 3" << "\t";
file_ << "Reporter intensity 4" << "\t";
file_ << "Reporter intensity 5" << "\t";
file_ << "Reporter intensity not corrected 0" << "\t";
file_ << "Reporter intensity not corrected 1" << "\t";
file_ << "Reporter intensity not corrected 2" << "\t";
file_ << "Reporter intensity not corrected 3" << "\t";
file_ << "Reporter intensity not corrected 4" << "\t";
file_ << "Reporter intensity not corrected 5" << "\t";
file_ << "Reporter PIF" << "\t";
file_ << "Reporter fraction" << "\t"; */
file_ << "Reverse" << "\t";
file_ << "Potential contaminant" << "\t";
file_ << "id" << "\t";
file_ << "Protein group IDs" << "\n";
/*file_ << "Peptide ID" << "\t"; not useful without the other MQ files
file_ << "Mod. peptide ID" << "\t";
file_ << "MS/MS IDs" << "\t";
file_ << "Best MS/MS" << "\t";
file_ << "AIF MS/MS IDs" << "\t";
file_ << "Oxidation (M) site IDs" << "\n"; */
}
void MQEvidence::exportRowFromFeature_(
const Feature& f,
const ConsensusMap& cmap,
const Size c_feature_number,
const String& raw_file,
const std::multimap<String, std::pair<Size, Size>>& UIDs,
const ProteinIdentification::Mapping& mp_f,
const MSExperiment& exp,
const std::map<String,String>& prot_mapper)
{
MQExporterHelper::MQCommonOutputs common_outputs{f, cmap, c_feature_number, UIDs, mp_f, exp, prot_mapper};
const PeptideHit* ptr_best_hit; // the best hit referring to score
const ConsensusFeature& cf = cmap[c_feature_number];
Size pep_ids_size = 0;
String type;
if (MQExporterHelper::hasValidPepID_(f, c_feature_number, UIDs, mp_f))
{
for (Size i = 1; i < f.getPeptideIdentifications().size(); ++i) // for msms-count
{
if (!f.getPeptideIdentifications()[i].getHits().empty())
{
if (f.getPeptideIdentifications()[i].getHits()[0].getSequence() == f.getPeptideIdentifications()[0].getHits()[0].getSequence())
{
++pep_ids_size;
}
else
break;
}
}
type = "MULTI-MSMS";
ptr_best_hit = &f.getPeptideIdentifications()[0].getHits()[0];
}
else if (MQExporterHelper::hasPeptideIdentifications_(cf))
{
type = "MULTI-MATCH";
ptr_best_hit = &cf.getPeptideIdentifications()[0].getHits()[0];
}
else
{
return; // no valid PepID; nothing to export
}
const AASequence& pep_seq = ptr_best_hit->getSequence();
if (pep_seq.empty())
{
return;
}
file_ << pep_seq.toUnmodifiedString() << "\t"; // Sequence
file_ << pep_seq.size() << "\t"; // Length
file_ << common_outputs.modifications.str() << "\t"; // Modifications
file_ << "_" << pep_seq << "_" << "\t"; // Modified Sequence
file_ << common_outputs.acetyl << "\t", // Acetyl (Protein N-term)
file_ << common_outputs.oxidation.str() << "\t"; // Oxidation (M)
file_ << ptr_best_hit->getMetaValue("missed_cleavages", "NA") << "\t"; // missed cleavages
const std::set<String>& accessions = ptr_best_hit->extractProteinAccessionsSet();
file_ << ListUtils::concatenate(accessions, ";") << "\t"; // Proteins
file_ << ptr_best_hit->getPeptideEvidences()[0].getProteinAccession() << "\t"; // Leading Proteins
file_ << ptr_best_hit->getPeptideEvidences()[0].getProteinAccession() << "\t"; // Leading Razor Proteins
file_ << common_outputs.gene_names.str() << "\t"; // Gene Names
file_ << common_outputs.protein_names.str() << "\t"; // Protein Names
file_ << type << "\t"; //type
file_ << raw_file << "\t"; // Raw File
file_ << common_outputs.msms_mz.str() << "\t"; // MS/MS m/z
file_ << f.getCharge() << "\t"; // Charge
file_ << f.getMZ() << "\t"; // MZ
file_ << pep_seq.getMonoWeight() << "\t"; // Mass
file_ << f.getMZ() / f.getWidth() << "\t"; // Resolution
file_ << common_outputs.uncalibrated_calibrated_mz_ppm.str() << "\t"; // Uncalibrated - Calibrated m/z [ppm]
file_ << common_outputs.uncalibrated_calibrated_mz_mda.str() << "\t"; // Uncalibrated - Calibrated m/z [Da]
file_ << common_outputs.mass_error_ppm.str() << "\t"; // Mass error [ppm]
file_ << common_outputs.mass_error_da.str() << "\t"; // Mass error [Da]
file_ << common_outputs.uncalibrated_mass_error_ppm.str() << "\t"; // Uncalibrated Mass error [ppm]
file_ << common_outputs.uncalibrated_mass_error_da .str() << "\t"; // Uncalibrated Mass error [Da]
file_ << f.getRT() / 60 << "\t"; // Retention time in min.
// RET LENGTH
f.metaValueExists("rt_raw_end") && f.metaValueExists("rt_raw_start") ?
file_ << (double(f.getMetaValue("rt_raw_end")) - double(f.getMetaValue("rt_raw_start"))) / 60 << "\t" : file_
<< "NA" << "\t";
if (f.metaValueExists("rt_align"))
{
file_ << double(f.getMetaValue("rt_align")) / 60 << "\t"; // Calibrated Retention Time
}
f.metaValueExists("rt_align_start") ? file_ << double(f.getMetaValue("rt_align_start")) / 60 << "\t" :
file_ << "NA" << "\t"; // Calibrated retention time start
f.metaValueExists("rt_align_end") ? file_ << double(f.getMetaValue("rt_align_end")) / 60 << "\t" :
file_ << "NA" << "\t"; // Calibrated retention time end
if (f.metaValueExists("rt_align"))
{
file_ << ((double(f.getMetaValue("rt_align")) - f.getRT() ) / 60) << "\t"; // Retention time calibration
}
else
{
file_ << "NA" << "\t"; // calibrated retention time
file_ << "NA" << "\t"; // Retention time calibration
}
if (type == "MULTI-MSMS")
{
file_ << "NA" << "\t"; // Match time diff
file_ << "NA" << "\t"; // Match mz diff
}
else
{
f.metaValueExists("rt_align") ? file_ << double(f.getMetaValue("rt_align")) - cmap[c_feature_number].getRT() << "\t" :
file_ << "NA"
<< "\t"; // Match time diff
file_ << f.getMZ() - cmap[c_feature_number].getMZ() << "\t"; // Match mz diff
}
const PeptideHit* cf_ptr_best_hit = &cf.getPeptideIdentifications()[0].getHits()[0];
cf_ptr_best_hit->metaValueExists("qvalue")? file_ << cf_ptr_best_hit->getMetaValue("qvalue") << "\t" : file_ << "\t"; // Match q-value
file_ << cf_ptr_best_hit->getScore() << "\t"; // Match score
f.metaValueExists(Constants::UserParam::NUM_OF_DATAPOINTS) ? file_ << (f.getMetaValue(Constants::UserParam::NUM_OF_DATAPOINTS)) << "\t": file_ << "\t"; // Number of data points
file_ << f.getConvexHulls().size() << "\t"; // Number of isotopic peaks
f.metaValueExists(Constants::UserParam::PSM_EXPLAINED_ION_CURRENT_USERPARAM) ? file_ << (f.getMetaValue(Constants::UserParam::PSM_EXPLAINED_ION_CURRENT_USERPARAM)) << "\t": file_ << "\t"; // Fraction of total spectrum
file_ << common_outputs.base_peak_fraction.str() << "\t"; // Base peak fraction
ptr_best_hit->metaValueExists("PEP")? file_ << ptr_best_hit->getMetaValue("PEP") << "\t" : file_ << "\t"; // PEP
file_ << pep_ids_size << "\t"; // MS/MS count
f.metaValueExists("spectrum_index") ? file_ << (f.getMetaValue("spectrum_index")) << "\t" : file_ << "\t";// MS/MS Scan Number
file_ << ptr_best_hit->getScore() << "\t"; // Score
f.metaValueExists("delta") ? file_ << (f.getMetaValue("delta")) << "\t" : file_ << "\t"; // Delta score
file_ << f.getIntensity() << "\t"; // Intensity
ptr_best_hit->isDecoy() ? file_ << "1\t" : file_ << "\t"; // reverse
String pot_containment = ptr_best_hit->getMetaValue("is_contaminant", "NA");
if (pot_containment == "1")
{
file_ << "+"
<< "\t"; // Potential contaminant
}
else
{
file_ << "\t";
}
file_ << id_ << "\t"; // ID
++id_;
file_ << ListUtils::concatenate(accessions, ";") << "\n"; // Protein group IDs
}
void MQEvidence::exportFeatureMap(const FeatureMap& feature_map, const ConsensusMap& cmap, const MSExperiment& exp, const std::map<String,String>& prot_mapper)
{
if (!MQExporterHelper::isValid(filename_))
{
OPENMS_LOG_ERROR << "MqEvidence object is not valid." << std::endl;
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename_);
}
const std::map<Size, Size>& fTc = MQExporterHelper::makeFeatureUIDtoConsensusMapIndex_(cmap);
StringList spectra_data;
feature_map.getPrimaryMSRunPath(spectra_data);
String raw_file = File::basename(spectra_data.empty() ? feature_map.getLoadedFilePath() : spectra_data[0]);
ProteinIdentification::Mapping mp_f;
mp_f.create(feature_map.getProteinIdentifications());
std::multimap<String, std::pair<Size, Size>> UIDs = PeptideIdentification::buildUIDsFromAllPepIDs(cmap);
for (const Feature& f : feature_map)
{
const Size& f_id = f.getUniqueId();
const auto& c_id = fTc.find(f_id);
if (c_id != fTc.end())
{
exportRowFromFeature_(f, cmap, c_id->second, raw_file, UIDs, mp_f, exp, prot_mapper);
}
else
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Feature in FeatureMap has no associated ConsensusFeature.");
}
}
file_.flush();
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/QC/IdentificationSummary.cpp | .cpp | 3,812 | 108 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Axel Walter $
// $Authors: Axel Walter $
// --------------------------------------------------------------------------
#include <OpenMS/QC/IdentificationSummary.h>
#include <OpenMS/QC/MissedCleavages.h>
#include <iostream>
#include <set>
using namespace std;
namespace OpenMS
{
IdentificationSummary::Result IdentificationSummary::compute(vector<ProteinIdentification>& prot_ids, PeptideIdentificationList& pep_ids)
{
IdentificationSummary::Result result;
set<String> peptides;
set<String> proteins;
// PSMs and collect unique peptides in set
for (const auto& pep_id : pep_ids)
{
if (!pep_id.empty())
{
result.peptide_spectrum_matches += 1;
const auto& temp_hits = pep_id.getHits();
if (temp_hits.empty())
continue;
peptides.insert(temp_hits[0].getSequence().toUnmodifiedString());
}
}
// get sum of all peptide length for mean calculation
UInt peptide_length_sum = 0;
for (const auto& pep : peptides)
{
peptide_length_sum += pep.size();
}
result.peptide_length_mean = (double)peptide_length_sum / peptides.size();
// get missed cleavages
UInt missed_cleavages = 0;
UInt pep_count = 0;
MissedCleavages mc;
mc.compute(prot_ids, pep_ids);
for (const auto& m : mc.getResults())
{
for (const auto& [key, val] : m)
{
missed_cleavages += key * val;
pep_count += val;
}
}
result.missed_cleavages_mean = (double)missed_cleavages / pep_count;
// collect unique proteins in sets and scores mean
double protein_hit_scores_sum = 0;
UInt protein_hit_count = 0;
for (const auto& prot_id : prot_ids)
{
const auto& temp_hits = prot_id.getHits();
protein_hit_count += temp_hits.size();
for (const auto& temp_hit : temp_hits)
{
proteins.insert(temp_hit.getAccession());
protein_hit_scores_sum += temp_hit.getScore();
}
}
result.protein_hit_scores_mean = protein_hit_scores_sum / protein_hit_count;
// unique peptides and proteins with their significance threshold (always the same in idXML file)
// get significance threshold if score type is FDR, else -1
result.unique_peptides.count = peptides.size();
result.unique_proteins.count = proteins.size();
if (pep_ids.front().getScoreType() == "FDR")
{
result.unique_peptides.fdr_threshold = pep_ids.front().getSignificanceThreshold();
}
if (prot_ids.front().getScoreType() == "FDR")
{
result.unique_proteins.fdr_threshold = prot_ids.front().getSignificanceThreshold();
}
return result;
}
bool IdentificationSummary::Result::operator==(const Result& rhs) const
{
return peptide_spectrum_matches == rhs.peptide_spectrum_matches && unique_peptides.count == rhs.unique_peptides.count && unique_peptides.fdr_threshold == rhs.unique_peptides.fdr_threshold &&
unique_proteins.count == rhs.unique_proteins.count && unique_proteins.fdr_threshold == rhs.unique_proteins.fdr_threshold && missed_cleavages_mean == rhs.missed_cleavages_mean &&
protein_hit_scores_mean == rhs.protein_hit_scores_mean && peptide_length_mean == rhs.peptide_length_mean;
}
/// Returns the name of the metric
const String& IdentificationSummary::getName() const
{
return name_;
}
/// Returns required file input i.e. MzML.
/// This is encoded as a bit in a Status object.
QCBase::Status IdentificationSummary::requirements() const
{
return QCBase::Status(QCBase::Requires::ID);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/QC/PeptideMass.cpp | .cpp | 1,061 | 39 | // 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/KERNEL/FeatureMap.h>
#include <OpenMS/QC/PeptideMass.h>
namespace OpenMS
{
void PeptideMass::compute(FeatureMap& features)
{
features.applyFunctionOnPeptideIDs(
[](PeptideIdentification& pi) {
if (pi.getHits().empty())
{
return;
}
auto& hit = pi.getHits()[0];
hit.setMetaValue("mass", (pi.getMZ() - Constants::PROTON_MASS_U) * hit.getCharge());
},
true);
}
const String& PeptideMass::getName() const
{
static const String& name = "PeptideMass";
return name;
}
QCBase::Status PeptideMass::requirements() const
{
return QCBase::Status() | QCBase::Requires::POSTFDRFEAT;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/QC/MQExporterHelper.cpp | .cpp | 10,802 | 269 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow$
// $Authors: Virginia Rossow, Lenny Kovac, Hendrik Beschorner$
// --------------------------------------------------------------------------
#include <OpenMS/QC/MQExporterHelper.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <fstream>
using namespace OpenMS;
Size MQExporterHelper::proteinGroupID_(std::map<OpenMS::String, OpenMS::Size>& database,
const String& protein_accession)
{
if (auto it = database.find(protein_accession); it == database.end())
{
database.emplace(protein_accession, database.size() + 1);
return database.size();
}
else
{
return it->second;
}
}
std::map<Size, Size> MQExporterHelper::makeFeatureUIDtoConsensusMapIndex_(const ConsensusMap& cmap)
{
std::map<Size, Size> f_to_ci;
for (Size i = 0; i < cmap.size(); ++i)
{
for (const auto& fh : cmap[i].getFeatures())
{
auto[it, was_created_newly] = f_to_ci.emplace(fh.getUniqueId(), i);
if (!was_created_newly)
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Adding [" + String(it->first) + "," + String(it->second) + "] failed. FeatureHandle exists twice in ConsensusMap!");
}
}
}
return f_to_ci;
}
bool MQExporterHelper::hasValidPepID_(
const Feature& f,
const Size c_feature_number,
const std::multimap<OpenMS::String, std::pair<OpenMS::Size, OpenMS::Size>>& UIDs,
const ProteinIdentification::Mapping& mp_f)
{
const PeptideIdentificationList& pep_ids_f = f.getPeptideIdentifications();
if (pep_ids_f.empty())
{
return false;
}
const PeptideIdentification& best_pep_id = pep_ids_f[0]; // PeptideIdentifications are sorted
String best_uid = PeptideIdentification::buildUIDFromPepID(best_pep_id, mp_f.identifier_to_msrunpath);
const auto range = UIDs.equal_range(best_uid);
for (std::multimap<OpenMS::String, std::pair<OpenMS::Size, OpenMS::Size>>::const_iterator it_pep = range.first;
it_pep != range.second; ++it_pep)
{
if (c_feature_number == it_pep->second.first)
{
return !pep_ids_f[0].getHits().empty(); // checks if PeptideIdentification has at least one hit
}
}
return false;
}
bool MQExporterHelper::hasPeptideIdentifications_(const ConsensusFeature& cf)
{
const PeptideIdentificationList& pep_ids_c = cf.getPeptideIdentifications();
if (!pep_ids_c.empty())
{
return !pep_ids_c[0].getHits().empty(); // checks if PeptideIdentification has at least one hit
}
return false;
}
bool MQExporterHelper::isValid(const std::string& filename)
{
return File::writable(filename);
}
String MQExporterHelper::extractGeneName(const String& prot_description)
{
String gene_name;
auto pos_gene = prot_description.find("GN=");
// description might not contain a gene name ...
if (pos_gene == std::string::npos) return gene_name;
gene_name = prot_description.substr(pos_gene +3, prot_description.find(" ", pos_gene +3));
return gene_name;
}
MQExporterHelper::MQCommonOutputs::MQCommonOutputs(
const OpenMS::Feature& f,
const OpenMS::ConsensusMap& cmap,
const OpenMS::Size c_feature_number,
const std::multimap<OpenMS::String, std::pair<OpenMS::Size, OpenMS::Size>>& UIDs,
const OpenMS::ProteinIdentification::Mapping& mp_f,
const OpenMS::MSExperiment& exp,
const std::map<OpenMS::String,OpenMS::String>& prot_mapper)
{
const OpenMS::PeptideHit* ptr_best_hit; // the best hit referring to score
const OpenMS::ConsensusFeature& cf = cmap[c_feature_number];
if (MQExporterHelper::hasValidPepID_(f, c_feature_number, UIDs, mp_f))
{
ptr_best_hit = &f.getPeptideIdentifications()[0].getHits()[0];
}
else if (MQExporterHelper::hasPeptideIdentifications_(cf))
{
ptr_best_hit = &cf.getPeptideIdentifications()[0].getHits()[0];
}
else
{
return; // no valid PepID; nothing to export
}
const OpenMS::AASequence& pep_seq = ptr_best_hit->getSequence();
if (pep_seq.empty())
{
return; // empty AASequence; nothing to export
}
std::map<OpenMS::String, OpenMS::Size> modifications_temp;
if (pep_seq.hasNTerminalModification())
{
const OpenMS::String& n_terminal_modification = pep_seq.getNTerminalModificationName();
modifications_temp.emplace(std::make_pair(n_terminal_modification, 1));
}
if (pep_seq.hasCTerminalModification())
{
modifications_temp.emplace(std::make_pair(pep_seq.getCTerminalModificationName(), 1));
}
for (OpenMS::Size i = 0; i < pep_seq.size(); ++i)
{
if (pep_seq.getResidue(i).isModified())
{
++modifications_temp[pep_seq.getResidue(i).getModification()->getFullId()];
}
}
if (modifications_temp.empty())
{
modifications.str("Unmodified");
}
else
{
auto it = modifications_temp.begin();
modifications.clear();
modifications << it->first;
++it;
for (; it != modifications_temp.end(); ++it)
{
modifications << ";" << it->first;
}
}
acetyl = '0';
if (pep_seq.hasNTerminalModification() && pep_seq.getNTerminalModificationName().hasSubstring("Acetyl"))
{
acetyl = '1'; // Acetyl (Protein N-term)
}
oxidation << modifications_temp["Oxidation (M)"];
const std::set<String>& accessions = ptr_best_hit->extractProteinAccessionsSet();
std::vector<String> gene_names_temp;
std::vector<String> protein_names_temp;
for(const auto& prot_access : accessions)
{
if (const auto& prot_mapper_it = prot_mapper.find(prot_access); prot_mapper_it == prot_mapper.end())
{
continue;
}
else
{
auto protein_description = prot_mapper_it->second;
auto gn = extractGeneName(protein_description);
if(!gn.empty())
{
gene_names_temp.push_back(std::move(gn));
}
protein_names_temp.push_back(std::move(protein_description));
}
}
gene_names.str(ListUtils::concatenate(gene_names_temp, ';')); //Gene Names
protein_names.str(ListUtils::concatenate(protein_names_temp, ';')); //Protein Names
if (f.metaValueExists("spectrum_index") && !exp.empty() && exp.getNrSpectra() >= (OpenMS::Size)f.getMetaValue("spectrum_index") && !exp[f.getMetaValue("spectrum_index")].empty())
{
const OpenMS::MSSpectrum& ms2_spec = exp[f.getMetaValue("spectrum_index")];
if (!ms2_spec.getPrecursors().empty())
{
msms_mz << ms2_spec.getPrecursors()[0].getMZ(); // MS/MS m/z
}
}
const double& uncalibrated_mz_error_ppm = ptr_best_hit->getMetaValue("uncalibrated_mz_error_ppm", NAN);
const double& calibrated_mz_error_ppm = ptr_best_hit->getMetaValue("calibrated_mz_error_ppm", NAN);
if (std::isnan(uncalibrated_mz_error_ppm) && std::isnan(calibrated_mz_error_ppm))
{
uncalibrated_calibrated_mz_ppm.str("NA"); // Uncalibrated - Calibrated m/z [ppm]
uncalibrated_calibrated_mz_mda.str("NA"); // Uncalibrated - Calibrated m/z [mDa]
mass_error_ppm.str("NA"); // Mass error [ppm]
mass_error_da.str("NA"); // Mass error [Da]
uncalibrated_mass_error_ppm.str("NA"); // Uncalibrated Mass error [ppm]
uncalibrated_mass_error_da.str("NA"); // Uncalibrated Mass error [Da]
}
else if (std::isnan(calibrated_mz_error_ppm))
{
uncalibrated_calibrated_mz_ppm.str("NA"); // Uncalibrated - Calibrated m/z [ppm]
uncalibrated_calibrated_mz_mda.str("NA"); // Uncalibrated - Calibrated m/z [mDa]
mass_error_ppm.str("NA"); // Mass error [ppm]
mass_error_da.str("NA"); // Mass error [Da]
uncalibrated_mass_error_ppm.clear();
uncalibrated_mass_error_da.clear();
uncalibrated_mass_error_ppm << uncalibrated_mz_error_ppm; // Uncalibrated Mass error [ppm]
uncalibrated_mass_error_da << OpenMS::Math::ppmToMass(uncalibrated_mz_error_ppm, f.getMZ()); // Uncalibrated Mass error [Da]
}
else if (std::isnan(uncalibrated_mz_error_ppm))
{
uncalibrated_calibrated_mz_ppm.str("NA"); // Uncalibrated - Calibrated m/z [ppm]
uncalibrated_calibrated_mz_mda.str("NA"); // Uncalibrated - Calibrated m/z [mDa]
mass_error_ppm.clear();
mass_error_da.clear();
mass_error_ppm << calibrated_mz_error_ppm; // Mass error [ppm]
mass_error_da << OpenMS::Math::ppmToMass(calibrated_mz_error_ppm, f.getMZ()); // Mass error [Da]
uncalibrated_mass_error_ppm.str("NA"); // Uncalibrated Mass error [ppm]
uncalibrated_mass_error_da.str("NA"); // Uncalibrated Mass error [Da]
}
else
{
uncalibrated_calibrated_mz_ppm.clear(); // Uncalibrated - Calibrated m/z [ppm]
uncalibrated_calibrated_mz_mda.clear(); // Uncalibrated - Calibrated m/z [mDa]
mass_error_ppm.clear(); // Mass error [ppm]
mass_error_da.clear(); // Mass error [Da]
uncalibrated_mass_error_ppm.clear(); // Uncalibrated Mass error [ppm]
uncalibrated_mass_error_da.clear(); // Uncalibrated Mass error [Da]
uncalibrated_calibrated_mz_ppm << uncalibrated_mz_error_ppm - calibrated_mz_error_ppm; // Uncalibrated - Calibrated m/z [ppm]
uncalibrated_calibrated_mz_mda << OpenMS::Math::ppmToMass((uncalibrated_mz_error_ppm - calibrated_mz_error_ppm), f.getMZ()); // Uncalibrated - Calibrated m/z [Da]
mass_error_ppm << calibrated_mz_error_ppm; // Mass error [ppm]
mass_error_da << OpenMS::Math::ppmToMass(calibrated_mz_error_ppm, f.getMZ()); // Mass error [Da]
uncalibrated_mass_error_ppm << uncalibrated_mz_error_ppm; // Uncalibrated Mass error [ppm]
uncalibrated_mass_error_da << OpenMS::Math::ppmToMass(uncalibrated_mz_error_ppm, f.getMZ()); // Uncalibrated Mass error [Da]
}
base_peak_fraction.clear();
if(f.metaValueExists("spectrum_index") && f.metaValueExists("base_peak_intensity") && !exp.empty())
{
const MSSpectrum& ms2_spec = exp[f.getMetaValue("spectrum_index")];
if (!ms2_spec.getPrecursors().empty())
{
base_peak_fraction << (ms2_spec.getPrecursors()[0].getIntensity() / (double)f.getMetaValue("base_peak_intensity")); // Base peak fraction
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/InstrumentSettings.cpp | .cpp | 3,590 | 126 | // 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/METADATA/InstrumentSettings.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <algorithm>
#include <utility>
using namespace std;
namespace OpenMS
{
const std::string InstrumentSettings::NamesOfScanMode[] = {"Unknown", "MassSpectrum", "MS1Spectrum", "MSnSpectrum", "SelectedIonMonitoring", "SelectedReactionMonitoring", "ConsecutiveReactionMonitoring", "ConstantNeutralGain", "ConstantNeutralLoss", "Precursor", "EnhancedMultiplyCharged", "TimeDelayedFragmentation", "ElectromagneticRadiation", "Emission", "Absorption"};
InstrumentSettings::InstrumentSettings() :
MetaInfoInterface(),
scan_mode_(ScanMode::UNKNOWN),
zoom_scan_(false),
polarity_(IonSource::Polarity::POLNULL),
scan_windows_()
{
}
InstrumentSettings::~InstrumentSettings() = default;
bool InstrumentSettings::operator==(const InstrumentSettings & rhs) const
{
return scan_mode_ == rhs.scan_mode_ &&
zoom_scan_ == rhs.zoom_scan_ &&
polarity_ == rhs.polarity_ &&
scan_windows_ == rhs.scan_windows_ &&
MetaInfoInterface::operator==(rhs);
}
bool InstrumentSettings::operator!=(const InstrumentSettings & rhs) const
{
return !(operator==(rhs));
}
InstrumentSettings::ScanMode InstrumentSettings::getScanMode() const
{
return scan_mode_;
}
void InstrumentSettings::setScanMode(InstrumentSettings::ScanMode scan_mode)
{
scan_mode_ = scan_mode;
}
IonSource::Polarity InstrumentSettings::getPolarity() const
{
return polarity_;
}
void InstrumentSettings::setPolarity(IonSource::Polarity polarity)
{
polarity_ = polarity;
}
const std::vector<ScanWindow> & InstrumentSettings::getScanWindows() const
{
return scan_windows_;
}
std::vector<ScanWindow> & InstrumentSettings::getScanWindows()
{
return scan_windows_;
}
void InstrumentSettings::setScanWindows(std::vector<ScanWindow> scan_windows)
{
scan_windows_ = std::move(scan_windows);
}
bool InstrumentSettings::getZoomScan() const
{
return zoom_scan_;
}
void InstrumentSettings::setZoomScan(bool zoom_scan)
{
zoom_scan_ = zoom_scan;
}
StringList InstrumentSettings::getAllNamesOfScanMode()
{
StringList names;
names.reserve(static_cast<size_t>(ScanMode::SIZE_OF_SCANMODE));
for (size_t i = 0; i < static_cast<size_t>(ScanMode::SIZE_OF_SCANMODE); ++i)
{
names.push_back(NamesOfScanMode[i]);
}
return names;
}
const std::string& InstrumentSettings::scanModeToString(ScanMode mode)
{
if (mode == ScanMode::SIZE_OF_SCANMODE)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_SCANMODE");
}
return NamesOfScanMode[static_cast<size_t>(mode)];
}
InstrumentSettings::ScanMode InstrumentSettings::toScanMode(const std::string& name)
{
auto first = &NamesOfScanMode[0];
auto last = &NamesOfScanMode[static_cast<size_t>(ScanMode::SIZE_OF_SCANMODE)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<ScanMode>(it - first);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ProteinHit.cpp | .cpp | 4,849 | 201 | // 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/METADATA/ProteinHit.h>
#include <ostream>
using namespace std;
namespace OpenMS
{
const double ProteinHit::COVERAGE_UNKNOWN = -1;
// default constructor
ProteinHit::ProteinHit() :
MetaInfoInterface(),
score_(0),
rank_(0),
accession_(""),
sequence_(""),
coverage_(COVERAGE_UNKNOWN)
{
}
// values constructor
ProteinHit::ProteinHit(double score, UInt rank, String accession, String sequence) :
MetaInfoInterface(),
score_(score),
rank_(rank),
accession_(accession.trim()),
sequence_(sequence.trim()),
coverage_(COVERAGE_UNKNOWN)
{
}
// assignment operator for MetaInfoInterface
ProteinHit& ProteinHit::operator=(const MetaInfoInterface& source)
{
MetaInfoInterface::operator=(source);
return *this;
}
// equality operator
bool ProteinHit::operator==(const ProteinHit& rhs) const
{
return MetaInfoInterface::operator==(rhs)
&& score_ == rhs.score_
&& rank_ == rhs.rank_
&& accession_ == rhs.accession_
&& sequence_ == rhs.sequence_
&& coverage_ == rhs.coverage_
&& modifications_ == rhs.modifications_;
}
// inequality operator
bool ProteinHit::operator!=(const ProteinHit& rhs) const
{
return !operator==(rhs);
}
// returns the score of the protein hit
double ProteinHit::getScore() const
{
return score_;
}
// returns the rank of the protein hit
UInt ProteinHit::getRank() const
{
return rank_;
}
// returns the protein sequence
const String& ProteinHit::getSequence() const
{
return sequence_;
}
// returns the accession of the protein
const String& ProteinHit::getAccession() const
{
return accession_;
}
// returns the description of the protein
String ProteinHit::getDescription() const
{
return getMetaValue("Description").toString();
}
// returns the coverage (in percent) of the protein hit based upon matched peptides
double ProteinHit::getCoverage() const
{
return coverage_;
}
// sets the score of the protein hit
void ProteinHit::setScore(const double score)
{
score_ = score;
}
// sets the rank
void ProteinHit::setRank(UInt newrank)
{
rank_ = newrank;
}
// sets the protein sequence
void ProteinHit::setSequence(const String& sequence)
{
sequence_ = sequence;
sequence_.trim();
}
// sets the protein sequence
void ProteinHit::setSequence(String&& sequence)
{
sequence_ = std::move(sequence);
sequence_.trim();
}
// sets the description of the protein
void ProteinHit::setDescription(const String& description)
{
setMetaValue("Description", description);
}
// sets the accession of the protein
void ProteinHit::setAccession(const String& accession)
{
accession_ = accession;
accession_.trim();
}
// sets the coverage (in percent) of the protein hit based upon matched peptides
void ProteinHit::setCoverage(const double coverage)
{
coverage_ = coverage;
}
const set<pair<Size, ResidueModification>>& ProteinHit::getModifications() const
{
return modifications_;
}
void ProteinHit::setModifications(std::set<std::pair<Size, ResidueModification>>& mods)
{
modifications_ = mods;
}
bool ProteinHit::isDecoy() const
{
return getTargetDecoyType() == TargetDecoyType::DECOY;
}
void ProteinHit::setTargetDecoyType(TargetDecoyType type)
{
switch(type)
{
case TargetDecoyType::TARGET:
setMetaValue("target_decoy", "target");
break;
case TargetDecoyType::DECOY:
setMetaValue("target_decoy", "decoy");
break;
case TargetDecoyType::UNKNOWN:
removeMetaValue("target_decoy");
break;
}
}
ProteinHit::TargetDecoyType ProteinHit::getTargetDecoyType() const
{
if (!metaValueExists("target_decoy"))
{
return TargetDecoyType::UNKNOWN;
}
String td = getMetaValue("target_decoy").toString().toLower();
if (td == "decoy") return TargetDecoyType::DECOY;
if (td == "target") return TargetDecoyType::TARGET;
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown value of meta value 'target_decoy'", td);
}
std::ostream& operator<< (std::ostream& stream, const ProteinHit& hit)
{
return stream << "protein hit with accession '" + hit.getAccession() + "', score " +
String(hit.getScore());
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/SourceFile.cpp | .cpp | 3,163 | 139 | // 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/METADATA/SourceFile.h>
using namespace std;
namespace OpenMS
{
const std::string SourceFile::NamesOfChecksumType[] = {"Unknown", "SHA-1", "MD5"};
SourceFile::SourceFile() :
CVTermList(),
name_of_file_(),
path_to_file_(),
file_size_(),
file_type_(),
checksum_(),
native_id_type_(""),
native_id_type_accession_("")
{
}
SourceFile::~SourceFile() = default;
bool SourceFile::operator==(const SourceFile& rhs) const
{
return CVTermList::operator==(rhs) &&
name_of_file_ == rhs.name_of_file_ &&
path_to_file_ == rhs.path_to_file_ &&
file_size_ == rhs.file_size_ &&
file_type_ == rhs.file_type_ &&
checksum_ == rhs.checksum_ &&
checksum_type_ == rhs.checksum_type_ &&
native_id_type_ == rhs.native_id_type_ &&
native_id_type_accession_ == rhs.native_id_type_accession_;
}
bool SourceFile::operator!=(const SourceFile& rhs) const
{
return !(operator==(rhs));
}
const String& SourceFile::getNameOfFile() const
{
return name_of_file_;
}
void SourceFile::setNameOfFile(const String& name_of_file)
{
name_of_file_ = name_of_file;
}
const String& SourceFile::getPathToFile() const
{
return path_to_file_;
}
void SourceFile::setPathToFile(const String& path_to_file)
{
path_to_file_ = path_to_file;
}
float SourceFile::getFileSize() const
{
return file_size_;
}
void SourceFile::setFileSize(float file_size)
{
file_size_ = static_cast<double>(file_size);
}
const String& SourceFile::getFileType() const
{
return file_type_;
}
void SourceFile::setFileType(const String& file_type)
{
file_type_ = file_type;
}
const String& SourceFile::getChecksum() const
{
return checksum_;
}
SourceFile::ChecksumType SourceFile::getChecksumType() const
{
return checksum_type_;
}
void SourceFile::setChecksum(const String& checksum, ChecksumType type)
{
checksum_ = checksum;
checksum_type_ = type;
}
const String& SourceFile::getNativeIDType() const
{
return native_id_type_;
}
void SourceFile::setNativeIDType(const String& type)
{
native_id_type_ = type;
}
const String& SourceFile::getNativeIDTypeAccession() const
{
return native_id_type_accession_;
}
void SourceFile::setNativeIDTypeAccession(const String& accession)
{
native_id_type_accession_ = accession;
}
StringList SourceFile::getAllNamesOfChecksumType()
{
StringList names;
names.reserve(static_cast<size_t>(ChecksumType::SIZE_OF_CHECKSUMTYPE));
for (size_t i = 0; i < static_cast<size_t>(ChecksumType::SIZE_OF_CHECKSUMTYPE); ++i)
{
names.push_back(NamesOfChecksumType[i]);
}
return names;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/SpectrumLookup.cpp | .cpp | 7,518 | 255 | // 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/METADATA/SpectrumLookup.h>
#include <OpenMS/METADATA/SpectrumNativeIDParser.h>
#include <boost/regex.hpp>
using namespace std;
namespace OpenMS
{
const String& SpectrumLookup::default_scan_regexp = R"(=(?<SCAN>\d+)$)";
const String& SpectrumLookup::regexp_names_ = "INDEX0 INDEX1 SCAN ID RT";
SpectrumLookup::SpectrumLookup():
rt_tolerance(0.01), n_spectra_(0),
regexp_name_list_(ListUtils::create<String>(regexp_names_, ' '))
{}
SpectrumLookup::~SpectrumLookup() = default;
bool SpectrumLookup::empty() const
{
return n_spectra_ == 0;
}
Size SpectrumLookup::findByRT(double rt) const
{
double upper_diff = numeric_limits<double>::infinity();
map<double, Size>::const_iterator upper = rts_.upper_bound(rt);
if (upper != rts_.end())
{
upper_diff = upper->first - rt;
}
double lower_diff = numeric_limits<double>::infinity();
map<double, Size>::const_iterator lower = upper;
if (lower != rts_.begin())
{
--lower;
lower_diff = rt - lower->first;
}
if ((lower_diff < upper_diff) && (lower_diff <= rt_tolerance))
{
return lower->second;
}
if (upper_diff <= rt_tolerance)
{
return upper->second;
}
String element = "spectrum with RT " + String(rt);
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
element);
}
Size SpectrumLookup::findByNativeID(const String& native_id) const
{
map<String, Size>::const_iterator pos = ids_.find(native_id);
if (pos == ids_.end())
{
String element = "spectrum with native ID '" + native_id + "'";
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
element);
}
return pos->second;
}
Size SpectrumLookup::findByIndex(Size index, bool count_from_one) const
{
Size adjusted_index = index;
if (count_from_one)
{
--adjusted_index; // overflow (index = 0) handled below
}
if (adjusted_index >= n_spectra_)
{
String element = "spectrum with index " + String(index);
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
element);
}
return adjusted_index;
}
Size SpectrumLookup::findByScanNumber(Size scan_number) const
{
map<Size, Size>::const_iterator pos = scans_.find(scan_number);
if (pos == scans_.end())
{
String element = "spectrum with scan number " + String(scan_number);
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
element);
}
return pos->second;
}
void SpectrumLookup::addReferenceFormat(const String& regexp)
{
// does the reg. exp. contain any of the recognized group names?
bool found = false;
for (vector<String>::iterator it = regexp_name_list_.begin();
it != regexp_name_list_.end(); ++it)
{
if (regexp.hasSubstring("?<" + (*it) + ">"))
{
found = true;
break;
}
}
if (!found)
{
String msg = "The regular expression describing the reference format must contain at least one of the following named groups (in the format '?<GROUP>'): " + regexp_names_;
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
msg);
}
boost::regex re(regexp);
reference_formats.push_back(re);
}
Size SpectrumLookup::findByRegExpMatch_(const String& spectrum_ref,
const String& regexp,
const boost::smatch& match) const
{
if (match["INDEX0"].matched)
{
String value = match["INDEX0"].str();
if (!value.empty())
{
Size index = value.toInt();
return findByIndex(index, false);
}
}
if (match["INDEX1"].matched)
{
String value = match["INDEX1"].str();
if (!value.empty())
{
Size index = value.toInt();
return findByIndex(index, true);
}
}
if (match["SCAN"].matched)
{
String value = match["SCAN"].str();
if (!value.empty())
{
Size scan_number = value.toInt();
return findByScanNumber(scan_number);
}
}
if (match["ID"].matched)
{
String value = match["ID"].str();
if (!value.empty())
{
return findByNativeID(value);
}
}
if (match["RT"].matched)
{
String value = match["RT"].str();
if (!value.empty())
{
double rt = value.toDouble();
return findByRT(rt);
}
}
String msg = "Unexpected format of spectrum reference '" + spectrum_ref +
"'. The regular expression '" + regexp + "' matched, but no usable "
"information could be extracted.";
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
msg);
}
Size SpectrumLookup::findByReference(const String& spectrum_ref) const
{
for (const boost::regex& reg : reference_formats)
{
boost::smatch match;
bool found = boost::regex_search(spectrum_ref, match, reg);
if (found)
{
return findByRegExpMatch_(spectrum_ref, reg.str(), match);
}
}
String msg = "Spectrum reference doesn't match any known format";
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
spectrum_ref, msg);
}
bool SpectrumLookup::isNativeID(const String& id)
{
return SpectrumNativeIDParser::isNativeID(id);
}
std::string SpectrumLookup::getRegExFromNativeID(const String& id)
{
return SpectrumNativeIDParser::getRegExFromNativeID(id);
}
Int SpectrumLookup::extractScanNumber(const String& native_id,
const boost::regex& scan_regexp,
bool no_error)
{
return SpectrumNativeIDParser::extractScanNumber(native_id, scan_regexp, no_error);
}
Int SpectrumLookup::extractScanNumber(const String& native_id,
const String& native_id_type_accession)
{
return SpectrumNativeIDParser::extractScanNumber(native_id, native_id_type_accession);
}
void SpectrumLookup::addEntry_(Size index, double rt, Int scan_number,
const String& native_id)
{
rts_[rt] = index;
ids_[native_id] = index;
if (scan_number != -1)
{
scans_[scan_number] = index;
}
}
void SpectrumLookup::setScanRegExp_(const String& scan_regexp)
{
if (!scan_regexp.empty())
{
if (!scan_regexp.hasSubstring("?<SCAN>"))
{
String msg = "The regular expression for extracting scan numbers from native IDs must contain a named group '?<SCAN>'.";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
scan_regexp_.assign(scan_regexp);
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/AcquisitionInfo.cpp | .cpp | 1,040 | 40 | // 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/METADATA/AcquisitionInfo.h>
using namespace std;
namespace OpenMS
{
bool AcquisitionInfo::operator==(const AcquisitionInfo & rhs) const
{
return method_of_combination_ == rhs.method_of_combination_ &&
MetaInfoInterface::operator==(rhs) &&
std::operator==(*this, rhs);
}
bool AcquisitionInfo::operator!=(const AcquisitionInfo & rhs) const
{
return !(operator==(rhs));
}
const String & AcquisitionInfo::getMethodOfCombination() const
{
return method_of_combination_;
}
void AcquisitionInfo::setMethodOfCombination(const String & method_of_combination)
{
method_of_combination_ = method_of_combination;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/SpectrumNativeIDParser.cpp | .cpp | 7,722 | 201 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Hendrik Weisser, Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/METADATA/SpectrumNativeIDParser.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <algorithm>
#include <vector>
using namespace std;
namespace OpenMS
{
bool SpectrumNativeIDParser::isNativeID(const String& id)
{
return id.hasPrefix("scan=") || id.hasPrefix("scanId=") || id.hasPrefix("scanID=")
|| id.hasPrefix("controllerType=") || id.hasPrefix("function=") || id.hasPrefix("sample=")
|| id.hasPrefix("index=") || id.hasPrefix("spectrum=") || id.hasPrefix("file=");
}
std::string SpectrumNativeIDParser::getRegExFromNativeID(const String& id)
{
// "scan=NUMBER" e.g. Bruker/Agilent
// "controllerType=0 controllerNumber=1 scan=NUMBER" for Thermo
// "function= process= scan=NUMBER" for Waters
if (id.hasPrefix("scan=")
|| id.hasPrefix("controllerType=")
|| id.hasPrefix("function=")) return std::string(R"(scan=(?<GROUP>\d+))");
// "index=NUMBER"
if (id.hasPrefix("index=")) return std::string(R"(index=(?<GROUP>\d+))");
// "scanId=NUMBER" or "scanID=NUMBER" - MS_Agilent_MassHunter_nativeID_format
if (id.hasPrefix("scanId=")) return std::string(R"(scanId=(?<GROUP>\d+))");
if (id.hasPrefix("scanID=")) return std::string(R"(scanID=(?<GROUP>\d+))");
// "spectrum=NUMBER"
if (id.hasPrefix("spectrum=")) return std::string(R"(spectrum=(?<GROUP>\d+))");
// "file=NUMBER" Bruker FID or single peak list
if (id.hasPrefix("file=")) return std::string(R"(file=(?<GROUP>\d+))");
// NUMBER
return std::string(R"((?<GROUP>\d+))");
}
Int SpectrumNativeIDParser::extractScanNumber(const String& native_id,
const boost::regex& scan_regexp,
bool no_error)
{
vector<string> matches;
boost::sregex_token_iterator current_begin(native_id.begin(), native_id.end(), scan_regexp, 1);
boost::sregex_token_iterator current_end(native_id.end(), native_id.end(), scan_regexp, 1);
matches.insert(matches.end(), current_begin, current_end);
if (!matches.empty())
{
// always use the last possible matching subgroup
String last_value = String(matches.back());
try
{
return last_value.toInt();
}
catch (Exception::ConversionError&)
{
}
}
if (!no_error)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
native_id, "Could not extract scan number");
}
return -1;
}
Int SpectrumNativeIDParser::extractScanNumber(const String& native_id,
const String& native_id_type_accession)
{
// check accession for data type to extract (e.g. MS:1000768 - Thermo nativeID format - scan=xsd:positiveInteger)
boost::regex regexp;
// list of CV accessions with native id format "scan=NUMBER"
std::vector<String> scan = {"MS:1000768","MS:1000769","MS:1000771","MS:1000772","MS:1000776"};
// list of CV accession with native id format "file=NUMBER"
std::vector<String> file = {"MS:1000773","MS:1000775"};
// expected number of subgroups
vector<int> subgroups = {1};
// "scan=NUMBER"
if (std::find(scan.begin(), scan.end(), native_id_type_accession) != scan.end())
{
regexp = std::string(R"(scan=(?<GROUP>\d+))");
}
// id="sample=1 period=1 cycle=96 experiment=1" - this will be described by a combination of (cycle * 1000 + experiment)
else if (native_id_type_accession == "MS:1000770") // WIFF nativeID format
{
regexp = std::string(R"(cycle=(?<GROUP>\d+)\s+experiment=(?<GROUP>\d+))");
subgroups = {1, 2};
}
// "file=NUMBER"
else if (std::find(file.begin(), file.end(), native_id_type_accession) != file.end())
{
regexp = std::string(R"(file=(?<GROUP>\d+))");
}
// "index=NUMBER"
else if (native_id_type_accession == "MS:1000774")
{
regexp = std::string(R"(index=(?<GROUP>\d+))");
}
// "scanId=NUMBER" - MS_Agilent_MassHunter_nativeID_format
else if (native_id_type_accession == "MS:1001508")
{
regexp = std::string(R"(scanId=(?<GROUP>\d+))");
}
// "spectrum=NUMBER"
else if (native_id_type_accession == "MS:1000777")
{
regexp = std::string(R"(spectrum=(?<GROUP>\d+))");
}
// NUMBER
else if (native_id_type_accession == "MS:1001530")
{
regexp = std::string(R"((?<GROUP>\d+))");
}
else
{
OPENMS_LOG_WARN << "native_id: " << native_id << " accession: " << native_id_type_accession << " Could not extract scan number - no valid native_id_type_accession was provided" << std::endl;
}
if (!regexp.empty())
{
vector<string> matches;
boost::sregex_token_iterator current_begin(native_id.begin(), native_id.end(), regexp, subgroups);
boost::sregex_token_iterator current_end(native_id.end(), native_id.end(), regexp, subgroups);
matches.insert(matches.end(), current_begin, current_end);
if (matches.size() < subgroups.size()) {
OPENMS_LOG_WARN << "native_id '" << native_id <<"' is invalid. Could not extract scan number." << std::endl;
return -1;
}
if (subgroups.size() == 1) // default case: one native identifier
{
try
{
// In case of merged spectra the last native id matches the scan number of the merged scan.
String value = String(matches[matches.size() - 1]);
if (native_id_type_accession == "MS:1000774")
{
return value.toInt() + 1; // if the native ID is index=.., the scan number is usually considered index+1 (especially for pepXML)
}
else
{
return value.toInt();
}
}
catch (Exception::ConversionError&)
{
OPENMS_LOG_WARN << "Value: '" << String(matches[matches.size() - 1]) << "' could not be converted to int in string. Native ID='" << native_id << "'" << std::endl;
return -1;
}
}
else if (subgroups.size() == 2) // special case: wiff file with two native identifiers
{
try
{
// In case of merged spectra the last native id matches the scan number of the merged scan.
String cycle_str = matches[matches.size() - 2];
String experiment_str = matches[matches.size() - 1];
if (experiment_str.toInt() < 1000) // checks if value of experiment is smaller than 1000 (cycle * 1000 + experiment)
{
int value = cycle_str.toInt() * 1000 + experiment_str.toInt();
return value;
}
else
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The value of experiment is too large and can not be handled properly.", experiment_str);
}
}
catch (Exception::ConversionError&)
{
OPENMS_LOG_WARN << "Values: '" << matches[matches.size() - 2] << "', '" << matches[matches.size() - 1] << "' could not be converted to int in string. Native ID='"
<< native_id << "' accession='" << native_id_type_accession << "'" << std::endl;
return -1;
}
}
else
{
return -1;
}
}
return -1;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/Instrument.cpp | .cpp | 3,918 | 169 | // 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/METADATA/Instrument.h>
using namespace std;
namespace OpenMS
{
const std::string Instrument::NamesOfIonOpticsType[] = {"Unknown", "magnetic deflection", "delayed extraction", "collision quadrupole", "selected ion flow tube", "time lag focusing", "reflectron", "einzel lens", "first stability region", "fringing field", "kinetic energy analyzer", "static field"};
Instrument::Instrument() :
MetaInfoInterface(),
ion_optics_(IonOpticsType::UNKNOWN)
{
}
Instrument::~Instrument() = default;
bool Instrument::operator==(const Instrument & rhs) const
{
return software_ == rhs.software_ &&
name_ == rhs.name_ &&
vendor_ == rhs.vendor_ &&
model_ == rhs.model_ &&
customizations_ == rhs.customizations_ &&
ion_sources_ == rhs.ion_sources_ &&
mass_analyzers_ == rhs.mass_analyzers_ &&
ion_detectors_ == rhs.ion_detectors_ &&
ion_optics_ == rhs.ion_optics_ &&
MetaInfoInterface::operator==(rhs);
}
bool Instrument::operator!=(const Instrument & rhs) const
{
return !(operator==(rhs));
}
const String & Instrument::getName() const
{
return name_;
}
void Instrument::setName(const String & name)
{
name_ = name;
}
const String & Instrument::getVendor() const
{
return vendor_;
}
void Instrument::setVendor(const String & vendor)
{
vendor_ = vendor;
}
const String & Instrument::getModel() const
{
return model_;
}
void Instrument::setModel(const String & model)
{
model_ = model;
}
const String & Instrument::getCustomizations() const
{
return customizations_;
}
void Instrument::setCustomizations(const String & customizations)
{
customizations_ = customizations;
}
const std::vector<IonSource> & Instrument::getIonSources() const
{
return ion_sources_;
}
std::vector<IonSource> & Instrument::getIonSources()
{
return ion_sources_;
}
void Instrument::setIonSources(const std::vector<IonSource> & ion_sources)
{
ion_sources_ = ion_sources;
}
const std::vector<MassAnalyzer> & Instrument::getMassAnalyzers() const
{
return mass_analyzers_;
}
std::vector<MassAnalyzer> & Instrument::getMassAnalyzers()
{
return mass_analyzers_;
}
void Instrument::setMassAnalyzers(const std::vector<MassAnalyzer> & mass_analyzers)
{
mass_analyzers_ = mass_analyzers;
}
const std::vector<IonDetector> & Instrument::getIonDetectors() const
{
return ion_detectors_;
}
std::vector<IonDetector> & Instrument::getIonDetectors()
{
return ion_detectors_;
}
void Instrument::setIonDetectors(const std::vector<IonDetector> & ion_detectors)
{
ion_detectors_ = ion_detectors;
}
const Software & Instrument::getSoftware() const
{
return software_;
}
Software & Instrument::getSoftware()
{
return software_;
}
void Instrument::setSoftware(const Software & software)
{
software_ = software;
}
Instrument::IonOpticsType Instrument::getIonOptics() const
{
return ion_optics_;
}
void Instrument::setIonOptics(Instrument::IonOpticsType ion_optics)
{
ion_optics_ = ion_optics;
}
StringList Instrument::getAllNamesOfIonOpticsType()
{
StringList names;
names.reserve(static_cast<size_t>(IonOpticsType::SIZE_OF_IONOPTICSTYPE));
for (size_t i = 0; i < static_cast<size_t>(IonOpticsType::SIZE_OF_IONOPTICSTYPE); ++i)
{
names.push_back(NamesOfIonOpticsType[i]);
}
return names;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/MassAnalyzer.cpp | .cpp | 12,939 | 423 | // 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/METADATA/MassAnalyzer.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <algorithm>
using namespace std;
namespace OpenMS
{
const std::string MassAnalyzer::NamesOfAnalyzerType[] = {"Unknown", "Quadrupole", "Quadrupole ion trap", "Radial ejection linear ion trap", "Axial ejection linear ion trap", "Time-of-flight", "Magnetic sector", "Fourier transform ion cyclotron resonance mass spectrometer", "Ion storage", "Electrostatic energy analyzer", "Ion trap", "Stored waveform inverse fourier transform", "Cyclotron", "Orbitrap", "Linear ion trap"};
const std::string MassAnalyzer::NamesOfResolutionMethod[] = {"Unknown", "Full width at half max", "Ten percent valley", "Baseline"};
const std::string MassAnalyzer::NamesOfResolutionType[] = {"Unknown", "Constant", "Proportional"};
const std::string MassAnalyzer::NamesOfScanDirection[] = {"Unknown", "Up", "Down"};
const std::string MassAnalyzer::NamesOfScanLaw[] = {"Unknown", "Exponential", "Linar", "Quadratic"};
const std::string MassAnalyzer::NamesOfReflectronState[] = {"Unknown", "On", "Off", "None"};
MassAnalyzer::MassAnalyzer() :
MetaInfoInterface(),
type_(AnalyzerType::ANALYZERNULL),
resolution_method_(ResolutionMethod::RESMETHNULL),
resolution_type_(ResolutionType::RESTYPENULL),
scan_direction_(ScanDirection::SCANDIRNULL),
scan_law_(ScanLaw::SCANLAWNULL),
reflectron_state_(ReflectronState::REFLSTATENULL),
resolution_(0.0),
accuracy_(0.0),
scan_rate_(0.0),
scan_time_(0.0),
TOF_total_path_length_(0.0),
isolation_width_(0.0),
final_MS_exponent_(0),
magnetic_field_strength_(0.0),
order_(0)
{
}
MassAnalyzer::~MassAnalyzer() = default;
bool MassAnalyzer::operator==(const MassAnalyzer & rhs) const
{
return order_ == rhs.order_ &&
type_ == rhs.type_ &&
resolution_method_ == rhs.resolution_method_ &&
resolution_type_ == rhs.resolution_type_ &&
scan_direction_ == rhs.scan_direction_ &&
scan_law_ == rhs.scan_law_ &&
reflectron_state_ == rhs.reflectron_state_ &&
resolution_ == rhs.resolution_ &&
accuracy_ == rhs.accuracy_ &&
scan_rate_ == rhs.scan_rate_ &&
scan_time_ == rhs.scan_time_ &&
TOF_total_path_length_ == rhs.TOF_total_path_length_ &&
isolation_width_ == rhs.isolation_width_ &&
final_MS_exponent_ == rhs.final_MS_exponent_ &&
magnetic_field_strength_ == rhs.magnetic_field_strength_ &&
MetaInfoInterface::operator==(rhs);
}
bool MassAnalyzer::operator!=(const MassAnalyzer & rhs) const
{
return !(operator==(rhs));
}
MassAnalyzer::AnalyzerType MassAnalyzer::getType() const
{
return type_;
}
void MassAnalyzer::setType(MassAnalyzer::AnalyzerType type)
{
type_ = type;
}
MassAnalyzer::ResolutionMethod MassAnalyzer::getResolutionMethod() const
{
return resolution_method_;
}
void MassAnalyzer::setResolutionMethod(MassAnalyzer::ResolutionMethod resolution_method)
{
resolution_method_ = resolution_method;
}
MassAnalyzer::ResolutionType MassAnalyzer::getResolutionType() const
{
return resolution_type_;
}
void MassAnalyzer::setResolutionType(MassAnalyzer::ResolutionType resolution_type)
{
resolution_type_ = resolution_type;
}
MassAnalyzer::ScanDirection MassAnalyzer::getScanDirection() const
{
return scan_direction_;
}
void MassAnalyzer::setScanDirection(MassAnalyzer::ScanDirection scan_direction)
{
scan_direction_ = scan_direction;
}
MassAnalyzer::ScanLaw MassAnalyzer::getScanLaw() const
{
return scan_law_;
}
void MassAnalyzer::setScanLaw(MassAnalyzer::ScanLaw scan_law)
{
scan_law_ = scan_law;
}
MassAnalyzer::ReflectronState MassAnalyzer::getReflectronState() const
{
return reflectron_state_;
}
void MassAnalyzer::setReflectronState(MassAnalyzer::ReflectronState reflectron_state)
{
reflectron_state_ = reflectron_state;
}
double MassAnalyzer::getResolution() const
{
return resolution_;
}
void MassAnalyzer::setResolution(double resolution)
{
resolution_ = resolution;
}
double MassAnalyzer::getAccuracy() const
{
return accuracy_;
}
void MassAnalyzer::setAccuracy(double accuracy)
{
accuracy_ = accuracy;
}
double MassAnalyzer::getScanRate() const
{
return scan_rate_;
}
void MassAnalyzer::setScanRate(double scan_rate)
{
scan_rate_ = scan_rate;
}
double MassAnalyzer::getScanTime() const
{
return scan_time_;
}
void MassAnalyzer::setScanTime(double scan_time)
{
scan_time_ = scan_time;
}
double MassAnalyzer::getTOFTotalPathLength() const
{
return TOF_total_path_length_;
}
void MassAnalyzer::setTOFTotalPathLength(double TOF_total_path_length)
{
TOF_total_path_length_ = TOF_total_path_length;
}
double MassAnalyzer::getIsolationWidth() const
{
return isolation_width_;
}
void MassAnalyzer::setIsolationWidth(double isolation_width)
{
isolation_width_ = isolation_width;
}
Int MassAnalyzer::getFinalMSExponent() const
{
return final_MS_exponent_;
}
void MassAnalyzer::setFinalMSExponent(Int final_MS_exponent)
{
final_MS_exponent_ = final_MS_exponent;
}
double MassAnalyzer::getMagneticFieldStrength() const
{
return magnetic_field_strength_;
}
void MassAnalyzer::setMagneticFieldStrength(double magnetic_field_strength)
{
magnetic_field_strength_ = magnetic_field_strength;
}
Int MassAnalyzer::getOrder() const
{
return order_;
}
void MassAnalyzer::setOrder(Int order)
{
order_ = order;
}
StringList MassAnalyzer::getAllNamesOfAnalyzerType()
{
StringList names;
names.reserve(static_cast<size_t>(AnalyzerType::SIZE_OF_ANALYZERTYPE));
for (size_t i = 0; i < static_cast<size_t>(AnalyzerType::SIZE_OF_ANALYZERTYPE); ++i)
{
names.push_back(NamesOfAnalyzerType[i]);
}
return names;
}
StringList MassAnalyzer::getAllNamesOfResolutionMethod()
{
StringList names;
names.reserve(static_cast<size_t>(ResolutionMethod::SIZE_OF_RESOLUTIONMETHOD));
for (size_t i = 0; i < static_cast<size_t>(ResolutionMethod::SIZE_OF_RESOLUTIONMETHOD); ++i)
{
names.push_back(NamesOfResolutionMethod[i]);
}
return names;
}
StringList MassAnalyzer::getAllNamesOfResolutionType()
{
StringList names;
names.reserve(static_cast<size_t>(ResolutionType::SIZE_OF_RESOLUTIONTYPE));
for (size_t i = 0; i < static_cast<size_t>(ResolutionType::SIZE_OF_RESOLUTIONTYPE); ++i)
{
names.push_back(NamesOfResolutionType[i]);
}
return names;
}
StringList MassAnalyzer::getAllNamesOfScanDirection()
{
StringList names;
names.reserve(static_cast<size_t>(ScanDirection::SIZE_OF_SCANDIRECTION));
for (size_t i = 0; i < static_cast<size_t>(ScanDirection::SIZE_OF_SCANDIRECTION); ++i)
{
names.push_back(NamesOfScanDirection[i]);
}
return names;
}
StringList MassAnalyzer::getAllNamesOfScanLaw()
{
StringList names;
names.reserve(static_cast<size_t>(ScanLaw::SIZE_OF_SCANLAW));
for (size_t i = 0; i < static_cast<size_t>(ScanLaw::SIZE_OF_SCANLAW); ++i)
{
names.push_back(NamesOfScanLaw[i]);
}
return names;
}
StringList MassAnalyzer::getAllNamesOfReflectronState()
{
StringList names;
names.reserve(static_cast<size_t>(ReflectronState::SIZE_OF_REFLECTRONSTATE));
for (size_t i = 0; i < static_cast<size_t>(ReflectronState::SIZE_OF_REFLECTRONSTATE); ++i)
{
names.push_back(NamesOfReflectronState[i]);
}
return names;
}
const std::string& MassAnalyzer::analyzerTypeToString(AnalyzerType type)
{
if (type == AnalyzerType::SIZE_OF_ANALYZERTYPE)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_ANALYZERTYPE");
}
return NamesOfAnalyzerType[static_cast<size_t>(type)];
}
MassAnalyzer::AnalyzerType MassAnalyzer::toAnalyzerType(const std::string& name)
{
auto first = &NamesOfAnalyzerType[0];
auto last = &NamesOfAnalyzerType[static_cast<size_t>(AnalyzerType::SIZE_OF_ANALYZERTYPE)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<AnalyzerType>(it - first);
}
const std::string& MassAnalyzer::resolutionMethodToString(ResolutionMethod method)
{
if (method == ResolutionMethod::SIZE_OF_RESOLUTIONMETHOD)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_RESOLUTIONMETHOD");
}
return NamesOfResolutionMethod[static_cast<size_t>(method)];
}
MassAnalyzer::ResolutionMethod MassAnalyzer::toResolutionMethod(const std::string& name)
{
auto first = &NamesOfResolutionMethod[0];
auto last = &NamesOfResolutionMethod[static_cast<size_t>(ResolutionMethod::SIZE_OF_RESOLUTIONMETHOD)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<ResolutionMethod>(it - first);
}
const std::string& MassAnalyzer::resolutionTypeToString(ResolutionType type)
{
if (type == ResolutionType::SIZE_OF_RESOLUTIONTYPE)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_RESOLUTIONTYPE");
}
return NamesOfResolutionType[static_cast<size_t>(type)];
}
MassAnalyzer::ResolutionType MassAnalyzer::toResolutionType(const std::string& name)
{
auto first = &NamesOfResolutionType[0];
auto last = &NamesOfResolutionType[static_cast<size_t>(ResolutionType::SIZE_OF_RESOLUTIONTYPE)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<ResolutionType>(it - first);
}
const std::string& MassAnalyzer::scanDirectionToString(ScanDirection direction)
{
if (direction == ScanDirection::SIZE_OF_SCANDIRECTION)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_SCANDIRECTION");
}
return NamesOfScanDirection[static_cast<size_t>(direction)];
}
MassAnalyzer::ScanDirection MassAnalyzer::toScanDirection(const std::string& name)
{
auto first = &NamesOfScanDirection[0];
auto last = &NamesOfScanDirection[static_cast<size_t>(ScanDirection::SIZE_OF_SCANDIRECTION)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<ScanDirection>(it - first);
}
const std::string& MassAnalyzer::scanLawToString(ScanLaw law)
{
if (law == ScanLaw::SIZE_OF_SCANLAW)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_SCANLAW");
}
return NamesOfScanLaw[static_cast<size_t>(law)];
}
MassAnalyzer::ScanLaw MassAnalyzer::toScanLaw(const std::string& name)
{
auto first = &NamesOfScanLaw[0];
auto last = &NamesOfScanLaw[static_cast<size_t>(ScanLaw::SIZE_OF_SCANLAW)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<ScanLaw>(it - first);
}
const std::string& MassAnalyzer::reflectronStateToString(ReflectronState state)
{
if (state == ReflectronState::SIZE_OF_REFLECTRONSTATE)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_REFLECTRONSTATE");
}
return NamesOfReflectronState[static_cast<size_t>(state)];
}
MassAnalyzer::ReflectronState MassAnalyzer::toReflectronState(const std::string& name)
{
auto first = &NamesOfReflectronState[0];
auto last = &NamesOfReflectronState[static_cast<size_t>(ReflectronState::SIZE_OF_REFLECTRONSTATE)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<ReflectronState>(it - first);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/CVTerm.cpp | .cpp | 2,067 | 103 | // 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/METADATA/CVTerm.h>
using namespace std;
namespace OpenMS
{
CVTerm::CVTerm(const String& accession, const String& name, const String& cv_identifier_ref, const String& value, const Unit& unit) :
accession_(accession),
name_(name),
cv_identifier_ref_(cv_identifier_ref),
unit_(unit),
value_(value)
{
}
CVTerm::~CVTerm() = default;
bool CVTerm::operator==(const CVTerm & rhs) const
{
return accession_ == rhs.accession_ &&
name_ == rhs.name_ &&
cv_identifier_ref_ == rhs.cv_identifier_ref_ &&
unit_ == rhs.unit_ &&
value_ == rhs.value_;
}
bool CVTerm::operator!=(const CVTerm& rhs) const
{
return !(*this == rhs);
}
void CVTerm::setAccession(const String& accession)
{
accession_ = accession;
}
const String& CVTerm::getAccession() const
{
return accession_;
}
void CVTerm::setName(const String& name)
{
name_ = name;
}
const String& CVTerm::getName() const
{
return name_;
}
void CVTerm::setCVIdentifierRef(const String& cv_identifier_ref)
{
cv_identifier_ref_ = cv_identifier_ref;
}
const String& CVTerm::getCVIdentifierRef() const
{
return cv_identifier_ref_;
}
void CVTerm::setUnit(const Unit& unit)
{
unit_ = unit;
}
const CVTerm::Unit& CVTerm::getUnit() const
{
return unit_;
}
void CVTerm::setValue(const DataValue& value)
{
value_ = value;
}
const DataValue& CVTerm::getValue() const
{
return value_;
}
bool CVTerm::hasUnit() const
{
return !unit_.accession.empty();
}
bool CVTerm::hasValue() const
{
return value_ != DataValue::EMPTY;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/MetaInfoDescription.cpp | .cpp | 4,040 | 138 | // 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/METADATA/MetaInfoDescription.h>
#include <OpenMS/CONCEPT/Helpers.h>
using namespace std;
namespace OpenMS
{
MetaInfoDescription::~MetaInfoDescription() = default;
bool MetaInfoDescription::operator==(const MetaInfoDescription & rhs) const
{
return MetaInfoInterface::operator==(rhs) &&
name_ == rhs.name_ &&
( data_processing_.size() == rhs.data_processing_.size() &&
std::equal(data_processing_.begin(),
data_processing_.end(),
rhs.data_processing_.begin(),
OpenMS::Helpers::cmpPtrSafe<DataProcessingPtr>) );
}
bool MetaInfoDescription::operator<(const MetaInfoDescription & rhs) const
{
// Compare data processing by size first (fast)
if (data_processing_.size() != rhs.data_processing_.size())
return data_processing_.size() < rhs.data_processing_.size();
// First compare the MetaInfoInterface base
if (MetaInfoInterface::operator!=(rhs))
{
// For MetaInfoInterface comparison, we need to create a deterministic ordering
// Compare by checking if one is empty and the other is not
bool lhs_empty = isMetaEmpty();
bool rhs_empty = rhs.isMetaEmpty();
if (lhs_empty != rhs_empty)
{
return lhs_empty < rhs_empty;
}
// Compare name
if (name_ != rhs.name_)
return name_ < rhs.name_;
// If both non-empty, compare by getting keys and comparing them
std::vector<UInt> lhs_keys, rhs_keys;
getKeys(lhs_keys);
rhs.getKeys(rhs_keys);
if (lhs_keys != rhs_keys)
return lhs_keys < rhs_keys;
// If keys are same, compare values for each key
for (UInt key : lhs_keys)
{
String lhs_val = getMetaValue(key).toString();
String rhs_val = rhs.getMetaValue(key).toString();
if (lhs_val != rhs_val)
return lhs_val < rhs_val;
}
}
// Compare data processing elements (simplified comparison by comparing names)
for (size_t i = 0; i < data_processing_.size(); ++i)
{
if (data_processing_[i] && rhs.data_processing_[i])
{
size_t lhs_size = data_processing_[i]->getProcessingActions().size();
size_t rhs_size = rhs.data_processing_[i]->getProcessingActions().size();
if (lhs_size != rhs_size)
return lhs_size < rhs_size;
}
else if (data_processing_[i] != rhs.data_processing_[i])
{
return (data_processing_[i] == nullptr) < (rhs.data_processing_[i] == nullptr);
}
}
return false; // Equal
}
bool MetaInfoDescription::operator<=(const MetaInfoDescription & rhs) const
{
return *this < rhs || *this == rhs;
}
bool MetaInfoDescription::operator>(const MetaInfoDescription & rhs) const
{
return !(*this <= rhs);
}
bool MetaInfoDescription::operator>=(const MetaInfoDescription & rhs) const
{
return !(*this < rhs);
}
bool MetaInfoDescription::operator!=(const MetaInfoDescription & rhs) const
{
return !(*this == rhs);
}
void MetaInfoDescription::setName(const String & name)
{
name_ = name;
}
const String & MetaInfoDescription::getName() const
{
return name_;
}
const vector<ConstDataProcessingPtr> & MetaInfoDescription::getDataProcessing() const
{
return OpenMS::Helpers::constifyPointerVector(data_processing_);
}
vector<DataProcessingPtr> & MetaInfoDescription::getDataProcessing()
{
return data_processing_;
}
void MetaInfoDescription::setDataProcessing(const vector<DataProcessingPtr> & processing_method)
{
data_processing_ = processing_method;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/DocumentIdentifier.cpp | .cpp | 1,918 | 81 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/METADATA/DocumentIdentifier.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <QtCore/QDir>
namespace OpenMS
{
DocumentIdentifier::DocumentIdentifier() :
id_(),
file_path_(),
file_type_(FileTypes::UNKNOWN)
{
}
DocumentIdentifier::~DocumentIdentifier() = default;
void DocumentIdentifier::setIdentifier(const String & id)
{
id_ = id;
}
const String & DocumentIdentifier::getIdentifier() const
{
return id_;
}
void DocumentIdentifier::setLoadedFilePath(const String & file_name)
{
// only change the path if we need to, otherwise low and upper case might be altered by Qt, making comparison in tests more tricky
// i.e., a call to this will report unmatched strings
if (QDir::isRelativePath(file_name.toQString()))
{
file_path_ = File::absolutePath(file_name);
}
else
{
file_path_ = file_name;
}
}
const String & DocumentIdentifier::getLoadedFilePath() const
{
return file_path_;
}
void DocumentIdentifier::setLoadedFileType(const String & file_name)
{
file_type_ = FileHandler::getTypeByContent(file_name);
}
const FileTypes::Type & DocumentIdentifier::getLoadedFileType() const
{
return file_type_;
}
void DocumentIdentifier::swap(DocumentIdentifier & from)
{
std::swap(id_, from.id_);
std::swap(file_path_, from.file_path_);
std::swap(file_type_, from.file_type_);
}
bool DocumentIdentifier::operator==(const DocumentIdentifier & rhs) const
{
return id_ == rhs.id_;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/Software.cpp | .cpp | 1,298 | 63 | // 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/METADATA/Software.h>
using namespace std;
namespace OpenMS
{
Software::Software(const String& name, const String& version) :
CVTermList(),
name_(name),
version_(version)
{
}
Software::~Software() = default;
bool Software::operator==(const Software& rhs) const
{
return CVTermList::operator==(rhs) &&
name_ == rhs.name_ &&
version_ == rhs.version_;
}
bool Software::operator!=(const Software& rhs) const
{
return !(operator==(rhs));
}
bool Software::operator<(const Software& rhs) const
{
return tie(name_, version_) < tie(rhs.name_, rhs.version_);
}
const String& Software::getName() const
{
return name_;
}
void Software::setName(const String& name)
{
name_ = name;
}
const String& Software::getVersion() const
{
return version_;
}
void Software::setVersion(const String& version)
{
version_ = version;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/CVTermList.cpp | .cpp | 2,359 | 93 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Andreas Bertsch, Mathias Walzer $
// --------------------------------------------------------------------------
#include <OpenMS/METADATA/CVTermList.h>
#include <OpenMS/FORMAT/ControlledVocabulary.h>
using namespace std;
namespace OpenMS
{
CVTermList::~CVTermList() = default;
CVTermList::CVTermList(CVTermList&& rhs) noexcept :
MetaInfoInterface(std::move(rhs)),
cv_terms_(std::move(rhs.cv_terms_))
{
}
void CVTermList::addCVTerm(const CVTerm& cv_term)
{
// TODO exception if empty
cv_terms_[cv_term.getAccession()].push_back(cv_term);
}
void CVTermList::setCVTerms(const vector<CVTerm>& cv_terms)
{
for (const CVTerm& tr : cv_terms)
{
addCVTerm(tr);
}
return;
}
void CVTermList::replaceCVTerm(const CVTerm& cv_term)
{
std::vector<CVTerm> tmp;
tmp.push_back(cv_term);
cv_terms_[cv_term.getAccession()] = tmp;
}
void CVTermList::replaceCVTerms(const vector<CVTerm>& cv_terms, const String& accession)
{
cv_terms_[accession] = cv_terms;
}
void CVTermList::replaceCVTerms(const std::map<String, vector<CVTerm> >& cv_term_map)
{
cv_terms_ = cv_term_map;
}
void CVTermList::consumeCVTerms(const std::map<String, vector<CVTerm> >& cv_term_map)
{
for (std::map<String, std::vector<CVTerm> >::const_iterator it = cv_term_map.begin(); it != cv_term_map.end(); ++it)
{
cv_terms_[it->first].insert(cv_terms_[it->first].end(), it->second.begin(), it->second.end());
}
}
const std::map<String, vector<CVTerm> >& CVTermList::getCVTerms() const
{
return cv_terms_;
}
bool CVTermList::hasCVTerm(const String& accession) const
{
return cv_terms_.find(accession) != cv_terms_.end();
}
bool CVTermList::operator==(const CVTermList& cv_term_list) const
{
return MetaInfoInterface::operator==(cv_term_list) && cv_terms_ == cv_term_list.cv_terms_;
}
bool CVTermList::operator!=(const CVTermList& cv_term_list) const
{
return !(*this == cv_term_list);
}
bool CVTermList::empty() const
{
return cv_terms_.empty();
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/DataArrays.cpp | .cpp | 417 | 15 | // 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/METADATA/DataArrays.h>
namespace OpenMS
{
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/HPLC.cpp | .cpp | 2,185 | 124 | // 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/METADATA/HPLC.h>
#include <utility>
using namespace std;
namespace OpenMS
{
HPLC::HPLC() :
instrument_(),
column_(),
temperature_(21),
pressure_(0),
flux_(0),
comment_(),
gradient_()
{
}
HPLC::~HPLC() = default;
bool HPLC::operator==(const HPLC & rhs) const
{
return (instrument_ == rhs.instrument_) &&
(column_ == rhs.column_) &&
(temperature_ == rhs.temperature_) &&
(pressure_ == rhs.pressure_) &&
(flux_ == rhs.flux_) &&
(comment_ == rhs.comment_) &&
(gradient_ == rhs.gradient_);
}
bool HPLC::operator!=(const HPLC & rhs) const
{
return !(operator==(rhs));
}
const String & HPLC::getInstrument() const
{
return instrument_;
}
void HPLC::setInstrument(const String & instrument)
{
instrument_ = instrument;
}
const String & HPLC::getColumn() const
{
return column_;
}
void HPLC::setColumn(const String & column)
{
column_ = column;
}
Int HPLC::getTemperature() const
{
return temperature_;
}
void HPLC::setTemperature(Int temperature)
{
temperature_ = temperature;
}
UInt HPLC::getPressure() const
{
return pressure_;
}
void HPLC::setPressure(UInt pressure)
{
pressure_ = pressure;
}
UInt HPLC::getFlux() const
{
return flux_;
}
void HPLC::setFlux(UInt flux)
{
flux_ = flux;
}
String HPLC::getComment() const
{
return comment_;
}
void HPLC::setComment(String comment)
{
comment_ = std::move(comment);
}
Gradient & HPLC::getGradient()
{
return gradient_;
}
const Gradient & HPLC::getGradient() const
{
return gradient_;
}
void HPLC::setGradient(const Gradient & gradient)
{
gradient_ = gradient;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/Gradient.cpp | .cpp | 5,468 | 205 | // 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/METADATA/Gradient.h>
#include <algorithm>
using namespace std;
namespace OpenMS
{
Gradient::~Gradient() = default;
bool Gradient::operator==(const Gradient & rhs) const
{
return (eluents_ == rhs.eluents_) &&
(times_ == rhs.times_) &&
(percentages_ == rhs.percentages_);
}
bool Gradient::operator!=(const Gradient & rhs) const
{
return !(operator==(rhs));
}
void Gradient::addEluent(const String & eluent)
{
//check if the eluent is valid
std::vector<String>::iterator elu_it = find(eluents_.begin(), eluents_.end(), eluent);
if (elu_it != eluents_.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "A eluent with this name already exists!", eluent);
}
eluents_.push_back(eluent);
// add zero values to percentages
percentages_.emplace_back(times_.size(), 0);
}
void Gradient::clearEluents()
{
eluents_.clear();
}
const std::vector<String> & Gradient::getEluents() const
{
return eluents_;
}
void Gradient::addTimepoint(Int timepoint)
{
if ((!times_.empty()) && (timepoint <= times_[times_.size() - 1]))
{
throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
times_.push_back(timepoint);
// add zero values to percentages
for (Size i = 0; i < eluents_.size(); ++i)
{
percentages_[i].push_back(0);
}
}
void Gradient::clearTimepoints()
{
times_.clear();
}
const std::vector<Int> & Gradient::getTimepoints() const
{
return times_;
}
void Gradient::setPercentage(const String & eluent, Int timepoint, UInt percentage)
{
// (1) validity check
//check if the eluent is valid
std::vector<String>::iterator elu_it = find(eluents_.begin(), eluents_.end(), eluent);
if (elu_it == eluents_.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The given eluent does not exist in the list of eluents!", eluent);
}
//check if the timepoint is valid
std::vector<Int>::iterator time_it = find(times_.begin(), times_.end(), timepoint);
if (time_it == times_.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The given timepoint does not exist in the list of timepoints!", String(timepoint));
}
// percentage is valid?
if (percentage > 100)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The percentage should be between 0 and 100!", String(percentage));
}
// (2) Look up indices
UInt elu_index(0), time_index(0);
//look up eluents index
for (std::vector<String>::iterator it = eluents_.begin(); it != eluents_.end(); ++it)
{
if (*it == eluent)
{
break;
}
++elu_index;
}
//look up timepoint index
for (std::vector<Int>::iterator it = times_.begin(); it != times_.end(); ++it)
{
if (*it == timepoint)
{
break;
}
++time_index;
}
// (3) set percentage
percentages_[elu_index][time_index] = percentage;
}
const std::vector<std::vector<UInt> > & Gradient::getPercentages() const
{
return percentages_;
}
UInt Gradient::getPercentage(const String & eluent, Int timepoint) const
{
// (1) validity check
//check if the eluent is valid
std::vector<String>::const_iterator elu_it = find(eluents_.begin(), eluents_.end(), eluent);
if (elu_it == eluents_.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The given eluent does not exist in the list of eluents!", eluent);
}
//check if the timepoint is valid
std::vector<Int>::const_iterator time_it = find(times_.begin(), times_.end(), timepoint);
if (time_it == times_.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The given timepoint does not exist in the list of timepoints!", String(timepoint));
}
// (2) Look up indices
UInt elu_index(0), time_index(0);
//look up eluents index
for (std::vector<String>::const_iterator it = eluents_.begin(); it != eluents_.end(); ++it)
{
if (*it == eluent)
{
break;
}
++elu_index;
}
//look up timepoint index
for (std::vector<Int>::const_iterator it = times_.begin(); it != times_.end(); ++it)
{
if (*it == timepoint)
{
break;
}
++time_index;
}
// (3) return percentage
return percentages_[elu_index][time_index];
}
void Gradient::clearPercentages()
{
percentages_.clear();
// fill all percentages with 0
percentages_.insert(percentages_.begin(), eluents_.size(), vector<UInt>(times_.size(), 0));
}
bool Gradient::isValid() const
{
for (Size j = 0; j < times_.size(); ++j)
{
Int sum = 0;
for (Size i = 0; i < eluents_.size(); ++i)
{
sum += percentages_[i][j];
}
if (sum != 100)
{
return false;
}
}
return true;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ProteinIdentification.cpp | .cpp | 32,496 | 932 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Nico Pfeifer, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/SYSTEM/File.h>
#include <numeric>
#include <unordered_set>
using namespace std;
namespace OpenMS
{
const std::string ProteinIdentification::NamesOfPeakMassType[] = {"Monoisotopic", "Average"};
ProteinIdentification::ProteinGroup::ProteinGroup() :
probability(0.0), accessions()
{
}
bool ProteinIdentification::ProteinGroup::operator==(const ProteinGroup& rhs) const
{
return std::tie(probability, accessions) == std::tie(rhs.probability, rhs.accessions);
}
bool ProteinIdentification::ProteinGroup::operator<(const ProteinGroup& rhs) const
{
// comparison of probabilities is intentionally "the wrong way around":
if (probability > rhs.probability)
{
return true;
}
if (probability < rhs.probability)
{
return false;
}
if (accessions.size() < rhs.accessions.size())
{
return true;
}
if (accessions.size() > rhs.accessions.size())
{
return false;
}
return accessions < rhs.accessions;
}
const ProteinIdentification::ProteinGroup::FloatDataArrays& ProteinIdentification::ProteinGroup::getFloatDataArrays() const
{
return float_data_arrays_;
}
void ProteinIdentification::ProteinGroup::setFloatDataArrays(const ProteinIdentification::ProteinGroup::FloatDataArrays &fda)
{
float_data_arrays_ = fda;
}
const ProteinIdentification::ProteinGroup::StringDataArrays& ProteinIdentification::ProteinGroup::getStringDataArrays() const
{
return string_data_arrays_;
}
void ProteinIdentification::ProteinGroup::setStringDataArrays(const ProteinIdentification::ProteinGroup::StringDataArrays& sda)
{
string_data_arrays_ = sda;
}
ProteinIdentification::ProteinGroup::StringDataArrays& ProteinIdentification::ProteinGroup::getStringDataArrays()
{
return string_data_arrays_;
}
const ProteinIdentification::ProteinGroup::IntegerDataArrays& ProteinIdentification::ProteinGroup::getIntegerDataArrays() const
{
return integer_data_arrays_;
}
ProteinIdentification::ProteinGroup::IntegerDataArrays& ProteinIdentification::ProteinGroup::getIntegerDataArrays()
{
return integer_data_arrays_;
}
void ProteinIdentification::ProteinGroup::setIntegerDataArrays(const ProteinIdentification::ProteinGroup::IntegerDataArrays& ida)
{
integer_data_arrays_ = ida;
}
ProteinIdentification::SearchParameters::SearchParameters() :
db(),
db_version(),
taxonomy(),
charges(),
mass_type(PeakMassType::MONOISOTOPIC),
fixed_modifications(),
variable_modifications(),
missed_cleavages(0),
fragment_mass_tolerance(0.0),
fragment_mass_tolerance_ppm(false),
precursor_mass_tolerance(0.0),
precursor_mass_tolerance_ppm(false),
digestion_enzyme("unknown_enzyme", ""),
enzyme_term_specificity(EnzymaticDigestion::SPEC_UNKNOWN)
{
}
bool ProteinIdentification::SearchParameters::operator==(const SearchParameters& rhs) const
{
return
std::tie(db, db_version, taxonomy, charges, mass_type, fixed_modifications, variable_modifications,
missed_cleavages, fragment_mass_tolerance, fragment_mass_tolerance_ppm, precursor_mass_tolerance,
precursor_mass_tolerance_ppm, digestion_enzyme, enzyme_term_specificity) ==
std::tie(rhs.db, rhs.db_version, rhs.taxonomy, rhs.charges, rhs.mass_type, rhs.fixed_modifications,
rhs.variable_modifications, rhs.missed_cleavages, rhs.fragment_mass_tolerance,
rhs.fragment_mass_tolerance_ppm, rhs.precursor_mass_tolerance,
rhs.precursor_mass_tolerance_ppm, rhs.digestion_enzyme, rhs.enzyme_term_specificity);
}
bool ProteinIdentification::SearchParameters::operator!=(const SearchParameters& rhs) const
{
return !(*this == rhs);
}
bool ProteinIdentification::SearchParameters::mergeable(const ProteinIdentification::SearchParameters& sp, const String& experiment_type) const
{
String spdb = sp.db;
spdb.substitute("\\","/");
String pdb = this->db;
pdb.substitute("\\","/");
if (this->precursor_mass_tolerance != sp.precursor_mass_tolerance ||
this->precursor_mass_tolerance_ppm != sp.precursor_mass_tolerance_ppm ||
File::basename(pdb) != File::basename(spdb) ||
this->db_version != sp.db_version ||
this->fragment_mass_tolerance != sp.fragment_mass_tolerance ||
this->fragment_mass_tolerance_ppm != sp.fragment_mass_tolerance_ppm ||
this->charges != sp.charges ||
this->digestion_enzyme != sp.digestion_enzyme ||
this->taxonomy != sp.taxonomy ||
this->enzyme_term_specificity != sp.enzyme_term_specificity)
{
return false;
}
set<String> fixed_mods(this->fixed_modifications.begin(), this->fixed_modifications.end());
set<String> var_mods(this->variable_modifications.begin(), this->variable_modifications.end());
set<String> curr_fixed_mods(sp.fixed_modifications.begin(), sp.fixed_modifications.end());
set<String> curr_var_mods(sp.variable_modifications.begin(), sp.variable_modifications.end());
if (fixed_mods != curr_fixed_mods ||
var_mods != curr_var_mods)
{
if (experiment_type != "labeled_MS1")
{
return false;
}
else
{
//TODO actually introduce a flag for labelling modifications in the Mod datastructures?
//OR put a unique ID for the used mod as a UserParam to the mapList entries (consensusHeaders)
//TODO actually you would probably need an experimental design here, because
//settings have to agree exactly in a FractionGroup but can slightly differ across runs.
//Or just ignore labelling mods during the check
return true;
}
}
return true;
}
int ProteinIdentification::SearchParameters::getChargeValue_(String& charge_str) const
{
// We have to do this because some people/tools put the + or - AFTER the number...
bool neg = charge_str.hasSubstring('-');
neg ? charge_str.remove('-') : charge_str.remove('+');
int val = charge_str.toInt();
return neg ? -val : val;
}
std::pair<int,int> ProteinIdentification::SearchParameters::getChargeRange() const
{
std::pair<int,int> result{0,0};
try // is there only one number (min = max)?
{
result.first = charges.toInt();
result.second = result.first;
}
catch (Exception::ConversionError&) // nope, something else
{
if (charges.hasSubstring(',')) // it's probably a list
{
IntList chgs = ListUtils::create<Int>(charges);
auto minmax = minmax_element(chgs.begin(), chgs.end());
result.first = *minmax.first;
result.second = *minmax.second;
}
else if (charges.hasSubstring(':')) // it's probably a range
{
StringList chgs;
charges.split(':', chgs);
if (chgs.size() > 2)
{
throw OpenMS::Exception::MissingInformation(
__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Charge string in SearchParameters not parseable.");
}
result.first = getChargeValue_(chgs[0]);
result.second = getChargeValue_(chgs[1]);
}
else
{
size_t pos = charges.find('-', 0);
std::vector<size_t> minus_positions;
while (pos != string::npos)
{
minus_positions.push_back(pos);
pos = charges.find('-', pos + 1);
}
if (!minus_positions.empty() && minus_positions.size() <= 3) // it's probably a range with '-'
{
Size split_pos(0);
if (minus_positions.size() <= 1) // split at first minus
{
split_pos = minus_positions[0];
}
else
{
split_pos = minus_positions[1];
}
String first = charges.substr(0, split_pos);
String second = charges.substr(split_pos + 1, string::npos);
result.first = getChargeValue_(first);
result.second = getChargeValue_(second);
}
}
}
return result;
}
ProteinIdentification::ProteinIdentification() :
MetaInfoInterface(),
id_(),
search_engine_(),
search_engine_version_(),
search_parameters_(),
date_(),
protein_score_type_(),
higher_score_better_(true),
protein_hits_(),
protein_groups_(),
indistinguishable_proteins_(),
protein_significance_threshold_(0.0)
{
}
ProteinIdentification::~ProteinIdentification() = default;
void ProteinIdentification::setDateTime(const DateTime& date)
{
date_ = date;
}
const DateTime& ProteinIdentification::getDateTime() const
{
return date_;
}
const vector<ProteinHit>& ProteinIdentification::getHits() const
{
return protein_hits_;
}
vector<ProteinHit>& ProteinIdentification::getHits()
{
return protein_hits_;
}
void ProteinIdentification::setHits(const vector<ProteinHit>& protein_hits)
{
protein_hits_ = protein_hits;
}
vector<ProteinHit>::iterator ProteinIdentification::findHit(
const String& accession)
{
vector<ProteinHit>::iterator pos = protein_hits_.begin();
for (; pos != protein_hits_.end(); ++pos)
{
if (pos->getAccession() == accession)
{
break;
}
}
return pos;
}
const vector<ProteinIdentification::ProteinGroup>& ProteinIdentification::getProteinGroups() const
{
return protein_groups_;
}
vector<ProteinIdentification::ProteinGroup>& ProteinIdentification::getProteinGroups()
{
return protein_groups_;
}
void ProteinIdentification::insertProteinGroup(const ProteinIdentification::ProteinGroup& group)
{
protein_groups_.push_back(group);
}
const vector<ProteinIdentification::ProteinGroup>&
ProteinIdentification::getIndistinguishableProteins() const
{
return indistinguishable_proteins_;
}
vector<ProteinIdentification::ProteinGroup>&
ProteinIdentification::getIndistinguishableProteins()
{
return indistinguishable_proteins_;
}
void ProteinIdentification::insertIndistinguishableProteins(
const ProteinIdentification::ProteinGroup& group)
{
indistinguishable_proteins_.push_back(group);
}
void ProteinIdentification::fillIndistinguishableGroupsWithSingletons()
{
unordered_set<string> groupedAccessions;
for (const ProteinGroup& proteinGroup : indistinguishable_proteins_)
{
for (const String& acc : proteinGroup.accessions)
{
groupedAccessions.insert(acc);
}
}
for (const ProteinHit& protein : getHits())
{
const String& acc = protein.getAccession();
if (groupedAccessions.find(acc) == groupedAccessions.end())
{
groupedAccessions.insert(acc);
ProteinGroup pg;
pg.accessions.push_back(acc);
pg.probability = protein.getScore();
indistinguishable_proteins_.push_back(pg);
}
}
}
// retrieval of the peptide significance threshold value
double ProteinIdentification::getSignificanceThreshold() const
{
return protein_significance_threshold_;
}
// setting of the peptide significance threshold value
void ProteinIdentification::setSignificanceThreshold(double value)
{
protein_significance_threshold_ = value;
}
void ProteinIdentification::setScoreType(const String& type)
{
protein_score_type_ = type;
}
const String& ProteinIdentification::getScoreType() const
{
return protein_score_type_;
}
void ProteinIdentification::insertHit(const ProteinHit& protein_hit)
{
protein_hits_.push_back(protein_hit);
}
void ProteinIdentification::insertHit(ProteinHit&& protein_hit)
{
protein_hits_.push_back(std::forward<ProteinHit>(protein_hit));
}
void ProteinIdentification::setPrimaryMSRunPath(const StringList& s, bool raw)
{
String meta_name = raw ? "spectra_data_raw" : "spectra_data";
setMetaValue(meta_name, DataValue(StringList()));
if (s.empty())
{
OPENMS_LOG_WARN << "Setting an empty value for primary MS runs paths." << std::endl;
}
else
{
addPrimaryMSRunPath(s, raw);
}
}
void ProteinIdentification::setPrimaryMSRunPath(const StringList& s, MSExperiment& e)
{
StringList ms_path;
e.getPrimaryMSRunPath(ms_path);
if (ms_path.size() == 1)
{
FileTypes::Type filetype = FileHandler::getTypeByFileName(ms_path[0]);
if ((filetype == FileTypes::MZML) && File::exists(ms_path[0]))
{
setMetaValue("spectra_data", DataValue(StringList({ms_path[0]})));
return; // don't do anything else in this case
}
if (filetype == FileTypes::RAW)
{
setMetaValue("spectra_data_raw", DataValue(StringList({ms_path[0]})));
}
}
setPrimaryMSRunPath(s);
}
/// get the file path to the first MS runs
void ProteinIdentification::getPrimaryMSRunPath(StringList& output, bool raw) const
{
String meta_name = raw ? "spectra_data_raw" : "spectra_data";
if (metaValueExists(meta_name))
{
output = getMetaValue(meta_name);
}
}
void ProteinIdentification::addPrimaryMSRunPath(const StringList& s, bool raw)
{
String meta_name = raw ? "spectra_data_raw" : "spectra_data";
if (!raw) // mzML files expected
{
for (const String &filename : s)
{
FileTypes::Type filetype = FileHandler::getTypeByFileName(filename);
if (filetype != FileTypes::MZML)
{
OPENMS_LOG_WARN << "To ensure tracability of results please prefer mzML files as primary MS runs.\n"
<< "Filename: '" << filename << "'" << std::endl;
}
}
}
StringList spectra_data = getMetaValue(meta_name, DataValue(StringList()));
spectra_data.insert(spectra_data.end(), s.begin(), s.end());
setMetaValue(meta_name, spectra_data);
}
void ProteinIdentification::addPrimaryMSRunPath(const String& s, bool raw)
{
addPrimaryMSRunPath(StringList({s}), raw);
}
Size ProteinIdentification::nrPrimaryMSRunPaths(bool raw) const
{
String meta_name = raw ? "spectra_data_raw" : "spectra_data";
StringList spectra_data = getMetaValue(meta_name, DataValue(StringList()));
return spectra_data.size();
}
//TODO find a more robust way to figure that out. CV Terms?
bool ProteinIdentification::hasInferenceData() const
{
return !getInferenceEngine().empty();
}
bool ProteinIdentification::hasInferenceEngineAsSearchEngine() const
{
String se = getSearchEngine();
return
se == "Fido" || // for downwards compatibility: FidoAdapter overwrites when it merges several runs
se == "BayesianProteinInference" || // for backwards compatibility
se == "Epifany" ||
(se == "Percolator" && !indistinguishable_proteins_.empty()) || // be careful, Percolator could be run with or without protein inference
se == "ProteinInference";
}
bool ProteinIdentification::peptideIDsMergeable(const ProteinIdentification& id_run, const String& experiment_type) const
{
const String& warn = " You probably do not want to merge the results with this tool."
" For merging searches with different engines/settings please use ConsensusID or PercolatorAdapter"
" to create a comparable score.";
const String& engine = this->getSearchEngine();
const String& version = this->getSearchEngineVersion();
bool ok = true;
if (id_run.getSearchEngine() != engine || id_run.getSearchEngineVersion() != version)
{
ok = false;
OPENMS_LOG_WARN << "Search engine " + id_run.getSearchEngine() + "from IDRun " + id_run.getIdentifier()
+ " does not match with the others." + warn;
}
const ProteinIdentification::SearchParameters& params = this->getSearchParameters();
const ProteinIdentification::SearchParameters& sp = id_run.getSearchParameters();
if (!params.mergeable(sp, experiment_type))
{
ok = false;
OPENMS_LOG_WARN << "Searchengine settings or modifications from IDRun " + id_run.getIdentifier() + " do not match with the others." + warn;
}
// TODO else merge as far as possible (mainly mods I guess)
return ok;
}
vector<pair<String,String>> ProteinIdentification::getSearchEngineSettingsAsPairs(const String& se) const
{
vector<pair<String,String>> result;
const auto& params = this->getSearchParameters();
if (se.empty() || (this->getSearchEngine() == se
&& this->getSearchEngine() != "Percolator" //meaningless settings
&& !this->getSearchEngine().hasPrefix("ConsensusID"))) //meaningless settings
{
//TODO add spectra_data?
result.emplace_back("db", params.db);
result.emplace_back("db_version", params.db_version);
result.emplace_back("fragment_mass_tolerance", params.fragment_mass_tolerance);
result.emplace_back("fragment_mass_tolerance_unit", params.fragment_mass_tolerance_ppm ? "ppm" : "Da");
result.emplace_back("precursor_mass_tolerance", params.precursor_mass_tolerance);
result.emplace_back("precursor_mass_tolerance_unit", params.precursor_mass_tolerance_ppm ? "ppm" : "Da");
result.emplace_back("enzyme", params.digestion_enzyme.getName());
result.emplace_back("enzyme_term_specificity", EnzymaticDigestion::NamesOfSpecificity[params.enzyme_term_specificity]);
result.emplace_back("charges", params.charges);
result.emplace_back("missed_cleavages", params.missed_cleavages);
result.emplace_back("fixed_modifications", ListUtils::concatenate(params.fixed_modifications,","));
result.emplace_back("variable_modifications", ListUtils::concatenate(params.variable_modifications,","));
}
else
{
vector<String> mvkeys;
params.getKeys(mvkeys);
for (const String & mvkey : mvkeys)
{
if (mvkey.hasPrefix(se))
{
result.emplace_back(mvkey.substr(se.size()+1), params.getMetaValue(mvkey));
}
}
}
return result;
}
// Equality operator
bool ProteinIdentification::operator==(const ProteinIdentification& rhs) const
{
return MetaInfoInterface::operator==(rhs) &&
std::tie(id_, search_engine_, search_engine_version_,
search_parameters_, date_, protein_hits_, protein_groups_,
indistinguishable_proteins_, protein_score_type_,
protein_significance_threshold_, higher_score_better_) ==
std::tie(rhs.id_, rhs.search_engine_, rhs.search_engine_version_,
rhs.search_parameters_, rhs.date_, rhs.protein_hits_, rhs.protein_groups_,
rhs.indistinguishable_proteins_, rhs.protein_score_type_,
rhs.protein_significance_threshold_, rhs.higher_score_better_);
}
// Inequality operator
bool ProteinIdentification::operator!=(const ProteinIdentification& rhs) const
{
return !operator==(rhs);
}
void ProteinIdentification::sort()
{
if (higher_score_better_)
{
std::stable_sort(protein_hits_.begin(), protein_hits_.end(), ProteinHit::ScoreMore());
}
else
{
std::stable_sort(protein_hits_.begin(), protein_hits_.end(), ProteinHit::ScoreLess());
}
}
void ProteinIdentification::fillEvidenceMapping_(unordered_map<String, set<PeptideEvidence> >& map_acc_2_evidence,
const PeptideIdentificationList& pep_ids) const
{
//TODO check matching identifiers?
for (const auto & peptide_id : pep_ids)
{
// peptide hits
const vector<PeptideHit>& peptide_hits = peptide_id.getHits();
for (const auto & peptide_hit : peptide_hits)
{
const std::vector<PeptideEvidence>& ph_evidences = peptide_hit.getPeptideEvidences();
// matched proteins for hit
for (const auto & evidence : ph_evidences)
{
map_acc_2_evidence[evidence.getProteinAccession()].insert(evidence);
}
}
}
}
void ProteinIdentification::computeCoverage(const PeptideIdentificationList& pep_ids)
{
// map protein accession to the corresponding peptide evidence
unordered_map<String, set<PeptideEvidence> > map_acc_2_evidence;
fillEvidenceMapping_(map_acc_2_evidence, pep_ids);
computeCoverageFromEvidenceMapping_(map_acc_2_evidence);
}
void ProteinIdentification::computeCoverage(const ConsensusMap& cmap, bool use_unassigned_ids)
{
// map protein accession to the corresponding peptide evidence
unordered_map<String, set<PeptideEvidence> > map_acc_2_evidence;
for (const auto& feat : cmap)
{
fillEvidenceMapping_(map_acc_2_evidence,feat.getPeptideIdentifications());
}
if (use_unassigned_ids)
{
fillEvidenceMapping_(map_acc_2_evidence, cmap.getUnassignedPeptideIdentifications());
}
computeCoverageFromEvidenceMapping_(map_acc_2_evidence);
}
void ProteinIdentification::computeCoverageFromEvidenceMapping_(const unordered_map<String, set<PeptideEvidence>>& map_acc_2_evidence)
{
for (Size i = 0; i < this->protein_hits_.size(); ++i)
{
const Size protein_length = this->protein_hits_[i].getSequence().length();
if (protein_length == 0)
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, " ProteinHits do not contain a protein sequence. Cannot compute coverage! Use PeptideIndexer to annotate proteins with sequence information.");
}
vector<bool> covered_amino_acids(protein_length, false);
const String& accession = this->protein_hits_[i].getAccession();
double coverage = 0.0;
if (map_acc_2_evidence.find(accession) != map_acc_2_evidence.end())
{
const set<PeptideEvidence>& evidences = map_acc_2_evidence.find(accession)->second;
for (const auto & evidence : evidences)
{
int start = evidence.getStart();
int stop = evidence.getEnd();
if (start == PeptideEvidence::UNKNOWN_POSITION || stop == PeptideEvidence::UNKNOWN_POSITION)
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
" PeptideEvidence does not contain start or end position. Cannot compute coverage!");
}
if (start < 0 || stop < start || stop > static_cast<int>(protein_length))
{
const String message = " PeptideEvidence (start/end) (" + String(start) + "/" + String(stop) +
" ) are invalid or point outside of protein '" + accession +
"' (length: " + String(protein_length) +
"). Cannot compute coverage!";
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, message);
}
std::fill(covered_amino_acids.begin() + start, covered_amino_acids.begin() + stop + 1, true);
}
coverage = 100.0 * (double) std::accumulate(covered_amino_acids.begin(),
covered_amino_acids.end(), 0) / (double) protein_length;
}
this->protein_hits_[i].setCoverage(coverage);
}
}
void ProteinIdentification::computeModifications(
const PeptideIdentificationList& pep_ids,
const StringList& skip_modifications)
{
// map protein accession to observed position,modifications pairs
unordered_map<String, set<pair<Size, ResidueModification>>> prot2mod;
fillModMapping_(pep_ids, skip_modifications, prot2mod);
for (auto & protein_hit : protein_hits_)
{
const String& accession = protein_hit.getAccession();
if (prot2mod.find(accession) != prot2mod.end())
{
protein_hit.setModifications(prot2mod[accession]);
}
}
}
void ProteinIdentification::computeModifications(
const ConsensusMap& cmap,
const StringList& skip_modifications,
bool use_unassigned_ids)
{
// map protein accession to observed position,modifications pairs
unordered_map<String, set<pair<Size, ResidueModification>>> prot2mod;
for (const auto& feat : cmap)
{
fillModMapping_(feat.getPeptideIdentifications(), skip_modifications, prot2mod);
}
if (use_unassigned_ids) fillModMapping_(cmap.getUnassignedPeptideIdentifications(), skip_modifications, prot2mod);
for (auto & protein_hit : protein_hits_)
{
const String& accession = protein_hit.getAccession();
if (prot2mod.find(accession) != prot2mod.end())
{
protein_hit.setModifications(prot2mod[accession]);
}
}
}
void ProteinIdentification::fillModMapping_(const PeptideIdentificationList& pep_ids, const StringList& skip_modifications,
unordered_map<String, set<pair<Size, ResidueModification>>>& prot2mod) const
{
for (const auto & peptide_id : pep_ids)
{
// peptide hits
const vector<PeptideHit>& peptide_hits = peptide_id.getHits();
for (const auto & peptide_hit : peptide_hits)
{
const AASequence& aas = peptide_hit.getSequence();
const vector<PeptideEvidence>& ph_evidences = peptide_hit.getPeptideEvidences();
// skip unmodified peptides
if (aas.isModified())
{
if (aas.hasNTerminalModification())
{
const ResidueModification * res_mod = aas.getNTerminalModification();
// skip mod if Id, e.g. 'Carbamidomethyl' or full id e.g., 'Carbamidomethyl (C)' match.
if (std::find(skip_modifications.begin(), skip_modifications.end(), res_mod->getId()) == skip_modifications.end()
&& std::find(skip_modifications.begin(), skip_modifications.end(), res_mod->getFullId()) == skip_modifications.end())
{
for (const auto & ph_evidence : ph_evidences)
{
const String& acc = ph_evidence.getProteinAccession();
const Size mod_pos = ph_evidence.getStart(); // mod at N terminus
prot2mod[acc].insert(make_pair(mod_pos, *res_mod));
}
}
}
for (Size ai = 0; ai != aas.size(); ++ai)
{
if (aas[ai].isModified())
{
const ResidueModification * res_mod = aas[ai].getModification();
if (find(skip_modifications.begin(), skip_modifications.end(), res_mod->getId()) == skip_modifications.end()
&& find(skip_modifications.begin(), skip_modifications.end(), res_mod->getFullId()) == skip_modifications.end())
{
for (const auto & ph_evidence : ph_evidences)
{
const String& acc = ph_evidence.getProteinAccession();
const Size mod_pos = ph_evidence.getStart() + ai; // start + ai
prot2mod[acc].insert(make_pair(mod_pos, *res_mod));
}
}
}
}
if (aas.hasCTerminalModification())
{
const ResidueModification * res_mod = aas.getCTerminalModification();
// skip mod?
if (find(skip_modifications.begin(), skip_modifications.end(), res_mod->getId()) == skip_modifications.end()
&& find(skip_modifications.begin(), skip_modifications.end(), res_mod->getFullId()) == skip_modifications.end())
{
for (const auto & ph_evidence : ph_evidences)
{
const String& acc = ph_evidence.getProteinAccession();
const Size mod_pos = ph_evidence.getEnd(); // mod at C terminus
prot2mod[acc].insert(make_pair(mod_pos, *res_mod));
}
}
}
}
}
}
}
bool ProteinIdentification::isHigherScoreBetter() const
{
return higher_score_better_;
}
void ProteinIdentification::setHigherScoreBetter(bool value)
{
higher_score_better_ = value;
}
const String& ProteinIdentification::getIdentifier() const
{
return id_;
}
void ProteinIdentification::setIdentifier(const String& id)
{
id_ = id;
}
void ProteinIdentification::setSearchEngine(const String& search_engine)
{
search_engine_ = search_engine;
}
const String& ProteinIdentification::getSearchEngine() const
{
return search_engine_;
}
const String ProteinIdentification::getOriginalSearchEngineName() const
{
// TODO: extend to multiple search engines and merging
String engine = search_engine_;
if (!engine.hasSubstring("Percolator") && !engine.hasSubstring("ConsensusID"))
{
return engine;
}
String original_SE = "Unknown";
vector<String> mvkeys;
getSearchParameters().getKeys(mvkeys);
for (const String& mvkey : mvkeys)
{
if (mvkey.hasPrefix("SE:") && !mvkey.hasSubstring("percolator"))
{
original_SE = mvkey.substr(3);
break; // multiSE percolator before consensusID not allowed; we take first only
}
}
return original_SE;
}
void ProteinIdentification::setSearchEngineVersion(const String& search_engine_version)
{
search_engine_version_ = search_engine_version;
}
const String& ProteinIdentification::getSearchEngineVersion() const
{
return search_engine_version_;
}
void ProteinIdentification::setSearchParameters(const SearchParameters& search_parameters)
{
search_parameters_ = search_parameters;
}
void ProteinIdentification::setSearchParameters(SearchParameters&& search_parameters)
{
search_parameters_ = std::move(search_parameters);
}
const ProteinIdentification::SearchParameters& ProteinIdentification::getSearchParameters() const
{
return search_parameters_;
}
ProteinIdentification::SearchParameters& ProteinIdentification::getSearchParameters()
{
return search_parameters_;
}
void ProteinIdentification::setInferenceEngine(const String& inference_engine)
{
this->search_parameters_.setMetaValue("InferenceEngine", inference_engine);
}
const String ProteinIdentification::getInferenceEngine() const
{
if (this->search_parameters_.metaValueExists("InferenceEngine"))
{
return this->search_parameters_.getMetaValue("InferenceEngine");
}
else if (hasInferenceEngineAsSearchEngine())
{
return search_engine_;
}
return "";
}
void ProteinIdentification::setInferenceEngineVersion(const String& search_engine_version)
{
this->search_parameters_.setMetaValue("InferenceEngineVersion", search_engine_version);
}
const String ProteinIdentification::getInferenceEngineVersion() const
{
if (this->search_parameters_.metaValueExists("InferenceEngineVersion"))
{
return this->search_parameters_.getMetaValue("InferenceEngineVersion");
}
else if (hasInferenceData())
{
return search_engine_version_;
}
return "";
}
void ProteinIdentification::copyMetaDataOnly(const ProteinIdentification& p)
{
id_ = p.id_;
search_engine_ = p.search_engine_;
search_engine_version_ = p.search_engine_version_;
search_parameters_ = p.search_parameters_;
date_ = p.date_;
protein_score_type_ = p.protein_score_type_;
higher_score_better_ = p.higher_score_better_;
protein_significance_threshold_ = p.protein_significance_threshold_;
MetaInfoInterface::operator=(static_cast<MetaInfoInterface>(p));
}
StringList ProteinIdentification::getAllNamesOfPeakMassType()
{
StringList names;
names.reserve(static_cast<size_t>(PeakMassType::SIZE_OF_PEAKMASSTYPE));
for (size_t i = 0; i < static_cast<size_t>(PeakMassType::SIZE_OF_PEAKMASSTYPE); ++i)
{
names.push_back(NamesOfPeakMassType[i]);
}
return names;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/Sample.cpp | .cpp | 4,611 | 213 | // 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/METADATA/Sample.h>
#include <algorithm>
using namespace std;
namespace OpenMS
{
const std::string Sample::NamesOfSampleState[] = {"Unknown", "solid", "liquid", "gas", "solution", "emulsion", "suspension"};
Sample::Sample() :
MetaInfoInterface(),
state_(SampleState::SAMPLENULL),
mass_(0.0),
volume_(0.0),
concentration_(0.0)
{
}
Sample::Sample(const Sample & source) :
MetaInfoInterface(source),
name_(source.name_),
number_(source.number_),
comment_(source.comment_),
organism_(source.organism_),
state_(source.state_),
mass_(source.mass_),
volume_(source.volume_),
concentration_(source.concentration_),
subsamples_(source.subsamples_)
{
}
Sample::~Sample() = default;
Sample & Sample::operator=(const Sample & source)
{
if (&source == this)
{
return *this;
}
name_ = source.name_;
number_ = source.number_;
comment_ = source.comment_;
organism_ = source.organism_;
state_ = source.state_;
mass_ = source.mass_;
volume_ = source.volume_;
concentration_ = source.concentration_;
subsamples_ = source.subsamples_;
MetaInfoInterface::operator=(source);
return *this;
}
bool Sample::operator==(const Sample & rhs) const
{
if (
name_ != rhs.name_ ||
number_ != rhs.number_ ||
comment_ != rhs.comment_ ||
organism_ != rhs.organism_ ||
state_ != rhs.state_ ||
mass_ != rhs.mass_ ||
volume_ != rhs.volume_ ||
concentration_ != rhs.concentration_ ||
subsamples_ != rhs.subsamples_ ||
MetaInfoInterface::operator!=(rhs))
{
return false;
}
return true;
}
const String & Sample::getName() const
{
return name_;
}
void Sample::setName(const String & name)
{
name_ = name;
}
const String & Sample::getOrganism() const
{
return organism_;
}
void Sample::setOrganism(const String & organism)
{
organism_ = organism;
}
const String & Sample::getNumber() const
{
return number_;
}
void Sample::setNumber(const String & number)
{
number_ = number;
}
const String & Sample::getComment() const
{
return comment_;
}
void Sample::setComment(const String & comment)
{
comment_ = comment;
}
Sample::SampleState Sample::getState() const
{
return state_;
}
void Sample::setState(Sample::SampleState state)
{
state_ = state;
}
double Sample::getMass() const
{
return mass_;
}
void Sample::setMass(double mass)
{
mass_ = mass;
}
double Sample::getVolume() const
{
return volume_;
}
void Sample::setVolume(double volume)
{
volume_ = volume;
}
double Sample::getConcentration() const
{
return concentration_;
}
void Sample::setConcentration(double concentration)
{
concentration_ = concentration;
}
const vector<Sample> & Sample::getSubsamples() const
{
return subsamples_;
}
vector<Sample> & Sample::getSubsamples()
{
return subsamples_;
}
void Sample::setSubsamples(const vector<Sample> & subsamples)
{
subsamples_ = subsamples;
}
StringList Sample::getAllNamesOfSampleState()
{
StringList names;
names.reserve(static_cast<size_t>(SampleState::SIZE_OF_SAMPLESTATE));
for (size_t i = 0; i < static_cast<size_t>(SampleState::SIZE_OF_SAMPLESTATE); ++i)
{
names.push_back(NamesOfSampleState[i]);
}
return names;
}
const std::string& Sample::sampleStateToString(SampleState state)
{
if (state == SampleState::SIZE_OF_SAMPLESTATE)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_SAMPLESTATE");
}
return NamesOfSampleState[static_cast<size_t>(state)];
}
Sample::SampleState Sample::toSampleState(const std::string& name)
{
auto first = &NamesOfSampleState[0];
auto last = &NamesOfSampleState[static_cast<size_t>(SampleState::SIZE_OF_SAMPLESTATE)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<SampleState>(it - first);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/AnnotatedMSRun.cpp | .cpp | 1,727 | 65 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: David Voigt, Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/METADATA/AnnotatedMSRun.h>
namespace OpenMS
{
PeptideIdentificationList& AnnotatedMSRun::getPeptideIdentifications()
{
return peptide_ids_;
}
const PeptideIdentificationList& AnnotatedMSRun::getPeptideIdentifications() const
{
return peptide_ids_;
}
void AnnotatedMSRun::setPeptideIdentifications(const PeptideIdentificationList& ids)
{
peptide_ids_ = ids;
}
void AnnotatedMSRun::setPeptideIdentifications(PeptideIdentificationList&& ids)
{
peptide_ids_ = std::move(ids);
}
MSExperiment& AnnotatedMSRun::getMSExperiment()
{
return data;
}
const MSExperiment& AnnotatedMSRun::getMSExperiment() const
{
return data;
}
void AnnotatedMSRun::setMSExperiment(MSExperiment&& experiment)
{
data = std::move(experiment);
}
void AnnotatedMSRun::setMSExperiment(const MSExperiment& experiment)
{
data = experiment;
}
void AnnotatedMSRun::checkPeptideIdSize_(const char* function_name) const
{
if (data.getSpectra().size() != peptide_ids_.size())
{
throw Exception::InvalidValue(__FILE__, __LINE__,
function_name, // Use the provided function name
"Internal inconsistency: Number of spectra and peptide identifications do not match.",
String(data.getSpectra().size()) + " vs " + String(peptide_ids_.size()));
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/Acquisition.cpp | .cpp | 875 | 38 | // 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/METADATA/Acquisition.h>
using namespace std;
namespace OpenMS
{
bool Acquisition::operator==(const Acquisition & rhs) const
{
return identifier_ == rhs.identifier_ && MetaInfoInterface::operator==(rhs);
}
bool Acquisition::operator!=(const Acquisition & rhs) const
{
return !(operator==(rhs));
}
const String & Acquisition::getIdentifier() const
{
return identifier_;
}
void Acquisition::setIdentifier(const String & identifier)
{
identifier_ = identifier;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/Product.cpp | .cpp | 1,223 | 61 | // 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/METADATA/Product.h>
using namespace std;
namespace OpenMS
{
bool Product::operator==(const Product & rhs) const
{
return mz_ == rhs.mz_ &&
window_low_ == rhs.window_low_ &&
window_up_ == rhs.window_up_ &&
CVTermList::operator==(rhs);
}
bool Product::operator!=(const Product & rhs) const
{
return !(operator==(rhs));
}
double Product::getMZ() const
{
return mz_;
}
void Product::setMZ(double mz)
{
mz_ = mz;
}
double Product::getIsolationWindowLowerOffset() const
{
return window_low_;
}
void Product::setIsolationWindowLowerOffset(double bound)
{
window_low_ = bound;
}
double Product::getIsolationWindowUpperOffset() const
{
return window_up_;
}
void Product::setIsolationWindowUpperOffset(double bound)
{
window_up_ = bound;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/IonDetector.cpp | .cpp | 5,031 | 166 | // 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/METADATA/IonDetector.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <algorithm>
using namespace std;
namespace OpenMS
{
const std::string IonDetector::NamesOfType[] = {"Unknown", "Electron multiplier", "Photo multiplier", "Focal plane array", "Faraday cup", "Conversion dynode electron multiplier", "Conversion dynode photo multiplier", "Multi-collector", "Channel electron multiplier", "channeltron", "daly detector", "microchannel plate detector", "array detector", "conversion dynode", "dynode", "focal plane collector", "ion-to-photon detector", "point collector", "postacceleration detector", "photodiode array detector", "inductive detector", "electron multiplier tube"};
const std::string IonDetector::NamesOfAcquisitionMode[] = {"Unknown", "Pulse counting", "Analog-digital converter", "Time-digital converter", "Transient recorder"};
IonDetector::IonDetector() :
MetaInfoInterface(),
type_(Type::TYPENULL),
acquisition_mode_(AcquisitionMode::ACQMODENULL),
resolution_(0.0),
ADC_sampling_frequency_(0.0),
order_(0)
{
}
IonDetector::~IonDetector() = default;
bool IonDetector::operator==(const IonDetector & rhs) const
{
return order_ == rhs.order_ &&
type_ == rhs.type_ &&
acquisition_mode_ == rhs.acquisition_mode_ &&
resolution_ == rhs.resolution_ &&
ADC_sampling_frequency_ == rhs.ADC_sampling_frequency_ &&
MetaInfoInterface::operator==(rhs);
}
bool IonDetector::operator!=(const IonDetector & rhs) const
{
return !(operator==(rhs));
}
IonDetector::Type IonDetector::getType() const
{
return type_;
}
void IonDetector::setType(IonDetector::Type type)
{
type_ = type;
}
IonDetector::AcquisitionMode IonDetector::getAcquisitionMode() const
{
return acquisition_mode_;
}
void IonDetector::setAcquisitionMode(IonDetector::AcquisitionMode acquisition_mode)
{
acquisition_mode_ = acquisition_mode;
}
double IonDetector::getResolution() const
{
return resolution_;
}
void IonDetector::setResolution(double resolution)
{
resolution_ = resolution;
}
double IonDetector::getADCSamplingFrequency() const
{
return ADC_sampling_frequency_;
}
void IonDetector::setADCSamplingFrequency(double ADC_sampling_frequency)
{
ADC_sampling_frequency_ = ADC_sampling_frequency;
}
Int IonDetector::getOrder() const
{
return order_;
}
void IonDetector::setOrder(Int order)
{
order_ = order;
}
StringList IonDetector::getAllNamesOfType()
{
StringList names;
names.reserve(static_cast<size_t>(Type::SIZE_OF_TYPE));
for (size_t i = 0; i < static_cast<size_t>(Type::SIZE_OF_TYPE); ++i)
{
names.push_back(NamesOfType[i]);
}
return names;
}
StringList IonDetector::getAllNamesOfAcquisitionMode()
{
StringList names;
names.reserve(static_cast<size_t>(AcquisitionMode::SIZE_OF_ACQUISITIONMODE));
for (size_t i = 0; i < static_cast<size_t>(AcquisitionMode::SIZE_OF_ACQUISITIONMODE); ++i)
{
names.push_back(NamesOfAcquisitionMode[i]);
}
return names;
}
const std::string& IonDetector::typeToString(Type type)
{
if (type == Type::SIZE_OF_TYPE)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_TYPE");
}
return NamesOfType[static_cast<size_t>(type)];
}
IonDetector::Type IonDetector::toType(const std::string& name)
{
auto first = &NamesOfType[0];
auto last = &NamesOfType[static_cast<size_t>(Type::SIZE_OF_TYPE)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<Type>(it - first);
}
const std::string& IonDetector::acquisitionModeToString(AcquisitionMode mode)
{
if (mode == AcquisitionMode::SIZE_OF_ACQUISITIONMODE)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_ACQUISITIONMODE");
}
return NamesOfAcquisitionMode[static_cast<size_t>(mode)];
}
IonDetector::AcquisitionMode IonDetector::toAcquisitionMode(const std::string& name)
{
auto first = &NamesOfAcquisitionMode[0];
auto last = &NamesOfAcquisitionMode[static_cast<size_t>(AcquisitionMode::SIZE_OF_ACQUISITIONMODE)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<AcquisitionMode>(it - first);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ProteinModificationSummary.cpp | .cpp | 791 | 23 | // Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/METADATA/ProteinModificationSummary.h>
using namespace OpenMS;
bool ProteinModificationSummary::operator==(const ProteinModificationSummary& rhs) const
{
return AALevelSummary == rhs.AALevelSummary;
}
bool ProteinModificationSummary::Statistics::operator==(const Statistics& rhs) const
{
return std::tie(count, frequency, FLR, probability) == std::tie(rhs.count, rhs.frequency, rhs.FLR, rhs.probability);
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/PeptideIdentification.cpp | .cpp | 9,086 | 310 | // 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/METADATA/PeptideIdentification.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/CONCEPT/Constants.h>
using namespace std;
namespace OpenMS
{
PeptideIdentification::PeptideIdentification() :
MetaInfoInterface(),
id_(),
hits_(),
score_type_(),
higher_score_better_(true),
mz_(std::numeric_limits<double>::quiet_NaN()),
rt_(std::numeric_limits<double>::quiet_NaN())
{
}
PeptideIdentification::~PeptideIdentification() noexcept = default;
// Equality operator
bool PeptideIdentification::operator==(const PeptideIdentification& rhs) const
{
return MetaInfoInterface::operator==(rhs)
&& id_ == rhs.id_
&& hits_ == rhs.hits_
&& getSignificanceThreshold() == rhs.getSignificanceThreshold()
&& score_type_ == rhs.score_type_
&& higher_score_better_ == rhs.higher_score_better_
&& getExperimentLabel() == rhs.getExperimentLabel()
&& getBaseName() == rhs.getBaseName()
&& (mz_ == rhs.mz_ || (!this->hasMZ() && !rhs.hasMZ())) // might be NaN, so comparing == will always be false
&& (rt_ == rhs.rt_ || (!this->hasRT() && !rhs.hasRT()));// might be NaN, so comparing == will always be false
}
// Inequality operator
bool PeptideIdentification::operator!=(const PeptideIdentification& rhs) const
{
return !(*this == rhs);
}
double PeptideIdentification::getRT() const
{
return rt_;
}
void PeptideIdentification::setRT(double rt)
{
rt_ = rt;
}
bool PeptideIdentification::hasRT() const
{
return !std::isnan(rt_);
}
double PeptideIdentification::getMZ() const
{
return mz_;
}
void PeptideIdentification::setMZ(double mz)
{
mz_ = mz;
}
bool PeptideIdentification::hasMZ() const
{
return !std::isnan(mz_);
}
const std::vector<PeptideHit>& PeptideIdentification::getHits() const
{
return hits_;
}
std::vector<PeptideHit>& PeptideIdentification::getHits()
{
return hits_;
}
void PeptideIdentification::insertHit(const PeptideHit& hit)
{
hits_.push_back(hit);
}
void PeptideIdentification::insertHit(PeptideHit&& hit)
{
hits_.push_back(std::move(hit));
}
void PeptideIdentification::setHits(const std::vector<PeptideHit>& hits)
{
hits_ = hits;
}
void PeptideIdentification::setHits(std::vector<PeptideHit>&& hits)
{
hits_ = std::move(hits);
}
double PeptideIdentification::getSignificanceThreshold() const
{
return getMetaValue(Constants::UserParam::SIGNIFICANCE_THRESHOLD, 0.0);
}
void PeptideIdentification::setSignificanceThreshold(double value)
{
if (value != 0.0)
{
setMetaValue(Constants::UserParam::SIGNIFICANCE_THRESHOLD, value);
}
else
{
// Remove the meta value if the value is 0.0
removeMetaValue(Constants::UserParam::SIGNIFICANCE_THRESHOLD);
}
}
const String& PeptideIdentification::getScoreType() const
{
return score_type_;
}
void PeptideIdentification::setScoreType(const String& type)
{
score_type_ = type;
}
bool PeptideIdentification::isHigherScoreBetter() const
{
return higher_score_better_;
}
void PeptideIdentification::setHigherScoreBetter(bool value)
{
higher_score_better_ = value;
}
const String& PeptideIdentification::getIdentifier() const
{
return id_;
}
void PeptideIdentification::setIdentifier(const String& id)
{
id_ = id;
}
String PeptideIdentification::getSpectrumReference() const
{
return getMetaValue(Constants::UserParam::SPECTRUM_REFERENCE, "");
}
void PeptideIdentification::setSpectrumReference(const String& id)
{
setMetaValue(Constants::UserParam::SPECTRUM_REFERENCE, id);
}
String PeptideIdentification::getBaseName() const
{
return getMetaValue(Constants::UserParam::BASE_NAME, "");
}
void PeptideIdentification::setBaseName(const String& base_name)
{
// do not store empty base_name (default value)
if (!base_name.empty())
{
setMetaValue(Constants::UserParam::BASE_NAME, base_name);
}
else
{
removeMetaValue(Constants::UserParam::BASE_NAME);
}
}
const String PeptideIdentification::getExperimentLabel() const
{
// implement as meta value in order to reduce bloat of PeptideIdentification object
// -> this is mostly used for pepxml at the moment which allows each peptide id to belong to a different experiment
return this->getMetaValue("experiment_label", "");
}
void PeptideIdentification::setExperimentLabel(const String& label)
{
// do not store empty label (default value)
if (!label.empty())
{
setMetaValue("experiment_label", label);
}
}
std::function<bool(const PeptideHit&, const PeptideHit&)>
PeptideIdentification::getScoreComparator(bool higher_score_better)
{
if (higher_score_better)
{
return PeptideHit::ScoreMore();
}
else
{
return PeptideHit::ScoreLess();
}
}
void PeptideIdentification::sort()
{
std::stable_sort(hits_.begin(), hits_.end(), getScoreComparator(higher_score_better_));
}
bool PeptideIdentification::empty() const
{
return id_.empty()
&& hits_.empty()
&& getSignificanceThreshold() == 0.0
&& score_type_.empty()
&& higher_score_better_ == true
&& getBaseName().empty();
}
std::vector<PeptideHit> PeptideIdentification::getReferencingHits(const std::vector<PeptideHit>& hits, const std::set<String>& accession)
{
std::vector<PeptideHit> filtered;
for (const PeptideHit& h_it : hits)
{
set<String> hit_accessions = h_it.extractProteinAccessionsSet();
set<String> intersect;
set_intersection(hit_accessions.begin(), hit_accessions.end(), accession.begin(), accession.end(), std::inserter(intersect, intersect.begin()));
if (!intersect.empty())
{
filtered.push_back(h_it);
}
}
return filtered;
}
std::multimap<String, std::pair<Size, Size>>
PeptideIdentification::buildUIDsFromAllPepIDs(const ConsensusMap &cmap)
{
multimap<String, std::pair<Size, Size>> customID_to_cpepID{};
ProteinIdentification::Mapping mp_c(cmap.getProteinIdentifications());
//Iterates of the vector of PeptideIdentification to build the UID
//and the pep_index
auto lamda = [](const PeptideIdentificationList &cpep_ids,
const map<String, StringList> &identifier_to_msrunpath,
multimap<String, std::pair<Size, Size>> &customID_to_cpepID,
const Size &cf_index) {
Size pep_index = 0;
for (const PeptideIdentification &cpep_id : cpep_ids)
{
std::pair<Size, Size> index = {cf_index, pep_index};
auto uid = buildUIDFromPepID(cpep_id, identifier_to_msrunpath);
customID_to_cpepID.insert(make_pair(uid, index));
++pep_index;
}
};
//Build the multimap of all UIDs from the ConsensusMap
//The multimap maps the UID of the PeptideIdentification to all occurrences in the ConsensusMap
//An occurrence is described as a pair of an index of the ConsensusFeature and the PeptideIdentification
for (Size i = 0; i < cmap.size(); ++i)
{
lamda(cmap[i].getPeptideIdentifications(), mp_c.identifier_to_msrunpath, customID_to_cpepID, i);
}
//all unassigned PeptideIdentifications get -1 for the ConsensusFeature index
lamda(cmap.getUnassignedPeptideIdentifications(), mp_c.identifier_to_msrunpath, customID_to_cpepID, -1);
return customID_to_cpepID;
}
String PeptideIdentification::buildUIDFromPepID(const PeptideIdentification &pep_id,
const std::map<String, StringList> &fidentifier_to_msrunpath)
{
if (!pep_id.metaValueExists("spectrum_reference"))
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Spectrum reference missing at PeptideIdentification.");
}
String UID;
const auto &ms_run_path = fidentifier_to_msrunpath.at(pep_id.getIdentifier());
if (ms_run_path.size() == 1)
{
UID = ms_run_path[0] + '|' + pep_id.getSpectrumReference();
}
else if (pep_id.metaValueExists("map_index"))
{
UID = pep_id.getMetaValue("map_index").toString() + '|' +
pep_id.getSpectrumReference();
}
else
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Multiple files in a run, but no map_index in PeptideIdentification found.");
}
return UID;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ExperimentalSettings.cpp | .cpp | 3,440 | 152 | // 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/METADATA/ExperimentalSettings.h>
#include <ostream>
using namespace std;
namespace OpenMS
{
ExperimentalSettings::~ExperimentalSettings() = default;
bool ExperimentalSettings::operator==(const ExperimentalSettings & rhs) const
{
return sample_ == rhs.sample_ &&
source_files_ == rhs.source_files_ &&
contacts_ == rhs.contacts_ &&
instrument_ == rhs.instrument_ &&
hplc_ == rhs.hplc_ &&
datetime_ == rhs.datetime_ &&
comment_ == rhs.comment_ &&
fraction_identifier_ == rhs.fraction_identifier_ &&
MetaInfoInterface::operator==(rhs) &&
DocumentIdentifier::operator==(rhs);
}
bool ExperimentalSettings::operator!=(const ExperimentalSettings & rhs) const
{
return !(operator==(rhs));
}
const Sample & ExperimentalSettings::getSample() const
{
return sample_;
}
Sample & ExperimentalSettings::getSample()
{
return sample_;
}
void ExperimentalSettings::setSample(const Sample & sample)
{
sample_ = sample;
}
const vector<SourceFile> & ExperimentalSettings::getSourceFiles() const
{
return source_files_;
}
vector<SourceFile> & ExperimentalSettings::getSourceFiles()
{
return source_files_;
}
void ExperimentalSettings::setSourceFiles(const vector<SourceFile> & source_file)
{
source_files_ = source_file;
}
const vector<ContactPerson> & ExperimentalSettings::getContacts() const
{
return contacts_;
}
vector<ContactPerson> & ExperimentalSettings::getContacts()
{
return contacts_;
}
void ExperimentalSettings::setContacts(const std::vector<ContactPerson> & contacts)
{
contacts_ = contacts;
}
const Instrument & ExperimentalSettings::getInstrument() const
{
return instrument_;
}
Instrument & ExperimentalSettings::getInstrument()
{
return instrument_;
}
void ExperimentalSettings::setInstrument(const Instrument & instrument)
{
instrument_ = instrument;
}
const DateTime & ExperimentalSettings::getDateTime() const
{
return datetime_;
}
void ExperimentalSettings::setDateTime(const DateTime & date)
{
datetime_ = date;
}
const HPLC & ExperimentalSettings::getHPLC() const
{
return hplc_;
}
HPLC & ExperimentalSettings::getHPLC()
{
return hplc_;
}
void ExperimentalSettings::setHPLC(const HPLC & hplc)
{
hplc_ = hplc;
}
std::ostream & operator<<(std::ostream & os, const ExperimentalSettings & /*exp*/)
{
os << "-- EXPERIMENTALSETTINGS BEGIN --\n";
os << "-- EXPERIMENTALSETTINGS END --\n";
return os;
}
const String & ExperimentalSettings::getComment() const
{
return comment_;
}
void ExperimentalSettings::setComment(const String & comment)
{
comment_ = comment;
}
const String & ExperimentalSettings::getFractionIdentifier() const
{
return fraction_identifier_;
}
void ExperimentalSettings::setFractionIdentifier(const String & fraction_identifier)
{
fraction_identifier_ = fraction_identifier;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/SpectrumSettings.cpp | .cpp | 6,834 | 245 | // 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/METADATA/SpectrumSettings.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/Helpers.h>
#include <algorithm>
using namespace std;
namespace OpenMS
{
const std::string SpectrumSettings::NamesOfSpectrumType[] = {"Unknown", "Centroid", "Profile"};
bool SpectrumSettings::operator==(const SpectrumSettings & rhs) const
{
return MetaInfoInterface::operator==(rhs) &&
type_ == rhs.type_ &&
native_id_ == rhs.native_id_ &&
comment_ == rhs.comment_ &&
instrument_settings_ == rhs.instrument_settings_ &&
acquisition_info_ == rhs.acquisition_info_ &&
source_file_ == rhs.source_file_ &&
precursors_ == rhs.precursors_ &&
products_ == rhs.products_ &&
( data_processing_.size() == rhs.data_processing_.size() &&
std::equal(data_processing_.begin(),
data_processing_.end(),
rhs.data_processing_.begin(),
OpenMS::Helpers::cmpPtrSafe<DataProcessingPtr>) );
}
bool SpectrumSettings::operator!=(const SpectrumSettings & rhs) const
{
return !(operator==(rhs));
}
void SpectrumSettings::unify(const SpectrumSettings & rhs)
{
// append metavalues (overwrite when already present)
std::vector<UInt> keys;
rhs.getKeys(keys);
for (Size i = 0; i < keys.size(); ++i)
{
setMetaValue(keys[i], rhs.getMetaValue(keys[i]));
}
if (type_ != rhs.type_)
{
type_ = SpectrumType::UNKNOWN; // only keep if both are equal
}
//native_id_ == rhs.native_id_ // keep
comment_ += rhs.comment_; // append
//instrument_settings_ == rhs.instrument_settings_ // keep
//acquisition_info_ == rhs.acquisition_info_
//source_file_ == rhs.source_file_ &&
precursors_.insert(precursors_.end(), rhs.precursors_.begin(), rhs.precursors_.end());
products_.insert(products_.end(), rhs.products_.begin(), rhs.products_.end());
data_processing_.insert(data_processing_.end(), rhs.data_processing_.begin(), rhs.data_processing_.end());
}
SpectrumSettings::SpectrumType SpectrumSettings::getType() const
{
return type_;
}
void SpectrumSettings::setType(SpectrumSettings::SpectrumType type)
{
type_ = type;
}
void SpectrumSettings::setIMFormat(const IMFormat& im_type)
{
if (im_type == IMFormat::MIXED)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Single spectrum can't have MIXED ion mobility format.", "SIZE_OF_IMFORMAT");
}
im_type_ = im_type;
}
IMFormat SpectrumSettings::getIMFormat() const
{
return im_type_;
}
const String & SpectrumSettings::getComment() const
{
return comment_;
}
void SpectrumSettings::setComment(const String & comment)
{
comment_ = comment;
}
const InstrumentSettings & SpectrumSettings::getInstrumentSettings() const
{
return instrument_settings_;
}
InstrumentSettings & SpectrumSettings::getInstrumentSettings()
{
return instrument_settings_;
}
void SpectrumSettings::setInstrumentSettings(const InstrumentSettings & instrument_settings)
{
instrument_settings_ = instrument_settings;
}
const AcquisitionInfo & SpectrumSettings::getAcquisitionInfo() const
{
return acquisition_info_;
}
AcquisitionInfo & SpectrumSettings::getAcquisitionInfo()
{
return acquisition_info_;
}
void SpectrumSettings::setAcquisitionInfo(const AcquisitionInfo & acquisition_info)
{
acquisition_info_ = acquisition_info;
}
const SourceFile & SpectrumSettings::getSourceFile() const
{
return source_file_;
}
SourceFile & SpectrumSettings::getSourceFile()
{
return source_file_;
}
void SpectrumSettings::setSourceFile(const SourceFile & source_file)
{
source_file_ = source_file;
}
const vector<Precursor> & SpectrumSettings::getPrecursors() const
{
return precursors_;
}
vector<Precursor> & SpectrumSettings::getPrecursors()
{
return precursors_;
}
void SpectrumSettings::setPrecursors(const vector<Precursor> & precursors)
{
precursors_ = precursors;
}
const vector<Product> & SpectrumSettings::getProducts() const
{
return products_;
}
vector<Product> & SpectrumSettings::getProducts()
{
return products_;
}
void SpectrumSettings::setProducts(const vector<Product> & products)
{
products_ = products;
}
std::ostream & operator<<(std::ostream & os, const SpectrumSettings & /*spec*/)
{
os << "-- SPECTRUMSETTINGS BEGIN --" << std::endl;
os << "-- SPECTRUMSETTINGS END --" << std::endl;
return os;
}
const String & SpectrumSettings::getNativeID() const
{
return native_id_;
}
void SpectrumSettings::setNativeID(const String & native_id)
{
native_id_ = native_id;
}
void SpectrumSettings::setDataProcessing(const std::vector< DataProcessingPtr > & data_processing)
{
data_processing_ = data_processing;
}
std::vector< DataProcessingPtr > & SpectrumSettings::getDataProcessing()
{
return data_processing_;
}
const std::vector< std::shared_ptr<const DataProcessing > > SpectrumSettings::getDataProcessing() const
{
return OpenMS::Helpers::constifyPointerVector(data_processing_);
}
StringList SpectrumSettings::getAllNamesOfSpectrumType()
{
StringList names;
names.reserve(static_cast<size_t>(SpectrumType::SIZE_OF_SPECTRUMTYPE));
for (size_t i = 0; i < static_cast<size_t>(SpectrumType::SIZE_OF_SPECTRUMTYPE); ++i)
{
names.push_back(NamesOfSpectrumType[i]);
}
return names;
}
const std::string& SpectrumSettings::spectrumTypeToString(SpectrumType type)
{
if (type == SpectrumType::SIZE_OF_SPECTRUMTYPE)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_SPECTRUMTYPE");
}
return NamesOfSpectrumType[static_cast<size_t>(type)];
}
SpectrumSettings::SpectrumType SpectrumSettings::toSpectrumType(const std::string& name)
{
auto first = &NamesOfSpectrumType[0];
auto last = &NamesOfSpectrumType[static_cast<size_t>(SpectrumType::SIZE_OF_SPECTRUMTYPE)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<SpectrumType>(it - first);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/SpectrumMetaDataLookup.cpp | .cpp | 12,306 | 365 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/METADATA/SpectrumMetaDataLookup.h>
#include <OpenMS/IONMOBILITY/IMTypes.h>
#include <OpenMS/IONMOBILITY/FAIMSHelper.h>
#include <OpenMS/CONCEPT/Constants.h>
using namespace std;
namespace OpenMS
{
void SpectrumMetaDataLookup::getSpectrumMetaData(Size index,
SpectrumMetaData& meta) const
{
if (index >= n_spectra_)
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
index, n_spectra_);
}
meta = metadata_[index];
}
void SpectrumMetaDataLookup::getSpectrumMetaData(
const MSSpectrum& spectrum, SpectrumMetaData& meta,
const boost::regex& scan_regexp, const map<Size, double>& precursor_rts)
{
meta.native_id = spectrum.getNativeID();
meta.rt = spectrum.getRT();
meta.ms_level = spectrum.getMSLevel();
if (!scan_regexp.empty())
{
meta.scan_number = extractScanNumber(meta.native_id, scan_regexp, true);
if (meta.scan_number < 0)
{
OPENMS_LOG_ERROR << "Error: Could not extract scan number from spectrum native ID '" + meta.native_id + "' using regular expression '" + scan_regexp.str() + "'." << endl;
}
}
if (!spectrum.getPrecursors().empty())
{
meta.precursor_mz = spectrum.getPrecursors()[0].getMZ();
meta.precursor_charge = spectrum.getPrecursors()[0].getCharge();
if (!precursor_rts.empty())
{
// precursor RT is RT of previous spectrum with lower MS level:
map<Size, double>::const_iterator pos =
precursor_rts.find(meta.ms_level - 1);
if (pos != precursor_rts.end()) // found
{
meta.precursor_rt = pos->second;
}
else
{
OPENMS_LOG_ERROR << "Error: Could not set precursor RT for spectrum with native ID '" + meta.native_id + "' - precursor spectrum not found." << endl;
}
}
}
}
void SpectrumMetaDataLookup::getSpectrumMetaData(const String& spectrum_ref,
SpectrumMetaData& meta,
MetaDataFlags flags) const
{
for (std::vector<boost::regex>::const_iterator it =
reference_formats.begin(); it != reference_formats.end(); ++it)
{
boost::smatch match;
bool found = boost::regex_search(spectrum_ref, match, *it);
if (found)
{
// first try to extract the requested meta data from the reference:
if (((flags & MDF_RT) == MDF_RT) && match["RT"].matched)
{
String value = match["RT"].str();
if (!value.empty())
{
meta.rt = value.toDouble();
flags &= ~MDF_RT; // unset flag
}
}
if (((flags & MDF_PRECURSORRT) == MDF_PRECURSORRT) &&
match["PRECRT"].matched)
{
String value = match["PRECRT"].str();
if (!value.empty())
{
meta.precursor_rt = value.toDouble();
flags &= ~MDF_PRECURSORRT; // unset flag
}
}
if (((flags & MDF_PRECURSORMZ) == MDF_PRECURSORMZ) &&
match["MZ"].matched)
{
String value = match["MZ"].str();
if (!value.empty())
{
meta.precursor_mz = value.toDouble();
flags &= ~MDF_PRECURSORMZ; // unset flag
}
}
if (((flags & MDF_PRECURSORCHARGE) == MDF_PRECURSORCHARGE) &&
match["CHARGE"].matched)
{
String value = match["CHARGE"].str();
if (!value.empty())
{
meta.precursor_charge = value.toDouble();
flags &= ~MDF_PRECURSORCHARGE; // unset flag
}
}
if (((flags & MDF_MSLEVEL) == MDF_MSLEVEL) && match["LEVEL"].matched)
{
String value = match["LEVEL"].str();
if (!value.empty())
{
meta.ms_level = value.toInt();
flags &= ~MDF_MSLEVEL; // unset flag
}
}
if (((flags & MDF_SCANNUMBER) == MDF_SCANNUMBER) &&
match["SCAN"].matched)
{
String value = match["SCAN"].str();
if (!value.empty())
{
meta.scan_number = value.toInt();
flags &= ~MDF_SCANNUMBER; // unset flag
}
}
if (((flags & MDF_NATIVEID) == MDF_NATIVEID) && match["ID"].matched)
{
meta.native_id = match["ID"].str();
if (!meta.native_id.empty())
{
flags &= ~MDF_NATIVEID; // unset flag
}
}
if (flags) // not all requested values have been found -> look them up
{
Size index = findByRegExpMatch_(spectrum_ref, it->str(), match);
meta = metadata_[index];
}
return; // use the first reference format that matches
}
}
}
bool SpectrumMetaDataLookup::addMissingRTsToPeptideIDs(PeptideIdentificationList& peptides,
const MSExperiment& exp)
{
// Check if the experiment has spectra
if (exp.getSpectra().empty())
{
OPENMS_LOG_INFO << "No spectra found in the experiment. Skipping RT annotation." << endl;
return false;
}
SpectrumLookup lookup;
lookup.readSpectra(exp.getSpectra());
bool success = true;
// Iterate over peptide IDs and annotate missing RT values
for (auto& pep : peptides)
{
if (std::isnan(pep.getRT())) // Only annotate peptides with missing RT
{
String native_id = pep.getSpectrumReference();
try
{
// Look up spectrum index by native ID and assign RT
Size index = lookup.findByNativeID(native_id);
pep.setRT(exp.getSpectra()[index].getRT());
}
catch (Exception::ElementNotFound&)
{
// Log error if the spectrum reference is not found
OPENMS_LOG_ERROR << "Error: Failed to look up retention time for peptide identification with spectrum reference '"
<< native_id << "' - no spectrum with corresponding native ID found." << endl;
success = false;
}
}
}
return success;
}
bool SpectrumMetaDataLookup::addMissingIMToPeptideIDs(PeptideIdentificationList& peptides,
const MSExperiment& exp)
{
// Check if the experiment has spectra
if (exp.getSpectra().empty())
{
OPENMS_LOG_INFO << "No spectra found in the experiment. Skipping IM annotation." << endl;
return false;
}
SpectrumLookup lookup;
bool all_ids_have_im = true;
lookup.readSpectra(exp.getSpectra());
// Iterate over peptide_ids and annotate IM values stored in MSExperiment
for (auto& pep : peptides)
{
String native_id = pep.getSpectrumReference();
Size index = lookup.findByNativeID(native_id);
const MSSpectrum& spec = exp.getSpectra()[index];
// Check if desired IM format is present
if (IMTypes::determineIMFormat(spec) == IMFormat::MULTIPLE_SPECTRA)
{
pep.setMetaValue(Constants::UserParam::IM, spec.getDriftTime());
}
else
{
all_ids_have_im = false;
}
}
return all_ids_have_im;
}
bool SpectrumMetaDataLookup::addMissingFAIMSToPeptideIDs(PeptideIdentificationList& peptides,
const MSExperiment& exp)
{
// Check if the experiment has spectra
if (exp.getSpectra().empty())
{
OPENMS_LOG_INFO << "No spectra found in the experiment. Skipping FAIMS annotation." << endl;
return false;
}
// Check if experiment contains FAIMS data
std::set<double> faims_cvs = FAIMSHelper::getCompensationVoltages(exp);
if (faims_cvs.empty())
{
OPENMS_LOG_DEBUG << "No FAIMS data found in the experiment. Skipping FAIMS annotation." << endl;
return false;
}
SpectrumLookup lookup;
lookup.readSpectra(exp.getSpectra());
// Build a mapping from spectrum index to FAIMS CV
// Both MS1 and MS2 spectra can have explicit FAIMS CV annotations (DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE)
// For MS2 spectra without explicit FAIMS CV, fall back to the last seen FAIMS CV (from preceding spectrum)
std::map<Size, double> index_to_faims_cv;
double last_faims_cv = std::numeric_limits<double>::quiet_NaN();
for (Size i = 0; i < exp.size(); ++i)
{
const MSSpectrum& spec = exp[i];
if (spec.getDriftTimeUnit() == DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE)
{
// Spectrum has explicit FAIMS CV (can be MS1 or MS2)
last_faims_cv = spec.getDriftTime();
index_to_faims_cv[i] = last_faims_cv;
}
else if (!std::isnan(last_faims_cv) && spec.getMSLevel() > 1)
{
// MS2+ spectrum without explicit FAIMS CV inherits from context
index_to_faims_cv[i] = last_faims_cv;
}
}
Size annotated_count = 0;
// Iterate over peptide_ids and annotate FAIMS CV values
for (auto& pep : peptides)
{
// Skip if already annotated
if (pep.metaValueExists(Constants::UserParam::FAIMS_CV))
{
++annotated_count;
continue;
}
String native_id = pep.getSpectrumReference();
try
{
Size index = lookup.findByNativeID(native_id);
auto it = index_to_faims_cv.find(index);
if (it != index_to_faims_cv.end())
{
pep.setMetaValue(Constants::UserParam::FAIMS_CV, it->second);
++annotated_count;
}
}
catch (Exception::ElementNotFound&)
{
OPENMS_LOG_WARN << "Could not find spectrum with native ID '" << native_id
<< "' for FAIMS annotation." << endl;
}
}
OPENMS_LOG_INFO << "Annotated " << annotated_count << " of " << peptides.size()
<< " peptide IDs with FAIMS CV values." << endl;
return annotated_count > 0;
}
bool SpectrumMetaDataLookup::addMissingSpectrumReferences(PeptideIdentificationList& peptides, const String& filename,
bool stop_on_error,
bool override_spectra_data,
bool override_spectra_references,
vector<ProteinIdentification> proteins)
{
bool success = true;
PeakMap exp;
SpectrumMetaDataLookup lookup;
if (lookup.empty())
{
FileHandler fh;
auto opts = fh.getOptions();
opts.setFillData(false);
opts.setSkipXMLChecks(true);
fh.setOptions(opts);
fh.loadExperiment(filename, exp, {FileTypes::MZXML, FileTypes::MZML, FileTypes::MZDATA, FileTypes::MGF}, OpenMS::ProgressLogger::NONE, true, true);
lookup.readSpectra(exp.getSpectra());
lookup.setSpectraDataRef(filename);
}
if (override_spectra_data)
{
vector<String> spectra_data(1);
spectra_data[0] = "file://" + lookup.spectra_data_ref;
for (auto& prot : proteins)
{
prot.setMetaValue("spectra_data", spectra_data);
}
}
for (auto& pep : peptides)
{
// spectrum reference already set? skip if we don't want to overwrite
if (!override_spectra_references && pep.metaValueExists("spectrum_reference"))
{
continue;
}
try
{
Size index = lookup.findByRT(pep.getRT());
SpectrumMetaDataLookup::SpectrumMetaData meta;
lookup.getSpectrumMetaData(index, meta);
pep.setSpectrumReference( meta.native_id);
}
catch (Exception::ElementNotFound&)
{
OPENMS_LOG_ERROR << "Error: Failed to look up spectrum native ID for peptide identification with retention time '" + String(pep.getRT()) + "'." << endl;
success = false;
if (stop_on_error)
{
break;
}
}
}
return success;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/PeptideHit.cpp | .cpp | 12,876 | 459 | // 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/METADATA/PeptideHit.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/DATASTRUCTURES/DataValue.h>
#include <algorithm>
#include <ostream>
#include <tuple>
#include <utility>
using namespace std;
namespace OpenMS
{
// default constructor
PeptideHit::PeptideHit() :
MetaInfoInterface(),
sequence_(),
score_(0),
charge_(0),
peptide_evidences_(),
fragment_annotations_()
{
// Default rank (0) is not stored as meta value
}
// values constructor
PeptideHit::PeptideHit(double score, UInt rank, Int charge, const AASequence& sequence) :
MetaInfoInterface(),
sequence_(sequence),
score_(score),
charge_(charge),
peptide_evidences_(),
fragment_annotations_()
{
// Only set rank as meta value if it's not the default value
if (rank != 0)
{
setMetaValue(Constants::UserParam::RANK, rank);
}
}
// values constructor
PeptideHit::PeptideHit(double score, UInt rank, Int charge, AASequence&& sequence) :
MetaInfoInterface(),
sequence_(std::move(sequence)),
score_(score),
charge_(charge),
peptide_evidences_(),
fragment_annotations_()
{
// Only set rank as meta value if it's not the default value
if (rank != 0)
{
setMetaValue(Constants::UserParam::RANK, rank);
}
}
// copy constructor
PeptideHit::PeptideHit(const PeptideHit& source) :
MetaInfoInterface(source),
sequence_(source.sequence_),
score_(source.score_),
charge_(source.charge_),
peptide_evidences_(source.peptide_evidences_),
fragment_annotations_(source.fragment_annotations_)
{
// MetaInfoInterface copy constructor already copies all meta values including rank
}
/// Move constructor
PeptideHit::PeptideHit(PeptideHit&& source) noexcept :
MetaInfoInterface(std::move(source)), // NOTE: rhs itself is an lvalue
sequence_(std::move(source.sequence_)),
score_(source.score_),
charge_(source.charge_),
peptide_evidences_(std::move(source.peptide_evidences_)),
fragment_annotations_(std::move(source.fragment_annotations_))
{
// MetaInfoInterface move constructor already moves all meta values including rank
}
// destructor
PeptideHit::~PeptideHit()
{
}
PeptideHit& PeptideHit::operator=(const PeptideHit& source)
{
if (this == &source)
{
return *this;
}
MetaInfoInterface::operator=(source);
sequence_ = source.sequence_;
score_ = source.score_;
charge_ = source.charge_;
peptide_evidences_ = source.peptide_evidences_;
fragment_annotations_ = source.fragment_annotations_;
return *this;
}
PeptideHit& PeptideHit::operator=(PeptideHit&& source) noexcept
{
if (&source == this)
{
return *this;
}
MetaInfoInterface::operator=(std::move(source));
//clang-tidy overly strict, should be fine to move the rest here
sequence_ = std::move(source.sequence_);
score_ = source.score_;
charge_ = source.charge_;
peptide_evidences_ = std::move(source.peptide_evidences_);
fragment_annotations_ = std::move(source.fragment_annotations_);
return *this;
}
bool PeptideHit::operator==(const PeptideHit& rhs) const
{
return MetaInfoInterface::operator==(rhs)
&& sequence_ == rhs.sequence_
&& score_ == rhs.score_
&& getRank() == rhs.getRank() // Use getter instead of direct member access
&& charge_ == rhs.charge_
&& peptide_evidences_ == rhs.peptide_evidences_
&& fragment_annotations_ == rhs.fragment_annotations_;
}
bool PeptideHit::operator!=(const PeptideHit& rhs) const
{
return !operator==(rhs);
}
// returns the score of the peptide hit
double PeptideHit::getScore() const
{
return score_;
}
// returns the rank of the peptide hit
UInt PeptideHit::getRank() const
{
return getMetaValue(Constants::UserParam::RANK, 0);
}
const AASequence& PeptideHit::getSequence() const
{
return sequence_;
}
AASequence& PeptideHit::getSequence()
{
return sequence_;
}
void PeptideHit::setSequence(const AASequence& sequence)
{
sequence_ = sequence;
}
void PeptideHit::setSequence(AASequence&& sequence)
{
sequence_ = std::move(sequence);
}
Int PeptideHit::getCharge() const
{
return charge_;
}
void PeptideHit::setCharge(Int charge)
{
charge_ = charge;
}
const std::vector<PeptideEvidence>& PeptideHit::getPeptideEvidences() const
{
return peptide_evidences_;
}
void PeptideHit::setPeptideEvidences(const std::vector<PeptideEvidence>& peptide_evidences)
{
peptide_evidences_ = peptide_evidences;
}
void PeptideHit::setPeptideEvidences(std::vector<PeptideEvidence>&& peptide_evidences)
{
peptide_evidences_ = std::move(peptide_evidences);
}
void PeptideHit::addPeptideEvidence(const PeptideEvidence& peptide_evidence)
{
peptide_evidences_.push_back(peptide_evidence);
}
// sets the score of the peptide hit
void PeptideHit::setScore(double score)
{
score_ = score;
}
void PeptideHit::setAnalysisResults(const std::vector<PeptideHit::PepXMLAnalysisResult>& aresult)
{
// Remove all existing analysis result meta values
std::vector<String> keys;
getKeys(keys);
for (const auto& key : keys)
{
if (key.hasPrefix("_ar_"))
{
removeMetaValue(key);
}
}
// Add new analysis results as meta values
for (size_t i = 0; i < aresult.size(); ++i)
{
const auto& ar = aresult[i];
setMetaValue("_ar_" + String(i) + "_score_type", ar.score_type);
setMetaValue("_ar_" + String(i) + "_score", ar.main_score);
setMetaValue("_ar_" + String(i) + "_higher_is_better", ar.higher_is_better == true ? "true" : "false");
for (const auto& subscore : ar.sub_scores)
{
setMetaValue("_ar_" + String(i) + "_subscore_" + subscore.first, subscore.second);
}
}
}
void PeptideHit::addAnalysisResults(const PeptideHit::PepXMLAnalysisResult& aresult)
{
size_t index = getNumberOfAnalysisResultsFromMetaValues_();
setMetaValue("_ar_" + String(index) + "_score_type", aresult.score_type);
setMetaValue("_ar_" + String(index) + "_score", aresult.main_score);
setMetaValue("_ar_" + String(index) + "_higher_is_better", aresult.higher_is_better == true ? "true" : "false");
for (const auto& subscore : aresult.sub_scores)
{
setMetaValue("_ar_" + String(index) + "_subscore_" + subscore.first, subscore.second);
}
}
std::vector<PeptideHit::PepXMLAnalysisResult> PeptideHit::getAnalysisResults() const
{
return extractAnalysisResultsFromMetaValues_();
}
size_t PeptideHit::getNumberOfAnalysisResultsFromMetaValues_() const
{
size_t count = 0;
std::vector<String> keys;
getKeys(keys);
for (const auto& key : keys)
{
if (key.hasPrefix("_ar_") &&
key.hasSuffix("_score_type"))
{
++count;
}
}
return count;
}
std::vector<PeptideHit::PepXMLAnalysisResult> PeptideHit::extractAnalysisResultsFromMetaValues_() const
{
std::vector<PeptideHit::PepXMLAnalysisResult> results;
std::vector<String> keys;
getKeys(keys);
// First, find all indices that have analysis results
std::set<size_t> indices;
for (const auto& key : keys)
{
const String prefix = "_ar_";
const String suffix = "_score_type";
if (key.hasPrefix(prefix) &&
key.hasSuffix(suffix))
{
String index_str = key.substr(prefix.size(), key.size() - prefix.size() - suffix.size()); // Extract index from _ar_<index>_score_type"
indices.insert(index_str.toInt());
}
}
// For each index, extract the analysis result
for (size_t index : indices)
{
PeptideHit::PepXMLAnalysisResult ar;
String prefix = "_ar_" + String(index) + "_";
// Get score type
if (metaValueExists(prefix + "score_type"))
{
ar.score_type = getMetaValue(prefix + "score_type").toString();
}
// Get main score
if (metaValueExists(prefix + "score"))
{
ar.main_score = getMetaValue(prefix + "score");
}
// Get higher_is_better flag
if (metaValueExists(prefix + "higher_is_better"))
{
ar.higher_is_better = getMetaValue(prefix + "higher_is_better").toBool();
}
// Get sub-scores
String subscore_prefix = prefix + "subscore_";
for (const auto& key : keys)
{
if (key.hasPrefix(subscore_prefix))
{
String subscore_name = key.substr(subscore_prefix.size());
ar.sub_scores[subscore_name] = getMetaValue(key);
}
}
results.push_back(ar);
}
return results;
}
// sets the rank
void PeptideHit::setRank(UInt newrank)
{
if (newrank != 0)
{
setMetaValue(Constants::UserParam::RANK, newrank);
}
else
{
// Remove the meta value if the value is the default rank
removeMetaValue(Constants::UserParam::RANK);
}
}
std::set<String> PeptideHit::extractProteinAccessionsSet() const
{
set<String> accessions;
for (const auto& ev : peptide_evidences_)
{
// don't return empty accessions
if (!ev.getProteinAccession().empty())
{
accessions.insert(ev.getProteinAccession());
}
}
return accessions;
}
std::vector<PeptideHit::PeakAnnotation>& PeptideHit::getPeakAnnotations()
{
return fragment_annotations_;
}
const std::vector<PeptideHit::PeakAnnotation>& PeptideHit::getPeakAnnotations() const
{
return fragment_annotations_;
}
void PeptideHit::setPeakAnnotations(std::vector<PeptideHit::PeakAnnotation> frag_annotations)
{
fragment_annotations_ = std::move(frag_annotations);
}
bool PeptideHit::isDecoy() const
{
return getTargetDecoyType() == TargetDecoyType::DECOY;
}
void PeptideHit::setTargetDecoyType(TargetDecoyType type)
{
switch(type)
{
case TargetDecoyType::TARGET:
setMetaValue("target_decoy", "target");
break;
case TargetDecoyType::DECOY:
setMetaValue("target_decoy", "decoy");
break;
case TargetDecoyType::TARGET_DECOY:
setMetaValue("target_decoy", "target+decoy");
break;
case TargetDecoyType::UNKNOWN:
removeMetaValue("target_decoy");
break;
}
}
PeptideHit::TargetDecoyType PeptideHit::getTargetDecoyType() const
{
if (!metaValueExists("target_decoy"))
{
return TargetDecoyType::UNKNOWN;
}
String td = getMetaValue("target_decoy").toString().toLower();
if (td == "decoy") return TargetDecoyType::DECOY;
if (td == "target+decoy") return TargetDecoyType::TARGET_DECOY;
if (td == "target") return TargetDecoyType::TARGET;
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown value of meta value 'target_decoy'", td);
}
std::ostream& operator<< (std::ostream& stream, const PeptideHit& hit)
{
return stream << "peptide hit with sequence '" + hit.getSequence().toString() +
"', charge " + String(hit.getCharge()) + ", score " +
String(hit.getScore());
}
// PeakAnnotation method implementations
bool PeptideHit::PeakAnnotation::operator<(const PeptideHit::PeakAnnotation& other) const
{
// sensible to sort first by m/z and charge
return std::tie(mz, charge, annotation, intensity) < std::tie(other.mz, other.charge, other.annotation, other.intensity);
}
bool PeptideHit::PeakAnnotation::operator==(const PeptideHit::PeakAnnotation& other) const
{
if (charge != other.charge || mz != other.mz ||
intensity != other.intensity || annotation != other.annotation) return false;
return true;
}
void PeptideHit::PeakAnnotation::writePeakAnnotationsString_(String& annotation_string, std::vector<PeptideHit::PeakAnnotation> annotations)
{
if (annotations.empty()) { return; }
// sort by mz, charge, ...
stable_sort(annotations.begin(), annotations.end());
String val;
for (auto& a : annotations)
{
annotation_string += String(a.mz) + "," + String(a.intensity) + "," + String(a.charge) + "," + String(a.annotation).quote();
if (&a != &annotations.back()) { annotation_string += "|"; }
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/IonSource.cpp | .cpp | 7,184 | 188 | // 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/METADATA/IonSource.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <algorithm>
using namespace std;
namespace OpenMS
{
const std::string IonSource::NamesOfInletType[] = {"Unknown", "Direct", "Batch", "Chromatography", "Particle beam", "Membrane sparator", "Open split", "Jet separator", "Septum", "Reservoir", "Moving belt", "Moving wire", "Flow injection analysis", "Electro spray", "Thermo spray", "Infusion", "Continuous flow fast atom bombardment", "Inductively coupled plasma", "Membrane inlet", "Nanospray inlet"};
const std::string IonSource::NamesOfIonizationMethod[] = {"Unknown", "Electrospray ionisation", "Electron ionization", "Chemical ionisation", "Fast atom bombardment", "Thermospray", "Laser desorption", "Field desorption", "Flame ionization", "Plasma desorption", "Secondary ion MS", "Thermal ionization", "Atmospheric pressure ionisation", "ISI", "Collsion induced decomposition", "Collsiona activated decomposition", "HN", "Atmospheric pressure chemical ionization", "Atmospheric pressure photo ionization", "Inductively coupled plasma", "Nano electrospray ionization", "Micro electrospray ionization", "Surface enhanced laser desorption ionization", "Surface enhanced neat desorption", "Fast ion bombardment", "Matrix-assisted laser desorption ionization", "Multiphoton ionization", "Desorption ionization", "Flowing afterglow", "Field ionization", "Glow discharge ionization", "Negative ion chemical ionization", "Neutralization reionization mass spectrometry", "Photoionization", "Pyrolysis mass spectrometry", "Resonance enhanced multiphoton ionization", "Adiabatic ionization", "Associative ionization", "Autodetachment", "Autoionization", "Charge exchange ionization", "Chemi-ionization", "Dissociative ionization", "Liquid secondary ionization", "Penning ionization", "Soft ionization", "Spark ionization", "Surface ionization", "Vertical ionization", "Atmospheric pressure matrix-assisted laser desorption ionization", "Desorption/ionization on silicon", "Surface-assisted laser desorption ionization"};
const std::string IonSource::NamesOfPolarity[] = {"unknown", "positive", "negative"};
IonSource::IonSource() :
MetaInfoInterface(),
inlet_type_(InletType::INLETNULL),
ionization_method_(IonizationMethod::IONMETHODNULL),
polarity_(Polarity::POLNULL),
order_(0)
{
}
IonSource::~IonSource() = default;
bool IonSource::operator==(const IonSource & rhs) const
{
return order_ == rhs.order_ &&
inlet_type_ == rhs.inlet_type_ &&
ionization_method_ == rhs.ionization_method_ &&
polarity_ == rhs.polarity_ &&
MetaInfoInterface::operator==(rhs);
}
bool IonSource::operator!=(const IonSource & rhs) const
{
return !(operator==(rhs));
}
IonSource::InletType IonSource::getInletType() const
{
return inlet_type_;
}
void IonSource::setInletType(IonSource::InletType inlet_type)
{
inlet_type_ = inlet_type;
}
IonSource::IonizationMethod IonSource::getIonizationMethod() const
{
return ionization_method_;
}
void IonSource::setIonizationMethod(IonSource::IonizationMethod ionization_type)
{
ionization_method_ = ionization_type;
}
IonSource::Polarity IonSource::getPolarity() const
{
return polarity_;
}
void IonSource::setPolarity(IonSource::Polarity polarity)
{
polarity_ = polarity;
}
Int IonSource::getOrder() const
{
return order_;
}
void IonSource::setOrder(Int order)
{
order_ = order;
}
StringList IonSource::getAllNamesOfInletType()
{
StringList names;
names.reserve(static_cast<size_t>(InletType::SIZE_OF_INLETTYPE));
for (size_t i = 0; i < static_cast<size_t>(InletType::SIZE_OF_INLETTYPE); ++i)
{
names.push_back(NamesOfInletType[i]);
}
return names;
}
StringList IonSource::getAllNamesOfIonizationMethod()
{
StringList names;
names.reserve(static_cast<size_t>(IonizationMethod::SIZE_OF_IONIZATIONMETHOD));
for (size_t i = 0; i < static_cast<size_t>(IonizationMethod::SIZE_OF_IONIZATIONMETHOD); ++i)
{
names.push_back(NamesOfIonizationMethod[i]);
}
return names;
}
StringList IonSource::getAllNamesOfPolarity()
{
StringList names;
names.reserve(static_cast<size_t>(Polarity::SIZE_OF_POLARITY));
for (size_t i = 0; i < static_cast<size_t>(Polarity::SIZE_OF_POLARITY); ++i)
{
names.push_back(NamesOfPolarity[i]);
}
return names;
}
const std::string& IonSource::inletTypeToString(InletType type)
{
if (type == InletType::SIZE_OF_INLETTYPE)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_INLETTYPE");
}
return NamesOfInletType[static_cast<size_t>(type)];
}
IonSource::InletType IonSource::toInletType(const std::string& name)
{
auto first = &NamesOfInletType[0];
auto last = &NamesOfInletType[static_cast<size_t>(InletType::SIZE_OF_INLETTYPE)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<InletType>(it - first);
}
const std::string& IonSource::ionizationMethodToString(IonizationMethod method)
{
if (method == IonizationMethod::SIZE_OF_IONIZATIONMETHOD)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_IONIZATIONMETHOD");
}
return NamesOfIonizationMethod[static_cast<size_t>(method)];
}
IonSource::IonizationMethod IonSource::toIonizationMethod(const std::string& name)
{
auto first = &NamesOfIonizationMethod[0];
auto last = &NamesOfIonizationMethod[static_cast<size_t>(IonizationMethod::SIZE_OF_IONIZATIONMETHOD)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<IonizationMethod>(it - first);
}
const std::string& IonSource::polarityToString(Polarity polarity)
{
if (polarity == Polarity::SIZE_OF_POLARITY)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_POLARITY");
}
return NamesOfPolarity[static_cast<size_t>(polarity)];
}
IonSource::Polarity IonSource::toPolarity(const std::string& name)
{
auto first = &NamesOfPolarity[0];
auto last = &NamesOfPolarity[static_cast<size_t>(Polarity::SIZE_OF_POLARITY)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<Polarity>(it - first);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ChromatogramSettings.cpp | .cpp | 5,490 | 192 | // 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/METADATA/ChromatogramSettings.h>
#include <OpenMS/CONCEPT/Helpers.h>
#include <boost/iterator/indirect_iterator.hpp> // for equality
using namespace std;
namespace OpenMS
{
// keep this in sync with enum ChromatogramType
const char * const ChromatogramSettings::ChromatogramNames[] = {"mass chromatogram", "total ion current chromatogram", "selected ion current chromatogram" ,"base peak chromatogram",
"selected ion monitoring chromatogram" ,"selected reaction monitoring chromatogram" ,"electromagnetic radiation chromatogram",
"absorption chromatogram", "emission chromatogram", "unknown chromatogram"}; // last entry should be "unknown", since this is the default in FileInfo.cpp
ChromatogramSettings::ChromatogramSettings() :
MetaInfoInterface(),
native_id_(),
comment_(),
instrument_settings_(),
source_file_(),
acquisition_info_(),
precursor_(),
product_(),
data_processing_(),
type_(ChromatogramType::MASS_CHROMATOGRAM)
{
}
ChromatogramSettings::~ChromatogramSettings() = default;
bool ChromatogramSettings::operator==(const ChromatogramSettings & rhs) const
{
return MetaInfoInterface::operator==(rhs) &&
native_id_ == rhs.native_id_ &&
comment_ == rhs.comment_ &&
instrument_settings_ == rhs.instrument_settings_ &&
acquisition_info_ == rhs.acquisition_info_ &&
source_file_ == rhs.source_file_ &&
precursor_ == rhs.precursor_ &&
product_ == rhs.product_ &&
// We are not interested whether the pointers are equal but whether
// the contents are equal
( data_processing_.size() == rhs.data_processing_.size() &&
std::equal( boost::make_indirect_iterator(data_processing_.begin()),
boost::make_indirect_iterator(data_processing_.end()),
boost::make_indirect_iterator(rhs.data_processing_.begin()) ) ) &&
type_ == rhs.type_;
}
bool ChromatogramSettings::operator!=(const ChromatogramSettings & rhs) const
{
return !(operator==(rhs));
}
const String & ChromatogramSettings::getComment() const
{
return comment_;
}
void ChromatogramSettings::setComment(const String & comment)
{
comment_ = comment;
}
const InstrumentSettings & ChromatogramSettings::getInstrumentSettings() const
{
return instrument_settings_;
}
InstrumentSettings & ChromatogramSettings::getInstrumentSettings()
{
return instrument_settings_;
}
void ChromatogramSettings::setInstrumentSettings(const InstrumentSettings & instrument_settings)
{
instrument_settings_ = instrument_settings;
}
const AcquisitionInfo & ChromatogramSettings::getAcquisitionInfo() const
{
return acquisition_info_;
}
AcquisitionInfo & ChromatogramSettings::getAcquisitionInfo()
{
return acquisition_info_;
}
void ChromatogramSettings::setAcquisitionInfo(const AcquisitionInfo & acquisition_info)
{
acquisition_info_ = acquisition_info;
}
const SourceFile & ChromatogramSettings::getSourceFile() const
{
return source_file_;
}
SourceFile & ChromatogramSettings::getSourceFile()
{
return source_file_;
}
void ChromatogramSettings::setSourceFile(const SourceFile & source_file)
{
source_file_ = source_file;
}
const Precursor & ChromatogramSettings::getPrecursor() const
{
return precursor_;
}
Precursor & ChromatogramSettings::getPrecursor()
{
return precursor_;
}
void ChromatogramSettings::setPrecursor(const Precursor & precursor)
{
precursor_ = precursor;
}
const Product & ChromatogramSettings::getProduct() const
{
return product_;
}
Product & ChromatogramSettings::getProduct()
{
return product_;
}
void ChromatogramSettings::setProduct(const Product & product)
{
product_ = product;
}
std::ostream & operator<<(std::ostream & os, const ChromatogramSettings & /*spec*/)
{
os << "-- CHROMATOGRAMSETTINGS BEGIN --" << std::endl;
os << "-- CHROMATOGRAMSETTINGS END --" << std::endl;
return os;
}
const String & ChromatogramSettings::getNativeID() const
{
return native_id_;
}
void ChromatogramSettings::setNativeID(const String & native_id)
{
native_id_ = native_id;
}
ChromatogramSettings::ChromatogramType ChromatogramSettings::getChromatogramType() const
{
return type_;
}
void ChromatogramSettings::setChromatogramType(ChromatogramType type)
{
type_ = type;
}
void ChromatogramSettings::setDataProcessing(const std::vector< DataProcessingPtr > & data_processing)
{
data_processing_ = data_processing;
}
std::vector< DataProcessingPtr > & ChromatogramSettings::getDataProcessing()
{
return data_processing_;
}
const std::vector< std::shared_ptr<const DataProcessing > > ChromatogramSettings::getDataProcessing() const
{
return OpenMS::Helpers::constifyPointerVector(data_processing_);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/DataProcessing.cpp | .cpp | 3,990 | 140 | // 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/METADATA/DataProcessing.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <algorithm>
using namespace std;
namespace OpenMS
{
const std::string DataProcessing::NamesOfProcessingAction[] =
{
"Data processing action",
"Charge deconvolution",
"Deisotoping",
"Smoothing",
"Charge calculation",
"Precursor recalculation",
"Baseline reduction",
"Peak picking",
"Retention time alignment",
"Calibration of m/z positions",
"Intensity normalization",
"Data filtering",
"Quantitation",
"Feature grouping",
"Identification mapping",
"File format conversion",
"Conversion to mzData format",
"Conversion to mzML format",
"Conversion to mzXML format",
"Conversion to DTA format",
"Identification",
"Ion mobility binning"
};
DataProcessing::~DataProcessing() = default;
DataProcessing::DataProcessing(DataProcessing&& rhs) noexcept :
MetaInfoInterface(std::move(rhs)),
software_(std::move(rhs.software_)),
processing_actions_(std::move(rhs.processing_actions_)),
completion_time_(std::move(rhs.completion_time_))
{
}
bool DataProcessing::operator==(const DataProcessing& rhs) const
{
return software_ == rhs.software_ &&
processing_actions_ == rhs.processing_actions_ &&
completion_time_ == rhs.completion_time_ &&
MetaInfoInterface::operator==(rhs);
}
bool DataProcessing::operator!=(const DataProcessing& rhs) const
{
return !(operator==(rhs));
}
const Software& DataProcessing::getSoftware() const
{
return software_;
}
Software& DataProcessing::getSoftware()
{
return software_;
}
void DataProcessing::setSoftware(const Software& software)
{
software_ = software;
}
const DateTime& DataProcessing::getCompletionTime() const
{
return completion_time_;
}
void DataProcessing::setCompletionTime(const DateTime& completion_time)
{
completion_time_ = completion_time;
}
const set<DataProcessing::ProcessingAction>& DataProcessing::getProcessingActions() const
{
return processing_actions_;
}
set<DataProcessing::ProcessingAction>& DataProcessing::getProcessingActions()
{
return processing_actions_;
}
void DataProcessing::setProcessingActions(const set<DataProcessing::ProcessingAction>& processing_actions)
{
processing_actions_ = processing_actions;
}
StringList DataProcessing::getAllNamesOfProcessingAction()
{
StringList names;
names.reserve(static_cast<size_t>(ProcessingAction::SIZE_OF_PROCESSINGACTION));
for (size_t i = 0; i < static_cast<size_t>(ProcessingAction::SIZE_OF_PROCESSINGACTION); ++i)
{
names.push_back(NamesOfProcessingAction[i]);
}
return names;
}
const std::string& DataProcessing::processingActionToString(ProcessingAction action)
{
if (action == ProcessingAction::SIZE_OF_PROCESSINGACTION)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_PROCESSINGACTION");
}
return NamesOfProcessingAction[static_cast<size_t>(action)];
}
DataProcessing::ProcessingAction DataProcessing::toProcessingAction(const std::string& name)
{
auto first = &NamesOfProcessingAction[0];
auto last = &NamesOfProcessingAction[static_cast<size_t>(ProcessingAction::SIZE_OF_PROCESSINGACTION)];
const auto it = std::find(first, last, name);
if (it == last)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value unknown", name);
}
return static_cast<ProcessingAction>(it - first);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/Precursor.cpp | .cpp | 9,526 | 315 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/METADATA/Precursor.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <algorithm>
using namespace std;
namespace OpenMS
{
const std::string Precursor::NamesOfActivationMethod[static_cast<size_t>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD)] = {
"Collision-induced dissociation",
"Post-source decay",
"Plasma desorption",
"Surface-induced dissociation",
"Blackbody infrared radiative dissociation",
"Electron capture dissociation",
"Infrared multiphoton dissociation",
"Sustained off-resonance irradiation",
"High-energy collision-induced dissociation",
"Low-energy collision-induced dissociation",
"Photodissociation",
"Electron transfer dissociation",
"Electron transfer and collision-induced dissociation",
"Electron transfer and higher-energy collision dissociation",
"Pulsed q dissociation",
"trap-type collision-induced dissociation",
"beam-type collision-induced dissociation", // == HCD
"in-source collision-induced dissociation",
"Bruker proprietary method"
};
const std::string Precursor::NamesOfActivationMethodShort[static_cast<size_t>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD)] = {
"CID",
"PSD",
"PD",
"SID",
"BIRD",
"ECD",
"IMD",
"SORI",
"HCID",
"LCID",
"PHD",
"ETD",
"ETciD",
"EThcD",
"PQD",
"TRAP",
"HCD",
"INSOURCE",
"LIFT"
};
// Compile-time assertions to ensure array sizes match enum size
static_assert(sizeof(Precursor::NamesOfActivationMethod) / sizeof(Precursor::NamesOfActivationMethod[0]) ==
static_cast<size_t>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD),
"NamesOfActivationMethod array size must match ActivationMethod enum size");
static_assert(sizeof(Precursor::NamesOfActivationMethodShort) / sizeof(Precursor::NamesOfActivationMethodShort[0]) ==
static_cast<size_t>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD),
"NamesOfActivationMethodShort array size must match ActivationMethod enum size");
Precursor::Precursor(Precursor&& rhs) noexcept :
CVTermList(std::move(rhs)),
Peak1D(std::move(rhs)),
activation_methods_(std::move(rhs.activation_methods_)),
activation_energy_(rhs.activation_energy_),
window_low_(rhs.window_low_),
window_up_(rhs.window_up_),
drift_time_(rhs.drift_time_),
drift_window_low_(rhs.drift_window_low_),
drift_window_up_(rhs.drift_window_up_),
drift_time_unit_(rhs.drift_time_unit_),
charge_(rhs.charge_),
possible_charge_states_(std::move(rhs.possible_charge_states_))
{
}
bool Precursor::operator==(const Precursor& rhs) const
{
return activation_methods_ == rhs.activation_methods_ &&
activation_energy_ == rhs.activation_energy_ &&
window_low_ == rhs.window_low_ &&
window_up_ == rhs.window_up_ &&
drift_time_ == rhs.drift_time_ &&
drift_window_up_ == rhs.drift_window_up_ &&
drift_window_low_ == rhs.drift_window_low_ &&
drift_time_unit_ == rhs.drift_time_unit_ &&
charge_ == rhs.charge_ &&
possible_charge_states_ == rhs.possible_charge_states_ &&
Peak1D::operator==(rhs) &&
CVTermList::operator==(rhs);
}
bool Precursor::operator!=(const Precursor& rhs) const
{
return !(operator==(rhs));
}
const set<Precursor::ActivationMethod>& Precursor::getActivationMethods() const
{
return activation_methods_;
}
set<Precursor::ActivationMethod>& Precursor::getActivationMethods()
{
return activation_methods_;
}
StringList Precursor::getActivationMethodsAsString() const
{
StringList am;
am.reserve(activation_methods_.size());
for (const auto& m : activation_methods_)
{
am.push_back(NamesOfActivationMethod[static_cast<size_t>(m)]);
}
return am;
}
StringList Precursor::getActivationMethodsAsShortString() const
{
StringList am;
am.reserve(activation_methods_.size());
for (const auto& m : activation_methods_)
{
am.push_back(NamesOfActivationMethodShort[static_cast<size_t>(m)]);
}
return am;
}
StringList Precursor::getAllNamesOfActivationMethods()
{
StringList am;
am.reserve(static_cast<size_t>(ActivationMethod::SIZE_OF_ACTIVATIONMETHOD));
for (size_t i = 0; i < static_cast<size_t>(ActivationMethod::SIZE_OF_ACTIVATIONMETHOD); ++i)
{
am.push_back(NamesOfActivationMethod[i]);
}
return am;
}
StringList Precursor::getAllShortNamesOfActivationMethods()
{
StringList am;
am.reserve(static_cast<size_t>(ActivationMethod::SIZE_OF_ACTIVATIONMETHOD));
for (size_t i = 0; i < static_cast<size_t>(ActivationMethod::SIZE_OF_ACTIVATIONMETHOD); ++i)
{
am.push_back(NamesOfActivationMethodShort[i]);
}
return am;
}
const std::string& Precursor::activationMethodToString(ActivationMethod m)
{
if (m == ActivationMethod::SIZE_OF_ACTIVATIONMETHOD)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_ACTIVATIONMETHOD");
}
return NamesOfActivationMethod[static_cast<size_t>(m)];
}
const std::string& Precursor::activationMethodToShortString(ActivationMethod m)
{
if (m == ActivationMethod::SIZE_OF_ACTIVATIONMETHOD)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value not allowed", "SIZE_OF_ACTIVATIONMETHOD");
}
return NamesOfActivationMethodShort[static_cast<size_t>(m)];
}
Precursor::ActivationMethod Precursor::toActivationMethod(const std::string& name)
{
// Search in full names
auto first_full = &NamesOfActivationMethod[0];
auto last_full = &NamesOfActivationMethod[static_cast<size_t>(ActivationMethod::SIZE_OF_ACTIVATIONMETHOD)];
auto it_full = std::find(first_full, last_full, name);
if (it_full != last_full)
{
return static_cast<ActivationMethod>(it_full - first_full);
}
// Search in short names
auto first_short = &NamesOfActivationMethodShort[0];
auto last_short = &NamesOfActivationMethodShort[static_cast<size_t>(ActivationMethod::SIZE_OF_ACTIVATIONMETHOD)];
auto it_short = std::find(first_short, last_short, name);
if (it_short != last_short)
{
return static_cast<ActivationMethod>(it_short - first_short);
}
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown activation method", name);
}
void Precursor::setActivationMethods(const set<Precursor::ActivationMethod> & activation_methods)
{
activation_methods_ = activation_methods;
}
double Precursor::getActivationEnergy() const
{
return activation_energy_;
}
void Precursor::setActivationEnergy(double activation_energy)
{
activation_energy_ = activation_energy;
}
double Precursor::getIsolationWindowLowerOffset() const
{
return window_low_;
}
void Precursor::setIsolationWindowLowerOffset(double bound)
{
if (bound < 0)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Precursor::setIsolationWindowLowerOffset() received a negative lower offset", String(bound));
}
window_low_ = bound;
}
double Precursor::getIsolationWindowUpperOffset() const
{
return window_up_;
}
void Precursor::setIsolationWindowUpperOffset(double bound)
{
if (bound < 0)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Precursor::setIsolationWindowUpperOffset() received a negative lower offset", String(bound));
}
window_up_ = bound;
}
double Precursor::getDriftTime() const
{
return drift_time_;
}
void Precursor::setDriftTime(double drift_time)
{
drift_time_ = drift_time;
}
DriftTimeUnit Precursor::getDriftTimeUnit() const
{
return drift_time_unit_;
}
void Precursor::setDriftTimeUnit(DriftTimeUnit dt)
{
drift_time_unit_ = dt;
}
double Precursor::getDriftTimeWindowLowerOffset() const
{
return drift_window_low_;
}
void Precursor::setDriftTimeWindowLowerOffset(double bound)
{
OPENMS_PRECONDITION(bound >= 0, "Relative drift time offset needs to be positive.")
drift_window_low_ = bound;
}
double Precursor::getDriftTimeWindowUpperOffset() const
{
return drift_window_up_;
}
void Precursor::setDriftTimeWindowUpperOffset(double bound)
{
OPENMS_PRECONDITION(bound >= 0, "Relative drift time offset needs to be positive.")
drift_window_up_ = bound;
}
Int Precursor::getCharge() const
{
return charge_;
}
void Precursor::setCharge(Int charge)
{
charge_ = charge;
}
std::vector<Int> & Precursor::getPossibleChargeStates()
{
return possible_charge_states_;
}
const std::vector<Int> & Precursor::getPossibleChargeStates() const
{
return possible_charge_states_;
}
void Precursor::setPossibleChargeStates(const std::vector<Int> & possible_charge_states)
{
possible_charge_states_ = possible_charge_states;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/PeptideEvidence.cpp | .cpp | 3,019 | 140 | // 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/METADATA/PeptideEvidence.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
namespace OpenMS
{
const int PeptideEvidence::UNKNOWN_POSITION = -1;
const int PeptideEvidence::N_TERMINAL_POSITION = 0;
const char PeptideEvidence::UNKNOWN_AA = 'X';
const char PeptideEvidence::N_TERMINAL_AA = '[';
const char PeptideEvidence::C_TERMINAL_AA = ']';
PeptideEvidence::PeptideEvidence()
: accession_(),
start_(UNKNOWN_POSITION),
end_(UNKNOWN_POSITION),
aa_before_(UNKNOWN_AA),
aa_after_(UNKNOWN_AA)
{
}
PeptideEvidence::PeptideEvidence(const String& accession, Int start, Int end, char aa_before, char aa_after) :
accession_(accession),
start_(start),
end_(end),
aa_before_(aa_before),
aa_after_(aa_after)
{
}
bool PeptideEvidence::operator==(const PeptideEvidence& rhs) const
{
return accession_ == rhs.accession_ &&
start_ == rhs.start_ &&
end_ == rhs.end_ &&
aa_before_ == rhs.aa_before_ &&
aa_after_ == rhs.aa_after_;
}
bool PeptideEvidence::operator<(const PeptideEvidence& rhs) const
{
if (accession_ != rhs.accession_)
{
return accession_ < rhs.accession_;
}
if (start_ != rhs.start_)
{
return start_ < rhs.start_;
}
if (end_ != rhs.end_)
{
return end_ < rhs.end_;
}
if (aa_before_ != rhs.aa_before_)
{
return aa_before_ < rhs.aa_before_;
}
if (aa_after_ != rhs.aa_after_)
{
return aa_after_ < rhs.aa_after_;
}
return false;
}
bool PeptideEvidence::operator!=(const PeptideEvidence& rhs) const
{
return !operator==(rhs);
}
bool PeptideEvidence::hasValidLimits() const
{
return !(
getStart() == UNKNOWN_POSITION ||
getEnd() == UNKNOWN_POSITION ||
getEnd() == N_TERMINAL_POSITION);
}
void PeptideEvidence::setProteinAccession(const String& s)
{
accession_ = s;
}
const String& PeptideEvidence::getProteinAccession() const
{
return accession_;
}
void PeptideEvidence::setStart(const Int a)
{
start_ = a;
}
Int PeptideEvidence::getStart() const
{
return start_;
}
void PeptideEvidence::setEnd(const Int a)
{
end_ = a;
}
Int PeptideEvidence::getEnd() const
{
return end_;
}
void PeptideEvidence::setAABefore(const char acid)
{
aa_before_ = acid;
}
char PeptideEvidence::getAABefore() const
{
return aa_before_;
}
void PeptideEvidence::setAAAfter(const char acid)
{
aa_after_ = acid;
}
char PeptideEvidence::getAAAfter() const
{
return aa_after_;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/PeptideIdentificationList.cpp | .cpp | 432 | 14 | // 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/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/MetaInfoInterface.cpp | .cpp | 5,644 | 272 | // 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/METADATA/MetaInfoInterface.h>
#include <OpenMS/METADATA/MetaInfo.h>
using namespace std;
namespace OpenMS
{
/// Copy constructor
MetaInfoInterface::MetaInfoInterface(const MetaInfoInterface& rhs) :
meta_(nullptr)
{
if (rhs.meta_ != nullptr)
{
meta_ = new MetaInfo(*(rhs.meta_));
}
}
/// Move constructor
MetaInfoInterface::MetaInfoInterface(MetaInfoInterface&& rhs) noexcept :
meta_(std::move(rhs.meta_))
{
// take ownership
rhs.meta_ = nullptr;
}
MetaInfoInterface::~MetaInfoInterface()
{
delete(meta_);
}
MetaInfoInterface& MetaInfoInterface::operator=(const MetaInfoInterface& rhs)
{
if (this == &rhs)
{
return *this;
}
if (rhs.meta_ != nullptr && meta_ != nullptr)
{
*meta_ = *(rhs.meta_);
}
else if (rhs.meta_ == nullptr && meta_ != nullptr)
{
delete(meta_);
meta_ = nullptr;
}
else if (rhs.meta_ != nullptr && meta_ == nullptr)
{
meta_ = new MetaInfo(*(rhs.meta_));
}
return *this;
}
// Move assignment
MetaInfoInterface& MetaInfoInterface::operator=(MetaInfoInterface&& rhs) noexcept
{
if (this == &rhs)
{
return *this;
}
// free memory and assign rhs memory
delete(meta_);
meta_ = rhs.meta_;
rhs.meta_ = nullptr;
return *this;
}
void MetaInfoInterface::swap(MetaInfoInterface& rhs)
{
std::swap(meta_, rhs.meta_);
// MetaInfo* temp = meta_;
// meta_ = rhs.meta_;
// rhs.meta_ = temp;
}
bool MetaInfoInterface::operator==(const MetaInfoInterface& rhs) const
{
if (rhs.meta_ == nullptr && meta_ == nullptr)
{
return true;
}
else if (rhs.meta_ == nullptr && meta_ != nullptr)
{
if (meta_->empty())
{
return true;
}
return false;
}
else if (rhs.meta_ != nullptr && meta_ == nullptr)
{
if (rhs.meta_->empty())
{
return true;
}
return false;
}
return *meta_ == *(rhs.meta_);
}
bool MetaInfoInterface::operator!=(const MetaInfoInterface& rhs) const
{
return !(operator==(rhs));
}
const DataValue& MetaInfoInterface::getMetaValue(const String& name) const
{
if (meta_ == nullptr)
{
return DataValue::EMPTY;
}
return meta_->getValue(name, DataValue::EMPTY);
}
DataValue MetaInfoInterface::getMetaValue(const String& name, const DataValue& default_value) const
{
if (meta_ == nullptr)
{
return default_value;
}
return meta_->getValue(name, default_value);
}
const DataValue& MetaInfoInterface::getMetaValue(UInt index) const
{
if (meta_ == nullptr)
{
return DataValue::EMPTY;
}
return meta_->getValue(index, DataValue::EMPTY);
}
DataValue MetaInfoInterface::getMetaValue(UInt index, const DataValue& default_value) const
{
if (meta_ == nullptr)
{
return default_value;
}
return meta_->getValue(index, default_value);
}
bool MetaInfoInterface::metaValueExists(const String& name) const
{
if (meta_ == nullptr)
{
return false;
}
return meta_->exists(name);
}
bool MetaInfoInterface::metaValueExists(UInt index) const
{
if (meta_ == nullptr)
{
return false;
}
return meta_->exists(index);
}
void MetaInfoInterface::setMetaValue(const String& name, const DataValue& value)
{
createIfNotExists_();
meta_->setValue(name, value);
}
void MetaInfoInterface::setMetaValue(UInt index, const DataValue& value)
{
createIfNotExists_();
meta_->setValue(index, value);
}
MetaInfoRegistry& MetaInfoInterface::metaRegistry()
{
return MetaInfo::registry();
}
void MetaInfoInterface::createIfNotExists_()
{
if (meta_ == nullptr)
{
meta_ = new MetaInfo();
}
}
void MetaInfoInterface::getKeys(std::vector<String>& keys) const
{
if (meta_ != nullptr)
{
meta_->getKeys(keys);
}
}
void MetaInfoInterface::getKeys(std::vector<UInt>& keys) const
{
if (meta_ != nullptr)
{
meta_->getKeys(keys);
}
}
bool MetaInfoInterface::isMetaEmpty() const
{
if (meta_ == nullptr)
{
return true;
}
return meta_->empty();
}
void MetaInfoInterface::clearMetaInfo()
{
delete meta_;
meta_ = nullptr;
}
void MetaInfoInterface::removeMetaValue(const String& name)
{
if (meta_ != nullptr)
{
meta_->removeValue(name);
}
}
void MetaInfoInterface::removeMetaValue(UInt index)
{
if (meta_ != nullptr)
{
meta_->removeValue(index);
}
}
void MetaInfoInterface::addMetaValues(const MetaInfoInterface& from)
{
if (from.meta_ == nullptr || from.meta_->empty())
{
return;
}
createIfNotExists_();
*meta_ += *(from.meta_);
}
MetaInfoInterface::MetaInfoConstIterator MetaInfoInterface::metaBegin() const
{
static const MetaInfo empty;
return meta_ ? meta_->begin() : empty.begin();
}
MetaInfoInterface::MetaInfoConstIterator MetaInfoInterface::metaEnd() const
{
static const MetaInfo empty;
return meta_ ? meta_->end() : empty.end();
}
Size MetaInfoInterface::metaSize() const
{
return meta_ ? meta_->size() : 0;
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ExperimentalDesign.cpp | .cpp | 30,176 | 853 | // 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/METADATA/ExperimentalDesign.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <QtCore/QString>
#include <QtCore/QFileInfo>
#include <algorithm>
#include <iostream>
using namespace std;
namespace OpenMS
{
using MSFileSection = std::vector<ExperimentalDesign::MSFileSection>;
ExperimentalDesign::SampleSection::SampleSection(
const std::vector< std::vector < String > >& content,
const std::map< String, Size >& sample_to_rowindex,
const std::map< String, Size >& columnname_to_columnindex
) :
content_(content),
sample_to_rowindex_(sample_to_rowindex),
columnname_to_columnindex_(columnname_to_columnindex)
{
}
ExperimentalDesign::ExperimentalDesign(
const ExperimentalDesign::MSFileSection& msfile_section,
const ExperimentalDesign::SampleSection& sample_section) :
msfile_section_(msfile_section),
sample_section_(sample_section)
{
sort_();
isValid_();
}
ExperimentalDesign ExperimentalDesign::fromConsensusMap(const ConsensusMap &cm)
{
ExperimentalDesign experimental_design;
// one of label-free, labeled_MS1, labeled_MS2
const String & experiment_type = cm.getExperimentType();
// path of the original MS run (mzML / raw file)
StringList ms_run_paths;
cm.getPrimaryMSRunPath(ms_run_paths);
// Note: consensus elements of the same fraction group corresponds to one sample abundance
ExperimentalDesign::MSFileSection msfile_section;
ExperimentalDesign::SampleSection sample_section;
// determine vector of ms file names (in order of appearance)
vector<String> msfiles;
std::map<pair<UInt,UInt>, UInt> fractiongroup_label_to_sample_mapping;
std::map<String, UInt> samplename_to_sample_mapping;
for (const auto &f : cm.getColumnHeaders())
{
if (std::find(msfiles.begin(), msfiles.end(), f.second.filename) == msfiles.end())
{
msfiles.push_back(f.second.filename);
}
}
bool no_fractions = true;
for (const auto &f : cm.getColumnHeaders())
{
ExperimentalDesign::MSFileSectionEntry r;
r.path = f.second.filename;
if (f.second.metaValueExists("fraction"))
{
no_fractions = false;
r.fraction = static_cast<unsigned int>(f.second.getMetaValue("fraction"));
if (f.second.metaValueExists("fraction_group"))
{
r.fraction_group = static_cast<unsigned int>(f.second.getMetaValue("fraction_group"));
}
else
{
// if we have annotated fractions, we need to also know how these are grouped
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Fractions annotated but no grouping provided.");
}
}
else
{ // no fractions and fraction group information annotated, deduce from data
r.fraction = 1;
// no fractions -> one fraction group for each MS file
// to create a unique group identifier [1..n], we take the index of the (unique) filenames
r.fraction_group = (std::find(msfiles.begin(), msfiles.end(), f.second.filename)
- msfiles.begin()) + 1;
}
if (no_fractions) OPENMS_LOG_INFO << "No fractions annotated in consensusXML. Assuming unfractionated." << endl;
r.label = f.second.getLabelAsUInt(experiment_type);
if (!f.second.metaValueExists("sample_name"))
{
// We create one sample for each fractiongroup/label combination
// this assumes that fractionation took place after labelling. Otherwise, a design needs to be given.
// check fractiongroup_label_to_sample_mapping and add if not present, otherwise use present
auto key = make_pair(r.fraction_group, r.label);
auto it = fractiongroup_label_to_sample_mapping.emplace(key, fractiongroup_label_to_sample_mapping.size());
r.sample = it.first->second;
r.sample_name = r.sample;
} else {
r.sample_name = f.second.getMetaValue("sample_name");
[[maybe_unused]] const auto& [it, inserted] = samplename_to_sample_mapping.emplace(r.sample_name,samplename_to_sample_mapping.size());
r.sample = it->second;
}
msfile_section.push_back(r);
if (!sample_section.hasSample(r.sample))
sample_section.addSample(r.sample);
}
experimental_design.setMSFileSection(msfile_section);
experimental_design.setSampleSection(sample_section);
OPENMS_LOG_DEBUG << "Experimental design (ConsensusMap derived):\n"
<< " Files: " << experimental_design.getNumberOfMSFiles()
<< " Fractions: " << experimental_design.getNumberOfFractions()
<< " Labels: " << experimental_design.getNumberOfLabels()
<< " Samples: " << experimental_design.getNumberOfSamples() << "\n"
<< endl;
return experimental_design;
}
void ExperimentalDesign::SampleSection::addSample(const String& samplename, const vector<String>& content)
{
//TODO warn when already present? Overwrite?
//TODO check content size
sample_to_rowindex_.try_emplace(samplename, sample_to_rowindex_.size());
content_.push_back(content);
}
String ExperimentalDesign::SampleSection::getSampleName(unsigned sample_row) const
{
return content_.at(sample_row).at(columnname_to_columnindex_.at("Sample"));
}
unsigned ExperimentalDesign::SampleSection::getSampleRow(const String& sample) const
{
return sample_to_rowindex_.at(sample);
}
ExperimentalDesign ExperimentalDesign::fromFeatureMap(const FeatureMap &fm)
{
ExperimentalDesign experimental_design;
// path of the original MS run (mzML / raw file)
StringList ms_paths;
fm.getPrimaryMSRunPath(ms_paths);
if (ms_paths.size() != 1)
{
throw Exception::MissingInformation(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"FeatureMap annotated with " + String(ms_paths.size()) + " MS files. Must be exactly one.");
}
// Feature map is simple. One file, one fraction, one sample, one fraction_group
ExperimentalDesign::MSFileSectionEntry r;
r.path = ms_paths[0];
r.fraction = 1;
r.sample = 0;
r.sample_name = "0";
r.fraction_group = 1;
r.label = 1;
ExperimentalDesign::MSFileSection rows(1, r);
ExperimentalDesign::SampleSection s;
s.addSample(r.sample_name);
experimental_design.setMSFileSection(rows);
experimental_design.setSampleSection(s);
OPENMS_LOG_INFO << "Experimental design (FeatureMap derived):\n"
<< " files: " << experimental_design.getNumberOfMSFiles()
<< " fractions: " << experimental_design.getNumberOfFractions()
<< " labels: " << experimental_design.getNumberOfLabels()
<< " samples: " << experimental_design.getNumberOfSamples() << "\n"
<< endl;
return experimental_design;
}
ExperimentalDesign ExperimentalDesign::fromIdentifications(const vector <ProteinIdentification> &proteins)
{
ExperimentalDesign experimental_design;
// path of the original MS files (mzML / raw file)
StringList ms_run_paths;
for (const auto &protein : proteins)
{
// Due to merging it is valid to have multiple origins in a ProteinIDRun
StringList tmp_ms_run_paths;
protein.getPrimaryMSRunPath(tmp_ms_run_paths);
ms_run_paths.insert(ms_run_paths.end(), tmp_ms_run_paths.begin(), tmp_ms_run_paths.end());
//TODO think about uniquifying or warning if duplicates occur
}
// For now and without further info we have to assume a labelfree, unfractionated experiment
// no fractionation -> as many fraction_groups as samples
// each identification run corresponds to one sample abundance
unsigned sample(0);
ExperimentalDesign::MSFileSection rows;
ExperimentalDesign::SampleSection srows;
for (const auto &f : ms_run_paths)
{
ExperimentalDesign::MSFileSectionEntry r;
r.path = f;
r.fraction = 1;
r.sample = sample;
r.sample_name = String(sample);
r.fraction_group = sample;
r.label = 1;
rows.push_back(r);
srows.addSample(String(sample));
++sample;
}
experimental_design.setMSFileSection(rows);
experimental_design.setSampleSection(srows);
OPENMS_LOG_INFO << "Experimental design (Identification derived):\n"
<< " files: " << experimental_design.getNumberOfMSFiles()
<< " fractions: " << experimental_design.getNumberOfFractions()
<< " labels: " << experimental_design.getNumberOfLabels()
<< " samples: " << experimental_design.getNumberOfSamples() << "\n"
<< endl;
return experimental_design;
}
map<unsigned, vector<String> > ExperimentalDesign::getFractionToMSFilesMapping() const
{
map<unsigned, vector<String> > ret;
for (MSFileSectionEntry const& r : msfile_section_)
{
ret[r.fraction].emplace_back(r.path);
}
return ret;
}
map<pair<String, unsigned>, unsigned> ExperimentalDesign::pathLabelMapper_(
const bool basename,
unsigned (*f)(const ExperimentalDesign::MSFileSectionEntry &entry)) const
{
map<pair<String, unsigned>, unsigned> ret;
for (MSFileSectionEntry const& r : msfile_section_)
{
const String path = String(r.path);
pair<String, unsigned> tpl = make_pair((basename ? File::basename(path) : path), r.label);
ret[tpl] = f(r);
}
return ret;
}
map<vector<String>, set<String>> ExperimentalDesign::getUniqueSampleRowToSampleMapping() const
{
map<vector<String>, set<String> > rowContent2RowIdx;
auto factors = sample_section_.getFactors();
assert(!factors.empty());
factors.erase("Sample"); // we do not care about ID in duplicates
for (const String& u : sample_section_.getSamples())
{
std::vector<String> valuesToHash{};
valuesToHash.reserve(factors.size());
for (const String& fac : factors)
{
valuesToHash.emplace_back(sample_section_.getFactorValue(u, fac));
}
auto emplace_pair = rowContent2RowIdx.emplace(valuesToHash, set<String>{});
emplace_pair.first->second.insert(u);
}
return rowContent2RowIdx;
}
map<String, unsigned> ExperimentalDesign::getSampleToPrefractionationMapping() const
{
map<String, unsigned> res;
// could happen when the Experimental Design was loaded from an idXML or consensusXML
// without additional Experimental Design file
if (sample_section_.getFactors().empty())
{
// no information about the origin of the samples -> assume uniqueness of all
Size i(0);
for (const auto& s : sample_section_.getSamples())
{
res[s] = i;
i++;
}
}
else
{
const map<vector<String>, set<String>>& rowContent2RowIdx = getUniqueSampleRowToSampleMapping();
Size s(0);
for (const auto &condition : rowContent2RowIdx)
{
for (auto &sample : condition.second)
{
res.emplace(sample, s);
}
++s;
}
}
return res;
}
map<vector<String>, set<unsigned>> ExperimentalDesign::getConditionToSampleMapping() const
{
const auto& facset = sample_section_.getFactors();
// assert(!facset.empty()); // not needed: If no factors are given, same condition is assumed for every run
set<String> nonRepFacs{};
for (const String& fac : facset)
{
if (fac != "Sample" && !fac.hasSubstring("replicate") && !fac.hasSubstring("Replicate"))
{
nonRepFacs.insert(fac);
}
}
map<vector<String>, set<unsigned> > rowContent2RowIdx;
for (const auto& u : sample_section_.getSamples())
{
std::vector<String> valuesToHash{};
valuesToHash.reserve(nonRepFacs.size());
for (const String& fac : nonRepFacs)
{
valuesToHash.emplace_back(sample_section_.getFactorValue(u, fac));
}
auto emplace_pair = rowContent2RowIdx.emplace(valuesToHash, set<unsigned>{});
emplace_pair.first->second.insert(sample_section_.getSampleRow(u));
}
return rowContent2RowIdx;
}
map<String, unsigned> ExperimentalDesign::getSampleToConditionMapping() const
{
map<String, unsigned> res;
// could happen when the Experimental Design was loaded from an idXML or consensusXML
// without additional Experimental Design file
if (sample_section_.getFactors().empty())
{
// no information about the origin of the samples -> assume uniqueness of all
unsigned nr(getNumberOfSamples());
for (unsigned i(0); i <= nr; ++i)
{
res[i] = i;
}
}
else
{
const map<vector<String>, set<unsigned>>& rowContent2RowIdx = getConditionToSampleMapping();
Size s(0);
for (const auto &condition : rowContent2RowIdx)
{
for (auto &sample : condition.second)
{
res.emplace(sample, s);
}
++s;
}
}
return res;
}
vector<vector<pair<String, unsigned>>> ExperimentalDesign::getConditionToPathLabelVector() const
{
const map<vector<String>, set<unsigned>>& rowContent2RowIdx = getConditionToSampleMapping();
const map<pair<String, unsigned>, unsigned>& pathLab2Sample = getPathLabelToSampleMapping(false);
vector<vector<pair<String, unsigned>>> res{rowContent2RowIdx.size()};
Size s(0);
// ["wt","24h","10mg"] -> sample [1, 3]
for (const auto& rcri : rowContent2RowIdx)
{
// sample 1
for (const auto& ri : rcri.second)
{
// [foo.mzml, ch1] -> sample 1
for (const auto& pl2Sample : pathLab2Sample)
{
// sample 1 == sample 1
if (pl2Sample.second == ri)
{
// res[0] -> [[foo, 1],...]
res[s].emplace_back(pl2Sample.first);
}
}
}
++s;
}
return res;
}
map<pair< String, unsigned >, unsigned> ExperimentalDesign::getPathLabelToPrefractionationMapping(const bool basename) const
{
const auto& sToPreFrac = getSampleToPrefractionationMapping();
const auto& pToS = getPathLabelToSampleMapping(basename);
map<pair<String, unsigned>, unsigned> ret;
for (const auto& entry : pToS)
{
ret.emplace(entry.first, sToPreFrac.at(entry.second));
}
return ret;
}
map<pair<String, unsigned>, unsigned> ExperimentalDesign::getPathLabelToConditionMapping(const bool basename) const
{
const auto& sToC = getSampleToConditionMapping();
const auto& pToS = getPathLabelToSampleMapping(basename);
map<pair<String, unsigned>, unsigned> ret;
for (const auto& entry : pToS)
{
ret.emplace(entry.first, sToC.at(entry.second));
}
return ret;
}
map<pair<String, unsigned>, unsigned> ExperimentalDesign::getPathLabelToSampleMapping(
const bool basename) const
{
return pathLabelMapper_(basename, [](const MSFileSectionEntry &r)
{ return r.sample; });
}
map<pair<String, unsigned>, unsigned> ExperimentalDesign::getPathLabelToFractionMapping(
const bool basename) const
{
return pathLabelMapper_(basename, [](const MSFileSectionEntry &r)
{ return r.fraction; });
}
map<pair<String, unsigned>, unsigned> ExperimentalDesign::getPathLabelToFractionGroupMapping(
const bool basename) const
{
return pathLabelMapper_(basename, [](const MSFileSectionEntry &r)
{ return r.fraction_group; });
}
bool ExperimentalDesign::sameNrOfMSFilesPerFraction() const
{
map<unsigned, vector<String>> frac2files = getFractionToMSFilesMapping();
if (frac2files.size() <= 1) { return true; }
Size files_per_fraction(0);
for (auto const &f : frac2files)
{
if (files_per_fraction == 0) // first fraction, initialize
{
files_per_fraction = f.second.size();
}
else // fraction >= 2
{
// different number of associated MS files?
if (f.second.size() != files_per_fraction)
{
return false;
}
}
}
return true;
}
const ExperimentalDesign::MSFileSection& ExperimentalDesign::getMSFileSection() const
{
return msfile_section_;
}
void ExperimentalDesign::setMSFileSection(const MSFileSection& msfile_section)
{
msfile_section_ = msfile_section;
sort_();
}
void ExperimentalDesign::setSampleSection(const SampleSection& sample_section)
{
sample_section_ = sample_section;
}
unsigned ExperimentalDesign::getNumberOfSamples() const
{
/*
if (msfile_section_.empty()) { return 0; }
return std::max_element(msfile_section_.begin(), msfile_section_.end(),
[](const MSFileSectionEntry& f1, const MSFileSectionEntry& f2)
{
return f1.sample < f2.sample;
})->sample;
*/
return sample_section_.getContentSize();
}
// TODO IMHO this is ill-defined and only works if exactly the same identifiers are used
// across fraction groups. Also, the number of fractions can change across
// fraction groups, e.g., if one is missing.
unsigned ExperimentalDesign::getNumberOfFractions() const
{
/*
if (msfile_section_.empty()) { return 0; }
return std::max_element(msfile_section_.begin(), msfile_section_.end(),
[](const MSFileSectionEntry& f1, const MSFileSectionEntry& f2)
{
return f1.fraction < f2.fraction;
})->fraction;
*/
auto fs = set<Size>();
for (const auto& row: msfile_section_)
{
fs.insert(row.fraction);
}
return fs.size();
}
// @return the number of labels per file
unsigned ExperimentalDesign::getNumberOfLabels() const
{
if (msfile_section_.empty()) { return 0; }
return std::max_element(msfile_section_.begin(), msfile_section_.end(),
[](const MSFileSectionEntry& f1, const MSFileSectionEntry& f2)
{
return f1.label < f2.label;
})->label;
}
// @return the number of MS files (= fractions * fraction_groups)
unsigned ExperimentalDesign::getNumberOfMSFiles() const
{
std::set<std::string> unique_paths;
for (auto const & r : msfile_section_)
{
unique_paths.insert(r.path);
}
return unique_paths.size();
}
bool ExperimentalDesign::isFractionated() const
{
// TODO Warning: only works if fractions are always the same in every fraction group!
std::vector<unsigned> fractions = getFractions_();
std::set<unsigned> fractions_set(fractions.begin(), fractions.end());
return fractions_set.size() > 1;
}
// TODO IMHO this is ill-defined and only works if fraction group names/IDs change over every sample
unsigned ExperimentalDesign::getNumberOfFractionGroups() const
{
/*
if (msfile_section_.empty()) { return 0; }
return std::max_element(msfile_section_.begin(), msfile_section_.end(),
[](const MSFileSectionEntry& f1, const MSFileSectionEntry& f2)
{
return f1.fraction_group < f2.fraction_group;
})->fraction_group;
*/
auto fgs = set<Size>();
for (const auto& row: msfile_section_)
{
fgs.insert(row.fraction_group);
}
return fgs.size();
}
unsigned ExperimentalDesign::getSample(unsigned fraction_group, unsigned label)
{
return std::find_if(msfile_section_.begin(), msfile_section_.end(),
[&fraction_group, &label](const MSFileSectionEntry& r)
{
return r.fraction_group == fraction_group && r.label == label;
})->sample;
}
const ExperimentalDesign::SampleSection& ExperimentalDesign::getSampleSection() const
{
return sample_section_;
}
std::vector< String > ExperimentalDesign::getFileNames_(const bool basename) const
{
std::vector<String> filenames;
for (const MSFileSectionEntry& row : msfile_section_)
{
const String path = String(row.path);
filenames.push_back(basename ? path : File::basename(path));
}
return filenames;
}
template<typename T>
void ExperimentalDesign::errorIfAlreadyExists(std::set<T> &container, T &item, const String &message)
{
if (container.find(item) != container.end())
{
throw Exception::MissingInformation(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION, message);
}
container.insert(item);
}
void ExperimentalDesign::isValid_()
{
std::set< std::tuple< unsigned, unsigned, unsigned > > fractiongroup_fraction_label_set;
std::set< std::tuple< std::string, unsigned > > path_label_set;
std::map< std::tuple< unsigned, unsigned >, std::set< unsigned > > fractiongroup_label_to_sample;
std::set< unsigned > label_set;
std::set< unsigned > fraction_group_set;
std::set< unsigned > sample_set;
if (msfile_section_.empty())
{
return;
}
bool labelfree = true;
for (const MSFileSectionEntry& row : msfile_section_)
{
// FRACTIONGROUP_FRACTION_LABEL TUPLE
std::tuple<unsigned, unsigned, unsigned> fractiongroup_fraction_label = std::make_tuple(row.fraction_group, row.fraction, row.label);
errorIfAlreadyExists(
fractiongroup_fraction_label_set,
fractiongroup_fraction_label,
"(Fraction Group, Fraction, Label) combination can only appear once");
// PATH_LABEL_TUPLE
std::tuple<std::string, unsigned> path_label = std::make_tuple(row.path, row.label);
errorIfAlreadyExists(
path_label_set,
path_label,
"(Path, Label) combination (" + String(get<0>(path_label)) + "," + String(get<1>(path_label)) + ") can only appear once");
// FRACTIONGROUP_LABEL TUPLE
std::tuple<unsigned, unsigned> fractiongroup_label = std::make_tuple(row.fraction_group, row.label);
fractiongroup_label_to_sample[fractiongroup_label].insert(row.sample);
label_set.insert(row.label);
fraction_group_set.insert(row.fraction_group);
}
if (label_set.size() > 1)
{
labelfree = false;
}
// TODO remove that restriction. Check if that order is still assumed somewhere.
// Except for in the getNrFractionGroups
if ((*fraction_group_set.begin()) != 1)
{
throw Exception::InvalidValue(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Fraction groups have to be integers and their set needs to be consecutive and start with 1.",
String(*fraction_group_set.begin()));
}
Size s = 0;
for (const auto& fg : fraction_group_set)
{
++s;
if (fg != s)
{
throw Exception::InvalidValue(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Fraction groups have to be integers and their set needs to be consecutive and start with 1.",
String(*fraction_group_set.begin()));
}
}
for (const auto& [k,v] : fractiongroup_label_to_sample)
{
if (labelfree && v.size() > 1)
{
throw Exception::MissingInformation(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION, "Multiple samples encountered for the same fraction group and the same label"
"Please correct your experimental design if this is a label free experiment, otherwise"
"check your labels. Occurred at fraction group " +
String(std::get<0>(k)) + "and label" + String(std::get<1>(k)));
}
}
}
std::vector<unsigned> ExperimentalDesign::getLabels_() const
{
std::vector<unsigned> labels;
for (const MSFileSectionEntry &row : msfile_section_)
{
labels.push_back(row.label);
}
return labels;
}
std::vector<unsigned> ExperimentalDesign::getFractions_() const
{
std::vector<unsigned> fractions;
for (const MSFileSectionEntry &row : msfile_section_)
{
fractions.push_back(row.fraction);
}
return fractions;
}
void ExperimentalDesign::sort_()
{
std::sort(msfile_section_.begin(), msfile_section_.end(),
[](const MSFileSectionEntry& a, const MSFileSectionEntry& b)
{
return std::tie(a.fraction_group, a.fraction, a.label, a.sample, a.path) <
std::tie(b.fraction_group, b.fraction, b.label, b.sample, b.path);
});
}
Size ExperimentalDesign::filterByBasenames(const set<String>& bns)
{
Size before = msfile_section_.size();
msfile_section_.erase(std::remove_if(msfile_section_.begin(), msfile_section_.end(),
[&bns](MSFileSectionEntry& e)
{
return bns.find(File::basename(e.path)) == bns.end();
}), msfile_section_.end());
int diff = before - msfile_section_.size();
if (diff > 0)
{
OPENMS_LOG_WARN << "Removed " << diff << " files from design to match given mzML/idXML subset." << std::endl;
}
if (msfile_section_.empty())
{
OPENMS_LOG_FATAL_ERROR << "Given basename set does not overlap with design. Design would be empty." << std::endl;
}
return (before - msfile_section_.size());
}
/* Implementations of SampleSection */
std::set<String> ExperimentalDesign::SampleSection::getSamples() const
{
std::set<String> samples;
for (const auto &kv : sample_to_rowindex_)
{
samples.insert(kv.first);
}
return samples;
}
std::set< String > ExperimentalDesign::SampleSection::getFactors() const
{
std::set<String> factors;
for (const auto &kv : columnname_to_columnindex_)
{
factors.insert(kv.first);
}
return factors;
}
bool ExperimentalDesign::SampleSection::hasSample(const String& sample) const
{
return sample_to_rowindex_.find(sample) != sample_to_rowindex_.end();
}
bool ExperimentalDesign::SampleSection::hasFactor(const String &factor) const
{
return columnname_to_columnindex_.find(factor) != columnname_to_columnindex_.end();
}
String ExperimentalDesign::SampleSection::getFactorValue(unsigned sample_idx, const String &factor) const
{
if (!hasFactor(factor))
{
throw Exception::MissingInformation(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Factor " + factor + " is not present in the Experimental Design");
}
const StringList& sample_row = content_.at(sample_idx);
const Size col_index = columnname_to_columnindex_.at(factor);
return sample_row[col_index];
}
String ExperimentalDesign::SampleSection::getFactorValue(const String& sample_name, const String &factor) const
{
if (!hasSample(sample_name))
{
throw Exception::MissingInformation(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Sample " + sample_name + " is not present in the Experimental Design");
}
if (!hasFactor(factor))
{
throw Exception::MissingInformation(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Factor " + factor + " is not present in the Experimental Design");
}
const StringList& sample_row = content_.at(sample_to_rowindex_.at(sample_name));
const Size col_index = columnname_to_columnindex_.at(factor);
return sample_row[col_index];
}
Size ExperimentalDesign::SampleSection::getFactorColIdx(const String &factor) const
{
if (! hasFactor(factor))
{
throw Exception::MissingInformation(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Factor " + factor + " is not present in the Experimental Design");
}
return columnname_to_columnindex_.at(factor);
}
Size ExperimentalDesign::SampleSection::getContentSize() const
{
return content_.size();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/CVTermListInterface.cpp | .cpp | 4,208 | 177 | // 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/METADATA/CVTermListInterface.h>
#include <OpenMS/METADATA/CVTermList.h>
#include <OpenMS/CONCEPT/Helpers.h>
#include <map>
namespace OpenMS
{
static const std::map<String, std::vector<CVTerm> > empty_cvterm_map = std::map<String, std::vector<CVTerm> >();
CVTermListInterface::CVTermListInterface() :
MetaInfoInterface(),
cvt_ptr_(nullptr)
{}
CVTermListInterface::CVTermListInterface(const CVTermListInterface & rhs) :
MetaInfoInterface(rhs),
cvt_ptr_(nullptr)
{
if (rhs.cvt_ptr_ != nullptr)
{
cvt_ptr_ = new CVTermList(*rhs.cvt_ptr_);
}
}
/// Move constructor
CVTermListInterface::CVTermListInterface(CVTermListInterface&& rhs) noexcept :
MetaInfoInterface(std::move(rhs)), // NOTE: rhs itself is an lvalue
cvt_ptr_(rhs.cvt_ptr_)
{
// see http://thbecker.net/articles/rvalue_references/section_05.html
// take ownership
rhs.cvt_ptr_ = nullptr;
}
CVTermListInterface::~CVTermListInterface()
{
delete cvt_ptr_;
}
CVTermListInterface & CVTermListInterface::operator=(const CVTermListInterface & rhs)
{
if (this != &rhs)
{
MetaInfoInterface::operator=(rhs);
delete cvt_ptr_;
cvt_ptr_ = nullptr;
if (rhs.cvt_ptr_ != nullptr)
{
cvt_ptr_ = new CVTermList(*rhs.cvt_ptr_);
}
}
return *this;
}
CVTermListInterface& CVTermListInterface::operator=(CVTermListInterface&& rhs) noexcept
{
if (&rhs == this)
{
return *this;
}
MetaInfoInterface::operator=(std::move(rhs));
// free memory and assign rhs memory
delete cvt_ptr_;
cvt_ptr_ = rhs.cvt_ptr_;
rhs.cvt_ptr_ = nullptr;
return *this;
}
bool CVTermListInterface::operator==(const CVTermListInterface& rhs) const
{
return MetaInfoInterface::operator==(rhs) &&
Helpers::cmpPtrSafe<CVTermList*>(cvt_ptr_, rhs.cvt_ptr_);
}
bool CVTermListInterface::operator!=(const CVTermListInterface& rhs) const
{
return !(*this == rhs);
}
void CVTermListInterface::replaceCVTerms(std::map<String, std::vector<CVTerm> > & cv_terms)
{
createIfNotExists_();
cvt_ptr_->replaceCVTerms(cv_terms);
}
void CVTermListInterface::createIfNotExists_()
{
if (!cvt_ptr_)
{
cvt_ptr_ = new CVTermList();
}
}
bool CVTermListInterface::empty() const
{
return (cvt_ptr_ == nullptr || cvt_ptr_->empty());
}
void CVTermListInterface::setCVTerms(const std::vector<CVTerm>& terms)
{
createIfNotExists_();
cvt_ptr_->setCVTerms(terms);
}
void CVTermListInterface::replaceCVTerm(const CVTerm& cv_term)
{
createIfNotExists_();
cvt_ptr_->replaceCVTerm(cv_term);
}
void CVTermListInterface::replaceCVTerms(const std::vector<CVTerm>& cv_terms, const String& accession)
{
createIfNotExists_();
cvt_ptr_->replaceCVTerms(cv_terms, accession);
}
void CVTermListInterface::replaceCVTerms(const std::map<String, std::vector<CVTerm> >& cv_term_map)
{
createIfNotExists_();
cvt_ptr_->replaceCVTerms(cv_term_map);
}
void CVTermListInterface::consumeCVTerms(const std::map<String, std::vector<CVTerm> >& cv_term_map)
{
createIfNotExists_();
cvt_ptr_->consumeCVTerms(cv_term_map);
}
const std::map<String, std::vector<CVTerm> >& CVTermListInterface::getCVTerms() const
{
if (!cvt_ptr_)
{
return empty_cvterm_map;
}
else
{
return cvt_ptr_->getCVTerms();
}
}
/// adds a CV term
void CVTermListInterface::addCVTerm(const CVTerm& term)
{
createIfNotExists_();
cvt_ptr_->addCVTerm(term);
}
/// checks whether the term has a value
bool CVTermListInterface::hasCVTerm(const String& accession) const
{
if (!cvt_ptr_)
{
return false;
}
else
{
return cvt_ptr_->hasCVTerm(accession);
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/AnnotatedMSRun.h | .h | 8,489 | 285 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: David Voigt $
// -------------------------------------------------------------------------------------------------------------------------------------
#pragma once
#include <OpenMS/OpenMSConfig.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <boost/range/combine.hpp>
#include <vector>
namespace OpenMS
{
class PeptideIdentification;
class MSSpectrum;
/**
* @brief Class for storing MS run data with peptide and protein identifications
*
* This class stores an MSExperiment (containing spectra) along with peptide and protein
* identifications. Each spectrum in the MSExperiment is associated with a single
* PeptideIdentification object.
*
* The class provides methods to access and modify these identifications, as well as
* iterators to traverse the spectra and their associated identifications together.
*/
class OPENMS_DLLAPI AnnotatedMSRun
{
public:
typedef std::pair<MSSpectrum&, PeptideIdentification&> Mapping;
typedef std::pair<const MSSpectrum&, const PeptideIdentification&> ConstMapping;
/// Default constructor
AnnotatedMSRun() = default;
/**
* @brief Move constructor for efficiently loading a MSExperiment without a deep copy
* @param[in] experiment The MSExperiment to move into this object
*/
explicit AnnotatedMSRun(MSExperiment&& experiment) : data(std::move(experiment))
{};
/// Move constructor
AnnotatedMSRun(AnnotatedMSRun&&) = default;
/// Destructor
~AnnotatedMSRun() = default;
/**
* @brief Get the protein identification
* @return A reference to the protein identification
*/
std::vector<ProteinIdentification>& getProteinIdentifications()
{
return protein_ids_;
}
/**
* @brief Get the protein identification (const version)
* @return A const reference to the protein identification
*/
const std::vector<ProteinIdentification>& getProteinIdentifications() const
{
return protein_ids_;
}
/**
* @brief Get all peptide identifications for all spectra
* @return A reference to the vector of peptide identifications
*/
PeptideIdentificationList& getPeptideIdentifications();
/**
* @brief Get all peptide identifications for all spectra (const version)
* @return A const reference to the vector of peptide identifications
*/
const PeptideIdentificationList& getPeptideIdentifications() const;
/**
* @brief Set all peptide identifications for all spectra
* @param[in] ids Vector of peptide identifications
*/
void setPeptideIdentifications(PeptideIdentificationList&& ids);
/**
* @brief Set all peptide identifications for all spectra
* @param[in] ids Vector of peptide identifications
*/
void setPeptideIdentifications(const PeptideIdentificationList& ids);
/**
* @brief Get the MSExperiment
* @return A reference to the MSExperiment
*/
MSExperiment& getMSExperiment();
/**
* @brief Get the MSExperiment (const version)
* @return A const reference to the MSExperiment
*/
const MSExperiment& getMSExperiment() const;
/**
* @brief Set the MSExperiment
* @param[in] experiment The MSExperiment to set
*/
void setMSExperiment(MSExperiment&& experiment);
/**
* @brief Set the MSExperiment
* @param[in] experiment The MSExperiment to set
*/
void setMSExperiment(const MSExperiment& experiment);
/**
* @brief Get a const iterator to the beginning of the data
* @return A const iterator to the beginning
*/
inline auto cbegin() const
{
return PairIterator(data.getSpectra().cbegin(), peptide_ids.cbegin());
}
/**
* @brief Get an iterator to the beginning of the data
* @return An iterator to the beginning
*/
inline auto begin()
{
return PairIterator(data.getSpectra().begin(), peptide_ids.begin());
}
/**
* @brief Get a const iterator to the beginning of the data
* @return A const iterator to the beginning
*/
inline auto begin() const
{
return PairIterator(data.getSpectra().cbegin(), peptide_ids.cbegin());
}
/**
* @brief Get an iterator to the end of the data
* @return An iterator to the end
*/
inline auto end()
{
return PairIterator(data.getSpectra().end(), peptide_ids.end());
}
/**
* @brief Get a const iterator to the end of the data
* @return A const iterator to the end
*/
inline auto end() const
{
return PairIterator(data.getSpectra().end(), peptide_ids.end());
}
/**
* @brief Get a const iterator to the end of the data
* @return A const iterator to the end
*/
inline auto cend() const
{
return PairIterator(data.getSpectra().cend(), peptide_ids.cend());
}
/**
* @brief Access a spectrum and its associated peptide identification
* @param[in] idx The index of the spectrum
* @return A pair of references to the spectrum and its peptide identification
*/
inline Mapping operator[](size_t idx)
{
return {data.getSpectra()[idx], peptide_ids[idx]};
}
/**
* @brief Access a spectrum and its associated peptide identification (const version)
* @param[in] idx The index of the spectrum
* @return A pair of const references to the spectrum and its peptide identification
*/
inline ConstMapping operator[](size_t idx) const
{
return {data.getSpectra()[idx], peptide_ids[idx]};
}
/**
* @brief Iterator for pairs of spectra and peptide identifications
*
* This iterator allows traversing the spectra and their associated peptide
* identifications together.
*/
template<typename T1, typename T2>
struct PairIterator
{
// TODO add check that both vectors are of the same length
using iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
//using value_type = std::pair<T1, T2>;
//using pointer = value_type*;
//using reference = value_type&;
/**
* @brief Constructor
* @param[in] ptr1 Iterator to the spectra
* @param[in] ptr2 Iterator to the peptide identifications
*/
PairIterator(T1 ptr1, T2 ptr2) : m_ptr1(ptr1), m_ptr2(ptr2)
{}
/**
* @brief Pre-increment operator
* @return Reference to this iterator after incrementing
*/
PairIterator& operator++()
{
++m_ptr1;
++m_ptr2;
return *this;
}
/**
* @brief Post-increment operator
* @return Copy of this iterator before incrementing
*/
PairIterator operator++(int)
{
auto tmp(*this);
++(*this);
return tmp;
}
/**
* @brief Dereference operator
* @return A pair of references to the current spectrum and peptide identification
*/
auto operator*()
{
return std::make_pair(std::ref(*m_ptr1), std::ref(*m_ptr2));
}
/**
* @brief Equality operator
* @param[in] a First iterator
* @param[in] b Second iterator
* @return True if the iterators are equal
*/
inline friend bool operator==(const PairIterator& a, const PairIterator& b)
{
return a.m_ptr1 == b.m_ptr1 && a.m_ptr2 == b.m_ptr2;
}
/**
* @brief Inequality operator
* @param[in] a First iterator
* @param[in] b Second iterator
* @return True if the iterators are not equal
*/
inline friend bool operator!=(const PairIterator& a, const PairIterator& b)
{
return !(a == b);
}
private:
T1 m_ptr1;
T2 m_ptr2;
};
typedef AnnotatedMSRun::PairIterator<std::vector<MSSpectrum>::iterator, PeptideIdentificationList::iterator> Iterator;
typedef AnnotatedMSRun::PairIterator<std::vector<MSSpectrum>::const_iterator, PeptideIdentificationList::const_iterator> ConstIterator;
private:
PeptideIdentificationList peptide_ids;
std::vector<ProteinIdentification> protein_ids_;
MSExperiment data;
};
} | Unknown |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ScanWindow.cpp | .cpp | 731 | 30 | // 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/METADATA/ScanWindow.h>
using namespace std;
namespace OpenMS
{
bool ScanWindow::operator==(const ScanWindow & source) const
{
return MetaInfoInterface::operator==(source) &&
begin == source.begin &&
end == source.end;
}
bool ScanWindow::operator!=(const ScanWindow & source) const
{
return !(operator==(source));
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/AbsoluteQuantitationStandards.cpp | .cpp | 4,656 | 119 | // 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/METADATA/AbsoluteQuantitationStandards.h>
namespace OpenMS
{
bool AbsoluteQuantitationStandards::findComponentFeature_(
const FeatureMap& feature_map,
const String& component_name,
Feature& feature_found
) const
{
for (const Feature& feature : feature_map)
{
for (const Feature& subordinate : feature.getSubordinates())
{
if (subordinate.metaValueExists("native_id") && subordinate.getMetaValue("native_id") == component_name)
{
feature_found = subordinate;
return true;
}
}
}
return false;
}
void AbsoluteQuantitationStandards::mapComponentsToConcentrations(
const std::vector<AbsoluteQuantitationStandards::runConcentration>& run_concentrations,
const std::vector<FeatureMap>& feature_maps,
std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>>& components_to_concentrations
) const
{
components_to_concentrations.clear();
for (const AbsoluteQuantitationStandards::runConcentration& run : run_concentrations)
{
if (run.sample_name.empty() || run.component_name.empty())
{
continue;
}
for (const FeatureMap& fmap : feature_maps) // not all elements are necessarily processed (break; is present inside the loop)
{
StringList filename;
fmap.getPrimaryMSRunPath(filename);
if (!filename.empty()) // if the FeatureMap doesn't have a sample_name, or if it is not the one we're looking for: skip.
{
if (filename[0].hasSuffix(".mzML"))
{
filename[0].resize(filename[0].size() - 5);
}
else if (filename[0].hasSuffix(".txt"))
{
filename[0].resize(filename[0].size() - 4);
}
if (filename[0] != run.sample_name)
{
continue;
}
}
AbsoluteQuantitationStandards::featureConcentration fc;
if (!findComponentFeature_(fmap, run.component_name, fc.feature)) // if there was no match: skip.
{
continue;
}
if (!run.IS_component_name.empty())
{
findComponentFeature_(fmap, run.IS_component_name, fc.IS_feature);
}
// fill the rest of the information from the current runConcentration
fc.actual_concentration = run.actual_concentration;
fc.IS_actual_concentration = run.IS_actual_concentration;
fc.concentration_units = run.concentration_units;
fc.dilution_factor = run.dilution_factor;
// add to the map
std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>>::iterator p;
p = components_to_concentrations.find(run.component_name);
if (p == components_to_concentrations.end()) // if the key doesn't exist, insert it and create a new vector with fc as its only element
{
components_to_concentrations.insert({run.component_name, {fc}});
}
else // otherwise, add the element to the existing vector
{
(p->second).push_back(fc);
}
break; // because there won't be another FeatureMap with the same sample_name
}
}
}
void AbsoluteQuantitationStandards::getComponentFeatureConcentrations(
const std::vector<AbsoluteQuantitationStandards::runConcentration>& run_concentrations,
const std::vector<FeatureMap>& feature_maps,
const String& component_name,
std::vector<AbsoluteQuantitationStandards::featureConcentration>& feature_concentrations
) const
{
std::vector<AbsoluteQuantitationStandards::runConcentration> filtered_rc;
for (const AbsoluteQuantitationStandards::runConcentration& run : run_concentrations)
{
if (run.component_name == component_name)
{
filtered_rc.push_back(run);
}
}
std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>> components_to_concentrations;
mapComponentsToConcentrations(filtered_rc, feature_maps, components_to_concentrations);
if (components_to_concentrations.count(component_name))
{
feature_concentrations = components_to_concentrations.at(component_name);
}
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/MetaInfoRegistry.cpp | .cpp | 8,629 | 305 | // 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, Hendrik Weisser $
// -------------------------------------------------------------------------
#include <sstream>
#include <OpenMS/METADATA/MetaInfoRegistry.h>
using namespace std;
namespace OpenMS
{
MetaInfoRegistry::MetaInfoRegistry() :
next_index_(1024),
name_to_index_(),
index_to_name_(),
index_to_description_(),
index_to_unit_()
{
name_to_index_["isotopic_range"] = 1;
index_to_name_[1] = "isotopic_range";
index_to_description_[1] = "consecutive numbering of the peaks in an isotope pattern. 0 is the monoisotopic peak";
index_to_unit_[1] = "";
name_to_index_["cluster_id"] = 2;
index_to_name_[2] = "cluster_id";
index_to_description_[2] = "consecutive numbering of isotope clusters in a spectrum";
index_to_unit_[2] = "";
name_to_index_["label"] = 3;
index_to_name_[3] = "label";
index_to_description_[3] = "label e.g. shown in visualization";
index_to_unit_[3] = "";
name_to_index_["icon"] = 4;
index_to_name_[4] = "icon";
index_to_description_[4] = "icon shown in visualization";
index_to_unit_[4] = "";
name_to_index_["color"] = 5;
index_to_name_[5] = "color";
index_to_description_[5] = "color used for visualization e.g. #FF00FF for purple";
index_to_unit_[5] = "";
name_to_index_["RT"] = 6;
index_to_name_[6] = "RT";
index_to_description_[6] = "the retention time of an identification";
index_to_unit_[6] = "";
name_to_index_["MZ"] = 7;
index_to_name_[7] = "MZ";
index_to_description_[7] = "the MZ of an identification";
index_to_unit_[7] = "";
name_to_index_["predicted_RT"] = 8;
index_to_name_[8] = "predicted_RT";
index_to_description_[8] = "the predicted retention time of a peptide hit";
index_to_unit_[8] = "";
name_to_index_["predicted_RT_p_value"] = 9;
index_to_name_[9] = "predicted_RT_p_value";
index_to_description_[9] = "the predicted RT p-value of a peptide hit";
index_to_unit_[9] = "";
name_to_index_["spectrum_reference"] = 10;
index_to_name_[10] = "spectrum_reference";
index_to_description_[10] = "Reference to a spectrum or feature number";
index_to_unit_[10] = "";
name_to_index_["ID"] = 11;
index_to_name_[11] = "ID";
index_to_description_[11] = "Some type of identifier";
index_to_unit_[11] = "";
name_to_index_["low_quality"] = 12;
index_to_name_[12] = "low_quality";
index_to_description_[12] = "Flag which indicates that some entity has a low quality (e.g. a feature pair)";
index_to_unit_[12] = "";
name_to_index_["charge"] = 13;
index_to_name_[13] = "charge";
index_to_description_[13] = "Charge of a feature or peak";
index_to_unit_[13] = "";
}
MetaInfoRegistry::MetaInfoRegistry(const MetaInfoRegistry& rhs)
{
*this = rhs;
}
MetaInfoRegistry::~MetaInfoRegistry() = default;
MetaInfoRegistry& MetaInfoRegistry::operator=(const MetaInfoRegistry& rhs)
{
if (this == &rhs)
{
return *this;
}
#pragma omp critical (MetaInfoRegistry)
{
next_index_ = rhs.next_index_;
name_to_index_ = rhs.name_to_index_;
index_to_name_ = rhs.index_to_name_;
index_to_description_ = rhs.index_to_description_;
index_to_unit_ = rhs.index_to_unit_;
}
return *this;
}
UInt MetaInfoRegistry::registerName(const String& name, const String& description, const String& unit)
{
UInt rv;
#pragma omp critical (MetaInfoRegistry)
{
MapString2IndexType::iterator it = name_to_index_.find(name);
if (it == name_to_index_.end())
{
name_to_index_[name] = next_index_;
index_to_name_[next_index_] = name;
index_to_description_[next_index_] = description;
index_to_unit_[next_index_] = unit;
rv = next_index_++;
}
else
{
rv = it->second;
}
}
return rv;
}
void MetaInfoRegistry::setDescription(UInt index, const String& description)
{
MapIndex2StringType::iterator pos;
#pragma omp critical (MetaInfoRegistry)
{
pos = index_to_description_.find(index);
if (pos != index_to_description_.end())
{
pos->second = description;
}
else
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unregistered index!", String(index));
}
}
}
void MetaInfoRegistry::setDescription(const String& name, const String& description)
{
MapString2IndexType::iterator pos;
#pragma omp critical (MetaInfoRegistry)
{
pos = name_to_index_.find(name);
if (pos != name_to_index_.end())
{
index_to_description_[pos->second] = description;
}
else
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unregistered name!", name);
}
}
}
void MetaInfoRegistry::setUnit(UInt index, const String& unit)
{
MapIndex2StringType::iterator pos;
#pragma omp critical (MetaInfoRegistry)
{
pos = index_to_unit_.find(index);
if (pos != index_to_unit_.end())
{
pos->second = unit;
}
else
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unregistered index!", String(index));
}
}
}
void MetaInfoRegistry::setUnit(const String& name, const String& unit)
{
MapString2IndexType::iterator pos;
#pragma omp critical (MetaInfoRegistry)
{
pos = name_to_index_.find(name);
if (pos != name_to_index_.end())
{
index_to_unit_[pos->second] = unit;
}
else
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unregistered name!", name);
}
}
}
UInt MetaInfoRegistry::getIndex(const String& name) const
{
UInt rv = UInt(-1);
#pragma omp critical (MetaInfoRegistry)
{
MapString2IndexType::const_iterator it = name_to_index_.find(name);
if (it != name_to_index_.end())
{
rv = it->second;
}
}
return rv;
}
String MetaInfoRegistry::getDescription(UInt index) const
{
String result;
#pragma omp critical (MetaInfoRegistry)
{
MapIndex2StringType::const_iterator it = index_to_description_.find(index);
if (it == index_to_description_.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unregistered index!", String(index));
}
result = it->second;
}
return result;
}
String MetaInfoRegistry::getDescription(const String& name) const
{
String rv;
UInt index = getIndex(name); // this has to be outside the OpenMP "critical" block!
if (index == UInt(-1)) // not found
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unregistered Name!", name);
}
else
{
#pragma omp critical (MetaInfoRegistry)
{
rv = (index_to_description_.find(index))->second;
}
}
return rv;
}
String MetaInfoRegistry::getUnit(UInt index) const
{
String result;
#pragma omp critical (MetaInfoRegistry)
{
MapIndex2StringType::const_iterator it = index_to_unit_.find(index);
if (it == index_to_unit_.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unregistered index!", String(index));
}
result = it->second;
}
return result;
}
String MetaInfoRegistry::getUnit(const String& name) const
{
String rv;
UInt index = getIndex(name); // this has to be outside the OpenMP "critical" block!
if (index == UInt(-1)) // not found
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unregistered Name!", name);
}
else
{
#pragma omp critical (MetaInfoRegistry)
{
rv = (index_to_unit_.find(index))->second;
}
}
return rv;
}
String MetaInfoRegistry::getName(UInt index) const
{
String rv;
#pragma omp critical (MetaInfoRegistry)
{
MapIndex2StringType::const_iterator it = index_to_name_.find(index);
if (it != index_to_name_.end())
{
rv = it->second;
}
else
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unregistered index!", String(index));
}
}
return rv;
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ContactPerson.cpp | .cpp | 2,554 | 127 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/METADATA/ContactPerson.h>
using namespace std;
namespace OpenMS
{
bool ContactPerson::operator==(const ContactPerson & rhs) const
{
return first_name_ == rhs.first_name_ &&
last_name_ == rhs.last_name_ &&
institution_ == rhs.institution_ &&
email_ == rhs.email_ &&
contact_info_ == rhs.contact_info_ &&
url_ == rhs.url_ &&
address_ == rhs.address_ &&
MetaInfoInterface::operator==(rhs);
}
bool ContactPerson::operator!=(const ContactPerson & rhs) const
{
return !(operator==(rhs));
}
const String & ContactPerson::getFirstName() const
{
return first_name_;
}
void ContactPerson::setFirstName(const String & name)
{
first_name_ = name;
}
const String & ContactPerson::getLastName() const
{
return last_name_;
}
void ContactPerson::setLastName(const String & name)
{
last_name_ = name;
}
void ContactPerson::setName(const String & name)
{
std::vector<String> tmp;
if (name.split(',', tmp))
{
first_name_ = tmp[1].trim();
last_name_ = tmp[0].trim();
}
else
{
if (name.split(' ', tmp))
{
first_name_ = tmp[0];
last_name_ = tmp[1];
}
else
{
last_name_ = name;
}
}
}
const String & ContactPerson::getEmail() const
{
return email_;
}
void ContactPerson::setEmail(const String & email)
{
email_ = email;
}
const String & ContactPerson::getInstitution() const
{
return institution_;
}
void ContactPerson::setInstitution(const String & institution)
{
institution_ = institution;
}
const String & ContactPerson::getContactInfo() const
{
return contact_info_;
}
void ContactPerson::setContactInfo(const String & contact_info)
{
contact_info_ = contact_info;
}
const String & ContactPerson::getURL() const
{
return url_;
}
void ContactPerson::setURL(const String & url)
{
url_ = url;
}
const String & ContactPerson::getAddress() const
{
return address_;
}
void ContactPerson::setAddress(const String & address)
{
address_ = address;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/MetaInfo.cpp | .cpp | 5,079 | 194 | // 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/METADATA/MetaInfo.h>
using namespace std;
namespace OpenMS
{
MetaInfoRegistry MetaInfo::registry_ = MetaInfoRegistry();
MetaInfo::~MetaInfo() = default;
bool MetaInfo::operator==(const MetaInfo& rhs) const
{
return index_to_value_ == rhs.index_to_value_;
}
bool MetaInfo::operator!=(const MetaInfo& rhs) const
{
return !(operator==(rhs));
}
MetaInfo& MetaInfo::operator+=(const MetaInfo& rhs)
{
if (rhs.index_to_value_.empty()) return *this;
if (index_to_value_.empty())
{
index_to_value_ = rhs.index_to_value_;
return *this;
}
// Two-way merge into vector, then construct flat_map from sorted range
using pair_type = MapType::value_type;
std::vector<pair_type> merged;
merged.reserve(index_to_value_.size() + rhs.index_to_value_.size());
auto it_this = index_to_value_.begin();
auto end_this = index_to_value_.end();
auto it_rhs = rhs.index_to_value_.begin();
auto end_rhs = rhs.index_to_value_.end();
// Merge with deduplication: rhs values overwrite
while (it_this != end_this && it_rhs != end_rhs)
{
if (it_this->first < it_rhs->first)
{
merged.push_back(*it_this++);
}
else if (it_rhs->first < it_this->first)
{
merged.push_back(*it_rhs++);
}
else
{
// Equal keys: rhs value overwrites
merged.push_back(*it_rhs++);
++it_this;
}
}
// Append remaining elements efficiently
merged.insert(merged.end(), it_this, end_this);
merged.insert(merged.end(), it_rhs, end_rhs);
// Construct flat_map from sorted range using move semantics
index_to_value_ = MapType(
boost::container::ordered_unique_range,
std::make_move_iterator(merged.begin()),
std::make_move_iterator(merged.end())
);
return *this;
}
const DataValue& MetaInfo::getValue(const String& name, const DataValue& default_value) const
{
MapType::const_iterator it = index_to_value_.find(registry_.getIndex(name));
if (it != index_to_value_.end())
{
return it->second;
}
return default_value;
}
const DataValue& MetaInfo::getValue(UInt index, const DataValue& default_value) const
{
MapType::const_iterator it = index_to_value_.find(index);
if (it != index_to_value_.end())
{
return it->second;
}
return default_value;
}
void MetaInfo::setValue(const String& name, const DataValue& value)
{
UInt index = registry_.registerName(name); // no-op if name is already registered
setValue(index, value);
}
void MetaInfo::setValue(UInt index, const DataValue& value)
{
// @TODO: check if that index is registered in MetaInfoRegistry?
auto it = index_to_value_.find(index);
if (it != index_to_value_.end())
{
it->second = value;
}
else
{
// Note; we need to create a copy of data value here and can't use the const &
// The underlying flat_map invalidates references to it if inserting
// an element leads to relocation (e.g, in constructs like: m.insert(1, m[2]));)
DataValue tmp = value;
index_to_value_.insert(std::make_pair(index, tmp));
}
}
MetaInfoRegistry& MetaInfo::registry()
{
return registry_;
}
bool MetaInfo::exists(const String& name) const
{
UInt index = registry_.getIndex(name);
if (index != UInt(-1))
{
return (index_to_value_.find(index) != index_to_value_.end());
}
return false;
}
bool MetaInfo::exists(UInt index) const
{
return (index_to_value_.find(index) != index_to_value_.end());
}
void MetaInfo::removeValue(const String& name)
{
MapType::iterator it = index_to_value_.find(registry_.getIndex(name));
if (it != index_to_value_.end())
{
index_to_value_.erase(it);
}
}
void MetaInfo::removeValue(UInt index)
{
MapType::iterator it = index_to_value_.find(index);
if (it != index_to_value_.end())
{
index_to_value_.erase(it);
}
}
void MetaInfo::getKeys(vector<String>& keys) const
{
keys.resize(index_to_value_.size());
UInt i = 0;
for (MapType::const_iterator it = index_to_value_.begin(); it != index_to_value_.end(); ++it)
{
keys[i++] = registry_.getName(it->first);
}
}
void MetaInfo::getKeys(vector<UInt>& keys) const
{
keys.resize(index_to_value_.size());
UInt i = 0;
for (MapType::const_iterator it = index_to_value_.begin(); it != index_to_value_.end(); ++it)
{
keys[i++] = it->first;
}
}
bool MetaInfo::empty() const
{
return index_to_value_.empty();
}
void MetaInfo::clear()
{
index_to_value_.clear();
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ID/IdentifiedMolecule.cpp | .cpp | 3,620 | 122 | // 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/METADATA/ID/IdentifiedMolecule.h>
namespace OpenMS::IdentificationDataInternal
{
bool operator==(const IdentifiedMolecule& a, const IdentifiedMolecule& b)
{
return operator==(static_cast<RefVariant>(a), static_cast<RefVariant>(b));
}
bool operator!=(const IdentifiedMolecule& a, const IdentifiedMolecule& b)
{
return !operator==(a, b);
}
bool operator<(const IdentifiedMolecule& a, const IdentifiedMolecule& b)
{
return operator<(static_cast<RefVariant>(a), static_cast<RefVariant>(b));
}
MoleculeType IdentifiedMolecule::getMoleculeType() const
{
if (std::get_if<IdentifiedPeptideRef>(this))
{
return MoleculeType::PROTEIN;
}
if (std::get_if<IdentifiedCompoundRef>(this))
{
return MoleculeType::COMPOUND;
}
// if (get<IdentifiedOligoRef>(this))
return MoleculeType::RNA;
}
IdentifiedPeptideRef IdentifiedMolecule::getIdentifiedPeptideRef() const
{
if (const IdentifiedPeptideRef* ref_ptr =
std::get_if<IdentifiedPeptideRef>(this))
{
return *ref_ptr;
}
String msg = "matched molecule is not a peptide";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
IdentifiedCompoundRef IdentifiedMolecule::getIdentifiedCompoundRef() const
{
if (const IdentifiedCompoundRef* ref_ptr =
std::get_if<IdentifiedCompoundRef>(this))
{
return *ref_ptr;
}
String msg = "matched molecule is not a compound";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
IdentifiedOligoRef IdentifiedMolecule::getIdentifiedOligoRef() const
{
if (const IdentifiedOligoRef* ref_ptr =
std::get_if<IdentifiedOligoRef>(this))
{
return *ref_ptr;
}
String msg = "matched molecule is not an oligonucleotide";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
EmpiricalFormula IdentifiedMolecule::getFormula(Size fragment_type /*= 0*/, Int charge /*= 0*/) const
{
switch (getMoleculeType())
{
case MoleculeType::PROTEIN:
{
auto type = static_cast<Residue::ResidueType>(fragment_type);
return getIdentifiedPeptideRef()->sequence.getFormula(type, charge);
}
case MoleculeType::COMPOUND:
{
// @TODO: what about fragment type and charge?
return getIdentifiedCompoundRef()->formula;
}
case MoleculeType::RNA:
{
auto type = static_cast<NASequence::NASFragmentType>(fragment_type);
return getIdentifiedOligoRef()->sequence.getFormula(type, charge);
}
default:
throw Exception::NotImplemented(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION);
}
}
String IdentifiedMolecule::toString() const
{
switch (getMoleculeType())
{
case MoleculeType::PROTEIN:
return getIdentifiedPeptideRef()->sequence.toString();
case MoleculeType::COMPOUND:
return getIdentifiedCompoundRef()->identifier; // or use "name"?
case MoleculeType::RNA:
return getIdentifiedOligoRef()->sequence.toString();
default:
throw Exception::NotImplemented(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION);
}
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ID/IdentificationDataConverter.cpp | .cpp | 52,824 | 1,369 | // 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/METADATA/ID/IdentificationDataConverter.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <vector>
using namespace std;
using ID = OpenMS::IdentificationData;
namespace OpenMS
{
void IdentificationDataConverter::importIDs(
IdentificationData& id_data, const vector<ProteinIdentification>& proteins,
const PeptideIdentificationList& peptides)
{
map<String, ID::ProcessingStepRef> id_to_step;
ProgressLogger progresslogger;
progresslogger.setLogType(ProgressLogger::CMD);
// ProteinIdentification:
progresslogger.startProgress(0, proteins.size(),
"converting protein identification runs");
Size proteins_counter = 0;
for (const ProteinIdentification& prot : proteins)
{
proteins_counter++;
progresslogger.setProgress(proteins_counter);
ID::ProcessingSoftware software(prot.getSearchEngine(),
prot.getSearchEngineVersion());
const bool missing_protein_score_type = prot.getScoreType().empty();
ID::ScoreType score_type;
ID::ScoreTypeRef prot_score_ref;
if (!missing_protein_score_type)
{
score_type = ID::ScoreType(prot.getScoreType(), prot.isHigherScoreBetter());
prot_score_ref = id_data.registerScoreType(score_type);
software.assigned_scores.push_back(prot_score_ref);
}
else
{
OPENMS_LOG_WARN << "Missing protein score type. All protein scores without score type will be removed during conversion." << std::endl;
}
ID::ProcessingSoftwareRef software_ref =
id_data.registerProcessingSoftware(software);
ID::SearchParamRef search_ref =
importDBSearchParameters_(prot.getSearchParameters(), id_data);
ID::ProcessingStep step(software_ref);
// ideally, this should give us the raw files:
vector<String> primary_files;
prot.getPrimaryMSRunPath(primary_files, true);
// ... and this should give us mzML files:
vector<String> spectrum_files;
prot.getPrimaryMSRunPath(spectrum_files);
// if there's the same number of each, hope they're in the same order:
bool match_files = (primary_files.size() == spectrum_files.size());
// @TODO: what to do with raw files if there's a different number?
for (Size i = 0; i < spectrum_files.size(); ++i)
{
if (spectrum_files[i].empty())
{
OPENMS_LOG_WARN << "Warning: spectrum file with no name - skipping" << endl;
continue;
}
ID::InputFile input(spectrum_files[i]);
if (match_files) input.primary_files.insert(primary_files[i]);
ID::InputFileRef file_ref = id_data.registerInputFile(input);
step.input_file_refs.push_back(file_ref);
}
step.date_time = prot.getDateTime();
ID::ProcessingStepRef step_ref =
id_data.registerProcessingStep(step, search_ref);
id_to_step[prot.getIdentifier()] = step_ref;
id_data.setCurrentProcessingStep(step_ref);
ProgressLogger sublogger;
sublogger.setLogType(ProgressLogger::CMD);
String run_label = "(run " + String(proteins_counter) + "/" +
String(proteins.size()) + ")";
// ProteinHit:
sublogger.startProgress(0, prot.getHits().size(),
"converting protein hits " + run_label);
Size hits_counter = 0;
for (const ProteinHit& hit : prot.getHits())
{
++hits_counter;
sublogger.setProgress(hits_counter);
ID::ParentSequence parent(hit.getAccession());
parent.sequence = hit.getSequence();
parent.description = hit.getDescription();
// coverage comes in percents, -1 for missing; we want 0 to 1:
parent.coverage = max(hit.getCoverage(), 0.0) / 100.0;
parent.addMetaValues(hit);
ID::AppliedProcessingStep applied(step_ref);
if (!missing_protein_score_type)
{ // discard scores without proper CV term
applied.scores[prot_score_ref] = hit.getScore();
}
parent.steps_and_scores.push_back(applied);
id_data.registerParentSequence(parent);
}
sublogger.endProgress();
// indistinguishable protein groups:
if (!prot.getIndistinguishableProteins().empty())
{
sublogger.startProgress(0, prot.getIndistinguishableProteins().size(),
"converting indistinguishable proteins " +
run_label);
Size groups_counter = 0;
ID::ScoreType score("probability", true);
ID::ScoreTypeRef score_ref = id_data.registerScoreType(score);
ID::ParentGroupSet grouping;
grouping.label = "indistinguishable proteins";
for (const auto& group : prot.getIndistinguishableProteins())
{
++groups_counter;
sublogger.setProgress(groups_counter);
ID::ParentGroup new_group;
new_group.scores[score_ref] = group.probability;
for (const String& acc : group.accessions)
{
// note: protein referenced from indistinguishable group was already registered
ID::ParentSequenceRef ref = id_data.getParentSequences().find(acc);
OPENMS_POSTCONDITION("Protein ID referenced from indistinguishable group is missing.", ref !=id_data.getParentSequences().end());
new_group.parent_refs.insert(ref);
}
grouping.groups.insert(new_group);
}
id_data.registerParentGroupSet(grouping);
sublogger.endProgress();
}
// other protein groups:
if (!prot.getProteinGroups().empty())
{
sublogger.startProgress(0, prot.getProteinGroups().size(),
"converting protein groups " + run_label);
Size groups_counter = 0;
ID::ScoreType score("probability", true);
ID::ScoreTypeRef score_ref = id_data.registerScoreType(score);
ID::ParentGroupSet grouping;
grouping.label = "protein groups";
for (const auto& group : prot.getProteinGroups())
{
++groups_counter;
sublogger.setProgress(groups_counter);
ID::ParentGroup new_group;
new_group.scores[score_ref] = group.probability;
for (const String& acc : group.accessions)
{
// note: protein referenced from general protein group was already registered
ID::ParentSequenceRef ref = id_data.getParentSequences().find(acc);
OPENMS_POSTCONDITION("Protein ID referenced from general protein group is missing.", ref !=id_data.getParentSequences().end());
new_group.parent_refs.insert(ref);
}
grouping.groups.insert(new_group);
}
id_data.registerParentGroupSet(grouping);
sublogger.endProgress();
}
id_data.clearCurrentProcessingStep();
}
progresslogger.endProgress();
// PeptideIdentification:
Size unknown_obs_counter = 1;
progresslogger.startProgress(0, peptides.size(),
"converting peptide identifications");
Size peptides_counter = 0;
for (const PeptideIdentification& pep : peptides)
{
peptides_counter++;
progresslogger.setProgress(peptides_counter);
const String& id = pep.getIdentifier();
ID::ProcessingStepRef step_ref = id_to_step.at(id);
ID::InputFileRef inputfile;
if (!pep.getBaseName().empty())
{
inputfile = id_data.registerInputFile(ID::InputFile(pep.getBaseName()));
}
else
{
if (!step_ref->input_file_refs.empty())
{
if (step_ref->input_file_refs.size() > 1)
{ // Undo the hack needed in the legacy id datastructure to represent merged id files. Extract the actual input file name so we can properly register it.
if (pep.metaValueExists(Constants::UserParam::ID_MERGE_INDEX))
{
inputfile = step_ref->input_file_refs[pep.getMetaValue(Constants::UserParam::ID_MERGE_INDEX)];
}
else
{
throw Exception::ElementNotFound(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
String("Multiple file origins in ProteinIdentification Run but no '") + Constants::UserParam::ID_MERGE_INDEX + String("' metavalue in PeptideIdentification.")
);
}
}
else // one file in the ProteinIdentification Run only
{
inputfile = step_ref->input_file_refs[0];
}
}
else
{ // no input file annotated in legacy data structure
inputfile = id_data.registerInputFile(ID::InputFile("UNKNOWN_INPUT_FILE_" + id));
}
}
String data_id; // an identifier unique to the input file
if (pep.metaValueExists("spectrum_reference"))
{ // use spectrum native id if present
data_id = pep.getSpectrumReference();
}
else
{
if (pep.hasRT() && pep.hasMZ())
{
data_id = String("RT=") + String(float(pep.getRT())) + "_MZ=" +
String(float(pep.getMZ()));
}
else
{
data_id = "UNKNOWN_OBSERVATION_" + String(unknown_obs_counter);
++unknown_obs_counter;
}
}
ID::Observation obs{data_id, inputfile, pep.getRT(), pep.getMZ()};
obs.addMetaValues(pep);
if (obs.metaValueExists("spectrum_reference"))
{
obs.removeMetaValue("spectrum_reference");
}
obs.removeMetaValue(Constants::UserParam::SIGNIFICANCE_THRESHOLD);
ID::ObservationRef obs_ref = id_data.registerObservation(obs);
ID::ScoreType score_type(pep.getScoreType(), pep.isHigherScoreBetter());
ID::ScoreTypeRef score_ref = id_data.registerScoreType(score_type);
// PeptideHit:
for (const PeptideHit& hit : pep.getHits())
{
if (hit.getSequence().empty())
{
OPENMS_LOG_WARN << "Warning: Trying to import PeptideHit without a sequence. This should not happen!" << std::endl;
continue;
}
ID::IdentifiedPeptide peptide(hit.getSequence());
peptide.addProcessingStep(step_ref);
for (const PeptideEvidence& evidence : hit.getPeptideEvidences())
{
const String& accession = evidence.getProteinAccession();
if (accession.empty()) continue;
ID::ParentSequence parent(accession);
parent.addProcessingStep(step_ref);
// this will merge information if the protein already exists:
ID::ParentSequenceRef parent_ref =
id_data.registerParentSequence(parent);
ID::ParentMatch parent_match(evidence.getStart(), evidence.getEnd(),
evidence.getAABefore(),
evidence.getAAAfter());
peptide.parent_matches[parent_ref].insert(parent_match);
}
ID::IdentifiedPeptideRef peptide_ref =
id_data.registerIdentifiedPeptide(peptide);
ID::ObservationMatch match(peptide_ref, obs_ref);
match.charge = hit.getCharge();
match.addMetaValues(hit);
if (!hit.getPeakAnnotations().empty())
{
match.peak_annotations[step_ref] = hit.getPeakAnnotations();
}
ID::AppliedProcessingStep applied(step_ref);
applied.scores[score_ref] = hit.getScore();
// analysis results from pepXML:
for (const PeptideHit::PepXMLAnalysisResult& ana_res :
hit.getAnalysisResults())
{
ID::ProcessingSoftware software;
software.setName(ana_res.score_type); // e.g. "peptideprophet"
ID::AppliedProcessingStep sub_applied;
ID::ScoreType main_score;
main_score.cv_term.setName(ana_res.score_type + "_probability");
main_score.higher_better = ana_res.higher_is_better;
ID::ScoreTypeRef main_score_ref =
id_data.registerScoreType(main_score);
software.assigned_scores.push_back(main_score_ref);
sub_applied.scores[main_score_ref] = ana_res.main_score;
for (const pair<const String, double>& sub_pair : ana_res.sub_scores)
{
ID::ScoreType sub_score;
sub_score.cv_term.setName(sub_pair.first);
ID::ScoreTypeRef sub_score_ref =
id_data.registerScoreType(sub_score);
software.assigned_scores.push_back(sub_score_ref);
sub_applied.scores[sub_score_ref] = sub_pair.second;
}
ID::ProcessingSoftwareRef software_ref =
id_data.registerProcessingSoftware(software);
ID::ProcessingStep sub_step(software_ref);
sub_step.input_file_refs.push_back(obs.input_file);
ID::ProcessingStepRef sub_step_ref =
id_data.registerProcessingStep(sub_step);
sub_applied.processing_step_opt = sub_step_ref;
match.addProcessingStep(sub_applied);
}
// most recent step (with primary score) goes last:
match.addProcessingStep(applied);
try
{
id_data.registerObservationMatch(match);
}
catch (Exception::InvalidValue& error)
{
OPENMS_LOG_ERROR << "Error: failed to register observation match - skipping.\n"
<< "Message was: " << error.getMessage() << endl;
}
}
}
progresslogger.endProgress();
}
void IdentificationDataConverter::exportIDs(IdentificationData const& id_data,
vector <ProteinIdentification>& proteins,
PeptideIdentificationList& peptides,
bool export_ids_wo_scores)
{
// "Observation" roughly corresponds to "PeptideIdentification",
// "ProcessingStep" roughly corresponds to "ProteinIdentification";
// score type is stored in "PeptideIdent.", not "PeptideHit":
map<pair<ID::ObservationRef, std::optional<ID::ProcessingStepRef>>,
pair<vector<PeptideHit>, ID::ScoreTypeRef>> psm_data;
// we only export peptides and proteins (or oligos and RNAs), so start by
// getting the PSMs (or OSMs):
for (const ID::ObservationMatch& input_match :
id_data.getObservationMatches())
{
PeptideHit hit;
hit.addMetaValues(input_match);
const ID::IdentifiedMolecule& molecule_var = input_match.identified_molecule_var;
const ID::ParentMatches* parent_matches_ptr = nullptr;
if (molecule_var.getMoleculeType() == ID::MoleculeType::PROTEIN)
{
ID::IdentifiedPeptideRef peptide_ref = molecule_var.getIdentifiedPeptideRef();
hit.setSequence(peptide_ref->sequence);
parent_matches_ptr = &(peptide_ref->parent_matches);
}
else if (molecule_var.getMoleculeType() == ID::MoleculeType::RNA)
{
ID::IdentifiedOligoRef oligo_ref = molecule_var.getIdentifiedOligoRef();
hit.setMetaValue("label", oligo_ref->sequence.toString());
hit.setMetaValue("molecule_type", "RNA");
parent_matches_ptr = &(oligo_ref->parent_matches);
}
else // small molecule
{
ID::IdentifiedCompoundRef compound_ref = molecule_var.getIdentifiedCompoundRef();
// @TODO: use "name" member instead of "identifier" here?
hit.setMetaValue("label", compound_ref->identifier);
hit.setMetaValue("molecule_type", "compound");
}
if (parent_matches_ptr != nullptr)
{
exportParentMatches(*parent_matches_ptr, hit);
}
hit.setCharge(input_match.charge);
if (input_match.adduct_opt)
{
hit.setMetaValue("adduct", (*input_match.adduct_opt)->getName());
}
// generate hits in different ID runs for different processing steps:
for (const ID::AppliedProcessingStep& applied : input_match.steps_and_scores)
{
//Note: this skips ObservationMatches without score if not prevented. This often removes fake/dummy/transfer/seed IDs.
if (applied.scores.empty() && !export_ids_wo_scores)
{
OPENMS_LOG_WARN << "Warning: trying to export ObservationMatch without score. Skipping.." << std::endl;
continue;
}
PeptideHit hit_copy = hit;
vector<pair<ID::ScoreTypeRef, double>> scores =
applied.getScoresInOrder();
// "primary" score comes first:
hit_copy.setScore(scores[0].second);
// add meta values for "secondary" scores:
for (auto it = ++scores.begin(); it != scores.end(); ++it)
{
hit_copy.setMetaValue(it->first->cv_term.getName(), it->second);
}
auto pos =
input_match.peak_annotations.find(applied.processing_step_opt);
if (pos != input_match.peak_annotations.end())
{
hit_copy.setPeakAnnotations(pos->second);
}
auto key = make_pair(input_match.observation_ref,
applied.processing_step_opt);
psm_data[key].first.push_back(hit_copy);
psm_data[key].second = scores[0].first; // primary score type
}
}
// order steps by date, if available:
set<StepOpt, StepOptCompare> steps;
for (const auto& obsref_stepopt2vechits_scoretype : psm_data)
{
const ID::Observation& obs = *obsref_stepopt2vechits_scoretype.first.first;
PeptideIdentification peptide;
peptide.addMetaValues(obs);
// set RT and m/z if they aren't missing (NaN):
if (obs.rt == obs.rt) peptide.setRT(obs.rt);
if (obs.mz == obs.mz) peptide.setMZ(obs.mz);
peptide.setSpectrumReference( obs.data_id);
peptide.setHits(obsref_stepopt2vechits_scoretype.second.first);
const ID::ScoreType& score_type = *obsref_stepopt2vechits_scoretype.second.second;
peptide.setScoreType(score_type.cv_term.getName());
peptide.setHigherScoreBetter(score_type.higher_better);
if (obsref_stepopt2vechits_scoretype.first.second) // processing step given
{
peptide.setIdentifier(String(Size(&(**obsref_stepopt2vechits_scoretype.first.second))));
}
else
{
peptide.setIdentifier("dummy");
}
peptides.push_back(peptide);
steps.insert(obsref_stepopt2vechits_scoretype.first.second);
}
// sort peptide IDs by RT and m/z to improve reproducibility:
sort(peptides.begin(), peptides.end(), PepIDCompare());
map<StepOpt, pair<vector<ProteinHit>, ID::ScoreTypeRef>> prot_data;
for (const auto& parent : id_data.getParentSequences())
{
ProteinHit hit;
hit.setAccession(parent.accession);
hit.setSequence(parent.sequence);
hit.setDescription(parent.description);
if (parent.coverage > 0.0)
{
hit.setCoverage(parent.coverage * 100.0); // convert to percents
}
else // zero coverage means coverage is unknown
{
hit.setCoverage(ProteinHit::COVERAGE_UNKNOWN);
}
hit.clearMetaInfo();
hit.addMetaValues(parent);
if (!parent.metaValueExists("target_decoy"))
{
hit.setMetaValue("target_decoy", parent.is_decoy ? "decoy" : "target");
}
// generate hits in different ID runs for different processing steps:
for (const ID::AppliedProcessingStep& applied : parent.steps_and_scores)
{
if (applied.scores.empty() && !steps.count(applied.processing_step_opt))
{
continue; // no scores and no associated peptides -> skip
}
ProteinHit hit_copy = hit;
if (!applied.scores.empty())
{
vector<pair<ID::ScoreTypeRef, double>> scores =
applied.getScoresInOrder();
// "primary" score comes first:
hit_copy.setScore(scores[0].second);
// add meta values for "secondary" scores:
for (auto it = ++scores.begin(); it != scores.end(); ++it)
{
hit_copy.setMetaValue(it->first->cv_term.getName(), it->second);
}
prot_data[applied.processing_step_opt].first.push_back(hit_copy);
prot_data[applied.processing_step_opt].second = scores[0].first;
continue;
}
// always include steps that have generated peptides:
auto pos = prot_data.find(applied.processing_step_opt);
if (pos != prot_data.end())
{
pos->second.first.push_back(hit);
// existing entry, don't overwrite score type
}
else
{
prot_data[applied.processing_step_opt].first.push_back(hit);
prot_data[applied.processing_step_opt].second =
id_data.getScoreTypes().end(); // no score given
}
}
}
for (const auto& step_ref_opt : steps)
{
ProteinIdentification protein;
if (!step_ref_opt) // no processing step given
{
protein.setIdentifier("dummy");
}
else
{
ID::ProcessingStepRef step_ref = *step_ref_opt;
protein.setIdentifier(String(Size(&(*step_ref))));
protein.setDateTime(step_ref->date_time);
exportMSRunInformation_(step_ref, protein);
const Software& software = *step_ref->software_ref;
protein.setSearchEngine(software.getName());
protein.setSearchEngineVersion(software.getVersion());
ID::DBSearchSteps::const_iterator ss_pos =
id_data.getDBSearchSteps().find(step_ref);
if (ss_pos != id_data.getDBSearchSteps().end())
{
protein.setSearchParameters(exportDBSearchParameters_(ss_pos->second));
}
}
auto pd_pos = prot_data.find(step_ref_opt);
if (pd_pos != prot_data.end())
{
protein.setHits(pd_pos->second.first);
if (pd_pos->second.second != id_data.getScoreTypes().end())
{
const ID::ScoreType& score_type = *pd_pos->second.second;
protein.setScoreType(score_type.cv_term.getName());
protein.setHigherScoreBetter(score_type.higher_better);
}
}
// protein groups:
for (const auto& grouping : id_data.getParentGroupSets())
{
// do these protein groups belong to the current search run?
if (grouping.getStepsAndScoresByStep().find(step_ref_opt) !=
grouping.getStepsAndScoresByStep().end())
{
for (const auto& group : grouping.groups)
{
ProteinIdentification::ProteinGroup new_group;
if (!group.scores.empty())
{
// @TODO: what if there are several scores?
new_group.probability = group.scores.begin()->second;
}
for (const auto& parent_ref : group.parent_refs)
{
new_group.accessions.push_back(parent_ref->accession);
}
sort(new_group.accessions.begin(), new_group.accessions.end());
if (grouping.label == "indistinguishable proteins")
{
protein.insertIndistinguishableProteins(new_group);
}
else
{
protein.insertProteinGroup(new_group);
}
}
}
}
sort(protein.getIndistinguishableProteins().begin(),
protein.getIndistinguishableProteins().end());
sort(protein.getProteinGroups().begin(),
protein.getProteinGroups().end());
proteins.push_back(protein);
}
}
MzTab IdentificationDataConverter::exportMzTab(const IdentificationData&
id_data)
{
MzTabMetaData meta;
Size counter = 1;
for (const auto& software : id_data.getProcessingSoftwares())
{
MzTabSoftwareMetaData sw_meta;
sw_meta.software.setName(software.getName());
sw_meta.software.setValue(software.getVersion());
meta.software[counter] = sw_meta;
++counter;
}
counter = 1;
map<ID::InputFileRef, Size> file_map;
for (auto it = id_data.getInputFiles().begin();
it != id_data.getInputFiles().end(); ++it)
{
MzTabMSRunMetaData run_meta;
run_meta.location.set(it->name);
meta.ms_run[counter] = run_meta;
file_map[it] = counter;
++counter;
}
set<String> fixed_mods, variable_mods;
for (const auto& search_param : id_data.getDBSearchParams())
{
fixed_mods.insert(search_param.fixed_mods.begin(),
search_param.fixed_mods.end());
variable_mods.insert(search_param.variable_mods.begin(),
search_param.variable_mods.end());
}
counter = 1;
for (const String& mod : fixed_mods)
{
MzTabModificationMetaData mod_meta;
mod_meta.modification.setName(mod);
meta.fixed_mod[counter] = mod_meta;
++counter;
}
counter = 1;
for (const String& mod : variable_mods)
{
MzTabModificationMetaData mod_meta;
mod_meta.modification.setName(mod);
meta.variable_mod[counter] = mod_meta;
++counter;
}
map<ID::ScoreTypeRef, Size> protein_scores, peptide_scores, psm_scores,
nucleic_acid_scores, oligonucleotide_scores, osm_scores;
// compound_scores;
MzTabProteinSectionRows proteins;
MzTabNucleicAcidSectionRows nucleic_acids;
for (const auto& parent : id_data.getParentSequences())
{
if (parent.molecule_type == ID::MoleculeType::PROTEIN)
{
exportParentSequenceToMzTab_(parent, proteins, protein_scores);
}
else if (parent.molecule_type == ID::MoleculeType::RNA)
{
exportParentSequenceToMzTab_(parent, nucleic_acids,
nucleic_acid_scores);
}
}
MzTabPeptideSectionRows peptides;
for (const auto& peptide : id_data.getIdentifiedPeptides())
{
exportPeptideOrOligoToMzTab_(peptide, peptides, peptide_scores);
}
MzTabOligonucleotideSectionRows oligos;
for (const auto& oligo : id_data.getIdentifiedOligos())
{
exportPeptideOrOligoToMzTab_(oligo, oligos, oligonucleotide_scores);
}
MzTabPSMSectionRows psms;
MzTabOSMSectionRows osms;
for (const auto& obs_match : id_data.getObservationMatches())
{
const ID::IdentifiedMolecule& molecule_var =
obs_match.identified_molecule_var;
// @TODO: what about small molecules?
ID::MoleculeType molecule_type = molecule_var.getMoleculeType();
if (molecule_type == ID::MoleculeType::PROTEIN)
{
const AASequence& seq = molecule_var.getIdentifiedPeptideRef()->sequence;
double calc_mass = seq.getMonoWeight(Residue::Full, obs_match.charge);
exportObservationMatchToMzTab_(seq.toString(), obs_match, calc_mass,
psms, psm_scores, file_map);
// "PSM_ID" field is set at the end, after sorting
}
else if (molecule_type == ID::MoleculeType::RNA)
{
const NASequence& seq = molecule_var.getIdentifiedOligoRef()->sequence;
double calc_mass = seq.getMonoWeight(NASequence::Full,
obs_match.charge);
exportObservationMatchToMzTab_(seq.toString(), obs_match, calc_mass,
osms, osm_scores, file_map);
}
}
addMzTabSEScores_(protein_scores, meta.protein_search_engine_score);
addMzTabSEScores_(peptide_scores, meta.peptide_search_engine_score);
addMzTabSEScores_(psm_scores, meta.psm_search_engine_score);
addMzTabSEScores_(nucleic_acid_scores,
meta.nucleic_acid_search_engine_score);
addMzTabSEScores_(oligonucleotide_scores,
meta.oligonucleotide_search_engine_score);
addMzTabSEScores_(osm_scores, meta.osm_search_engine_score);
// sort rows:
sort(proteins.begin(), proteins.end(),
MzTabProteinSectionRow::RowCompare());
sort(peptides.begin(), peptides.end(),
MzTabPeptideSectionRow::RowCompare());
sort(psms.begin(), psms.end(), MzTabPSMSectionRow::RowCompare());
// set "PSM_ID" fields - the IDs are repeated for peptides with multiple
// protein accessions; however, we don't write out the accessions on PSM
// level (only on peptide level), so just number consecutively:
for (Size i = 0; i < psms.size(); ++i)
{
psms[i].PSM_ID.set(i + 1);
}
sort(nucleic_acids.begin(), nucleic_acids.end(),
MzTabNucleicAcidSectionRow::RowCompare());
sort(oligos.begin(), oligos.end(),
MzTabOligonucleotideSectionRow::RowCompare());
sort(osms.begin(), osms.end(), MzTabOSMSectionRow::RowCompare());
MzTab output;
output.setMetaData(meta);
output.setProteinSectionRows(proteins);
output.setPeptideSectionRows(peptides);
output.setPSMSectionRows(psms);
output.setNucleicAcidSectionRows(nucleic_acids);
output.setOligonucleotideSectionRows(oligos);
output.setOSMSectionRows(osms);
return output;
}
void IdentificationDataConverter::importSequences(
IdentificationData& id_data, const vector<FASTAFile::FASTAEntry>& fasta,
ID::MoleculeType type, const String& decoy_pattern)
{
for (const FASTAFile::FASTAEntry& entry : fasta)
{
ID::ParentSequence parent(entry.identifier, type, entry.sequence,
entry.description);
if (!decoy_pattern.empty() &&
entry.identifier.hasSubstring(decoy_pattern))
{
parent.is_decoy = true;
}
id_data.registerParentSequence(parent);
}
}
void IdentificationDataConverter::exportParentMatches(
const ID::ParentMatches& parent_matches, PeptideHit& hit)
{
for (const auto& pair : parent_matches)
{
ID::ParentSequenceRef parent_ref = pair.first;
for (const ID::ParentMatch& parent_match : pair.second)
{
PeptideEvidence evidence;
evidence.setProteinAccession(parent_ref->accession);
evidence.setStart(parent_match.start_pos);
evidence.setEnd(parent_match.end_pos);
if (!parent_match.left_neighbor.empty())
{
evidence.setAABefore(parent_match.left_neighbor[0]);
}
if (!parent_match.right_neighbor.empty())
{
evidence.setAAAfter(parent_match.right_neighbor[0]);
}
hit.addPeptideEvidence(evidence);
}
}
// sort the evidences:
vector<PeptideEvidence> evidences = hit.getPeptideEvidences();
sort(evidences.begin(), evidences.end());
hit.setPeptideEvidences(evidences);
}
void IdentificationDataConverter::exportStepsAndScoresToMzTab_(
const ID::AppliedProcessingSteps& steps_and_scores,
MzTabParameterList& steps_out, map<Size, MzTabDouble>& scores_out,
map<ID::ScoreTypeRef, Size>& score_map)
{
vector<MzTabParameter> search_engines;
set<ID::ProcessingSoftwareRef> sw_refs;
for (const ID::AppliedProcessingStep& applied : steps_and_scores)
{
if (applied.processing_step_opt)
{
ID::ProcessingSoftwareRef sw_ref =
(*applied.processing_step_opt)->software_ref;
// mention each search engine only once:
if (!sw_refs.count(sw_ref))
{
MzTabParameter param;
param.setName(sw_ref->getName());
param.setValue(sw_ref->getVersion());
search_engines.push_back(param);
sw_refs.insert(sw_ref);
}
}
else
{
MzTabParameter param;
param.setName("unknown");
search_engines.push_back(param);
}
for (const pair<ID::ScoreTypeRef, double>& score_pair :
applied.getScoresInOrder())
{
if (!score_map.count(score_pair.first)) // new score type
{
score_map.insert(make_pair(score_pair.first, score_map.size() + 1));
}
Size index = score_map[score_pair.first];
scores_out[index].set(score_pair.second);
}
}
steps_out.set(search_engines);
}
void IdentificationDataConverter::addMzTabSEScores_(
const map<ID::ScoreTypeRef, Size>& scores,
map<Size, MzTabParameter>& output)
{
for (const pair<const ID::ScoreTypeRef, Size>& score_pair : scores)
{
const ID::ScoreType& score_type = *score_pair.first;
MzTabParameter param;
param.setName(score_type.cv_term.getName());
param.setAccession(score_type.cv_term.getAccession());
param.setCVLabel(score_type.cv_term.getCVIdentifierRef());
output[score_pair.second] = param;
}
}
void IdentificationDataConverter::addMzTabMoleculeParentContext_(
const ID::ParentMatch& match, MzTabOligonucleotideSectionRow& row)
{
if (match.left_neighbor == String(ID::ParentMatch::LEFT_TERMINUS))
{
row.pre.set("-");
}
else if (match.left_neighbor !=
String(ID::ParentMatch::UNKNOWN_NEIGHBOR))
{
row.pre.set(match.left_neighbor);
}
if (match.right_neighbor == String(ID::ParentMatch::RIGHT_TERMINUS))
{
row.post.set("-");
}
else if (match.right_neighbor !=
String(ID::ParentMatch::UNKNOWN_NEIGHBOR))
{
row.post.set(match.right_neighbor);
}
if (match.start_pos != ID::ParentMatch::UNKNOWN_POSITION)
{
row.start.set(match.start_pos + 1);
}
if (match.end_pos != ID::ParentMatch::UNKNOWN_POSITION)
{
row.end.set(match.end_pos + 1);
}
}
void IdentificationDataConverter::addMzTabMoleculeParentContext_(
const ID::ParentMatch& /* match */,
MzTabPeptideSectionRow& /* row */)
{
// nothing to do here
}
ID::SearchParamRef IdentificationDataConverter::importDBSearchParameters_(
const ProteinIdentification::SearchParameters& pisp,
IdentificationData& id_data)
{
ID::DBSearchParam dbsp;
dbsp.molecule_type = ID::MoleculeType::PROTEIN;
dbsp.mass_type = ID::MassType(pisp.mass_type);
dbsp.database = pisp.db;
dbsp.database_version = pisp.db_version;
dbsp.taxonomy = pisp.taxonomy;
pair<int, int> charge_range = pisp.getChargeRange();
for (int charge = charge_range.first; charge <= charge_range.second;
++charge)
{
dbsp.charges.insert(charge);
}
dbsp.fixed_mods.insert(pisp.fixed_modifications.begin(),
pisp.fixed_modifications.end());
dbsp.variable_mods.insert(pisp.variable_modifications.begin(),
pisp.variable_modifications.end());
dbsp.precursor_mass_tolerance = pisp.precursor_mass_tolerance;
dbsp.fragment_mass_tolerance = pisp.fragment_mass_tolerance;
dbsp.precursor_tolerance_ppm = pisp.precursor_mass_tolerance_ppm;
dbsp.fragment_tolerance_ppm = pisp.fragment_mass_tolerance_ppm;
const String& enzyme_name = pisp.digestion_enzyme.getName();
if (ProteaseDB::getInstance()->hasEnzyme(enzyme_name))
{
dbsp.digestion_enzyme = ProteaseDB::getInstance()->getEnzyme(enzyme_name);
}
dbsp.missed_cleavages = pisp.missed_cleavages;
dbsp.enzyme_term_specificity = pisp.enzyme_term_specificity;
static_cast<MetaInfoInterface&>(dbsp) = pisp;
return id_data.registerDBSearchParam(dbsp);
}
ProteinIdentification::SearchParameters
IdentificationDataConverter::exportDBSearchParameters_(ID::SearchParamRef ref)
{
const ID::DBSearchParam& dbsp = *ref;
ProteinIdentification::SearchParameters pisp;
pisp.mass_type = ProteinIdentification::PeakMassType(dbsp.mass_type);
pisp.db = dbsp.database;
pisp.db_version = dbsp.database_version;
pisp.taxonomy = dbsp.taxonomy;
pisp.charges = ListUtils::concatenate(dbsp.charges, ", ");
pisp.fixed_modifications.insert(pisp.fixed_modifications.end(),
dbsp.fixed_mods.begin(),
dbsp.fixed_mods.end());
pisp.variable_modifications.insert(pisp.variable_modifications.end(),
dbsp.variable_mods.begin(),
dbsp.variable_mods.end());
pisp.precursor_mass_tolerance = dbsp.precursor_mass_tolerance;
pisp.fragment_mass_tolerance = dbsp.fragment_mass_tolerance;
pisp.precursor_mass_tolerance_ppm = dbsp.precursor_tolerance_ppm;
pisp.fragment_mass_tolerance_ppm = dbsp.fragment_tolerance_ppm;
if (dbsp.digestion_enzyme && (dbsp.molecule_type ==
ID::MoleculeType::PROTEIN))
{
pisp.digestion_enzyme =
*(static_cast<const DigestionEnzymeProtein*>(dbsp.digestion_enzyme));
}
else
{
pisp.digestion_enzyme = DigestionEnzymeProtein("unknown_enzyme", "");
}
pisp.missed_cleavages = dbsp.missed_cleavages;
static_cast<MetaInfoInterface&>(pisp) = dbsp;
return pisp;
}
void IdentificationDataConverter::exportMSRunInformation_(
ID::ProcessingStepRef step_ref, ProteinIdentification& protein)
{
for (ID::InputFileRef input_ref : step_ref->input_file_refs)
{
// @TODO: check if files are mzMLs?
protein.addPrimaryMSRunPath(input_ref->name);
for (const String& primary_file : input_ref->primary_files)
{
protein.addPrimaryMSRunPath(primary_file, true);
}
}
}
void IdentificationDataConverter::importFeatureIDs(FeatureMap& features,
bool clear_original)
{
// collect all peptide IDs:
PeptideIdentificationList peptides = features.getUnassignedPeptideIdentifications();
// get peptide IDs from each feature and its subordinates, add meta values:
Size id_counter = 0;
for (Size i = 0; i < features.size(); ++i)
{
handleFeatureImport_(features[i], IntList(1, i), peptides, id_counter, clear_original);
}
IdentificationData& id_data = features.getIdentificationData();
importIDs(id_data, features.getProteinIdentifications(), peptides);
// map converted IDs back to features using meta values assigned in "handleFeatureImport_";
for (ID::ObservationMatchRef ref = id_data.getObservationMatches().begin();
ref != id_data.getObservationMatches().end(); ++ref)
{
vector<String> meta_keys;
ref->getKeys(meta_keys);
for (const String& key : meta_keys)
{
if (key.hasPrefix("IDConverter_trace_"))
{
IntList indexes = ref->getMetaValue(key);
Feature* feat_ptr = &features.at(indexes[0]);
for (Size i = 1; i < indexes.size(); ++i)
{
feat_ptr = &feat_ptr->getSubordinates()[indexes[i]];
}
feat_ptr->addIDMatch(ref);
id_data.removeMetaValue(ref, key);
}
}
}
if (clear_original)
{
features.getUnassignedPeptideIdentifications().clear();
features.getProteinIdentifications().clear();
}
}
void IdentificationDataConverter::handleFeatureImport_(Feature& feature, const IntList& indexes,
PeptideIdentificationList& peptides,
Size& id_counter, bool clear_original)
{
for (const PeptideIdentification& pep : feature.getPeptideIdentifications())
{
peptides.push_back(pep);
// store trace of feature indexes so we can map the converted ID back;
// key needs to be unique in case the same ID matches multiple features:
String key = "IDConverter_trace_" + String(id_counter);
for (PeptideHit& hit : peptides.back().getHits())
{
hit.setMetaValue(key, indexes);
}
++id_counter;
}
if (clear_original) feature.getPeptideIdentifications().clear();
for (Size i = 0; i < feature.getSubordinates().size(); ++i)
{
IntList extended = indexes;
extended.push_back(i);
handleFeatureImport_(feature.getSubordinates()[i], extended, peptides,
id_counter, clear_original);
}
}
void IdentificationDataConverter::exportFeatureIDs(FeatureMap& features,
bool clear_original)
{
Size id_counter = 0;
// Adds dummy Obs.Match for features with ID but no matches. Adds "IDConverter_trace" meta value
// to Matches for every feature/subfeature they are contained in
// e.g. 3,1,2 for a Match in subfeature 2 of subfeature 1 of feature 3
for (Size i = 0; i < features.size(); ++i)
{
handleFeatureExport_(features[i], IntList(1, i),
features.getIdentificationData(), id_counter);
}
exportIDs(features.getIdentificationData(), features.getProteinIdentifications(),
features.getUnassignedPeptideIdentifications(), false);
// map converted IDs back to features using meta values assigned in "handleFeatureExport_";
// in principle, different "observation matches" from one "observation"
// can map to different features, which makes things complicated when they
// are converted to "peptide hits"/"peptide identifications"...
auto& pep_ids = features.getUnassignedPeptideIdentifications();
for (Size i = 0; i < pep_ids.size(); )
{
PeptideIdentification& pep = pep_ids[i];
// move hits outside of peptide ID so ID can be copied without the hits:
vector<PeptideHit> all_hits;
all_hits.swap(pep.getHits());
vector<bool> assigned_hits(all_hits.size(), false);
// which hits map to which features:
map<Feature*, set<Size>> features_to_hits;
for (Size j = 0; j < all_hits.size(); ++j)
{
PeptideHit& hit = all_hits[j];
vector<String> meta_keys;
hit.getKeys(meta_keys);
for (const String& key : meta_keys)
{ // ID-data stores a trace (path through the feature-subfeature hierarchy) which is used
// for a lookup to attach the converted IDs back to the specific feature.
if (key.hasPrefix("IDConverter_trace_"))
{
IntList indexes = hit.getMetaValue(key);
hit.removeMetaValue(key);
Feature* feat_ptr = &features.at(indexes[0]);
for (Size k = 1; k < indexes.size(); ++k)
{
feat_ptr = &feat_ptr->getSubordinates()[indexes[k]];
}
features_to_hits[feat_ptr].insert(j);
assigned_hits[j] = true;
}
}
}
// copy peptide ID with corresponding hits to relevant features:
for (auto& pair : features_to_hits)
{
auto& feat_ids = pair.first->getPeptideIdentifications();
feat_ids.push_back(pep);
for (Size hit_index : pair.second)
{
feat_ids.back().getHits().push_back(all_hits[hit_index]);
}
}
bool all_assigned = all_of(assigned_hits.begin(), assigned_hits.end(),
[](bool b) { return b; });
if (all_assigned) // remove peptide ID from unassigned IDs
{
pep_ids.erase(pep_ids.begin() + i);
// @TODO: use "std::remove" to make this more efficient
}
else // only keep hits that weren't assigned:
{
for (Size j = 0; j < assigned_hits.size(); ++j)
{
if (!assigned_hits[j])
{
pep.getHits().push_back(all_hits[j]);
}
}
++i;
}
}
if (clear_original)
{
features.getIdentificationData().clear();
for (auto& feat : features)
{
feat.clearPrimaryID();
feat.getIDMatches().clear();
}
}
}
void IdentificationDataConverter::handleFeatureExport_(
Feature& feature, const IntList& indexes, IdentificationData& id_data, Size& id_counter)
{
if (feature.getIDMatches().empty() && feature.hasPrimaryID())
{
// primary ID without supporting ID matches - generate a "dummy" ID match
// so we can export it:
ID::InputFile file("ConvertedFromFeature");
ID::InputFileRef file_ref = id_data.registerInputFile(file);
ID::Observation obs(String(feature.getUniqueId()), file_ref,
feature.getRT(), feature.getMZ());
ID::ObservationRef obs_ref = id_data.registerObservation(obs);
ID::ObservationMatch match(feature.getPrimaryID(), obs_ref,
feature.getCharge());
ID::ObservationMatchRef match_ref = id_data.registerObservationMatch(match);
feature.addIDMatch(match_ref);
}
for (ID::ObservationMatchRef ref : feature.getIDMatches())
{
// store trace of feature indexes so we can map the converted ID back;
// key needs to be unique in case the same ID matches multiple features:
String key = "IDConverter_trace_" + String(id_counter);
id_data.setMetaValue(ref, key, indexes);
++id_counter;
}
for (Size i = 0; i < feature.getSubordinates().size(); ++i)
{
IntList extended = indexes;
extended.push_back(i);
handleFeatureExport_(feature.getSubordinates()[i], extended, id_data,
id_counter);
}
}
void IdentificationDataConverter::importConsensusIDs(ConsensusMap& consensus,
bool clear_original)
{
// copy identification information in old format to new format;
// i.e. from 'protein_identifications_'/'unassigned_peptide_identifications_' (consensus map)
// and 'peptides_' (features) to 'id_data_' (consensus map) and 'primary_id_'/'id_matches_' (features);
// use meta values to temporarily store which features IDs are assigned to
// collect all peptide IDs:
PeptideIdentificationList peptides = consensus.getUnassignedPeptideIdentifications();
// get peptide IDs from each consensus feature, add meta values:
Size id_counter = 0;
for (Size i = 0; i < consensus.size(); ++i)
{
ConsensusFeature& feature = consensus[i];
for (const PeptideIdentification& pep : feature.getPeptideIdentifications())
{
peptides.push_back(pep);
// store feature index so we can map the converted ID back;
// key needs to be unique in case the same ID matches multiple features:
String key = "IDConverter_trace_" + String(id_counter);
for (PeptideHit& hit : peptides.back().getHits())
{
hit.setMetaValue(key, i);
}
++id_counter;
}
if (clear_original) feature.getPeptideIdentifications().clear();
}
IdentificationData& id_data = consensus.getIdentificationData();
importIDs(id_data, consensus.getProteinIdentifications(), peptides);
// map converted IDs back to consensus features using meta values assigned above:
for (ID::ObservationMatchRef ref = id_data.getObservationMatches().begin();
ref != id_data.getObservationMatches().end(); ++ref)
{
vector<String> meta_keys;
ref->getKeys(meta_keys);
for (const String& key : meta_keys)
{
if (key.hasPrefix("IDConverter_trace_"))
{
Size index = ref->getMetaValue(key);
ConsensusFeature& feat = consensus.at(index);
feat.addIDMatch(ref);
id_data.removeMetaValue(ref, key);
}
}
}
if (clear_original)
{
consensus.getUnassignedPeptideIdentifications().clear();
consensus.getProteinIdentifications().clear();
}
}
void IdentificationDataConverter::exportConsensusIDs(ConsensusMap& consensus,
bool clear_original)
{
// copy identification information in new format to old format;
// i.e. from 'id_data_' (consensus map) and 'primary_id_'/'id_matches_' (features)
// to 'protein_identifications_'/'unassigned_peptide_identifications_' (consensus map)
// and 'peptides_' (features);
// use meta values to temporarily store which features IDs are assigned to
Size id_counter = 0;
IdentificationData& id_data = consensus.getIdentificationData();
// Adds dummy Obs.Match for features with ID but no matches.
// Adds "IDConverter_trace" meta value to Matches for every feature they are contained in
for (Size i = 0; i < consensus.size(); ++i)
{
ConsensusFeature& feature = consensus[i];
if (feature.getIDMatches().empty() && feature.hasPrimaryID())
{
// primary ID without supporting ID matches - generate a "dummy" ID match
// so we can export it:
ID::InputFile file("ConvertedFromFeature");
ID::InputFileRef file_ref = id_data.registerInputFile(file);
ID::Observation obs(String(feature.getUniqueId()), file_ref,
feature.getRT(), feature.getMZ());
ID::ObservationRef obs_ref = id_data.registerObservation(obs);
ID::ObservationMatch match(feature.getPrimaryID(), obs_ref,
feature.getCharge());
ID::ObservationMatchRef match_ref = id_data.registerObservationMatch(match);
feature.addIDMatch(match_ref);
}
for (ID::ObservationMatchRef ref : feature.getIDMatches())
{
// store trace of feature indexes so we can map the converted ID back;
// key needs to be unique in case the same ID matches multiple features:
String key = "IDConverter_trace_" + String(id_counter);
id_data.setMetaValue(ref, key, i);
++id_counter;
}
}
exportIDs(consensus.getIdentificationData(), consensus.getProteinIdentifications(),
consensus.getUnassignedPeptideIdentifications(), false);
// map converted IDs back to features using meta values assigned above;
// in principle, different "observation matches" from one "observation"
// can map to different features, which makes things complicated when they
// are converted to "peptide hits"/"peptide identifications"...
auto& pep_ids = consensus.getUnassignedPeptideIdentifications();
for (Size i = 0; i < pep_ids.size(); )
{
PeptideIdentification& pep = pep_ids[i];
// move hits outside of peptide ID so ID can be copied without the hits:
vector<PeptideHit> all_hits;
all_hits.swap(pep.getHits());
vector<bool> assigned_hits(all_hits.size(), false);
// which hits map to which features:
map<ConsensusFeature*, set<Size>> features_to_hits;
for (Size j = 0; j < all_hits.size(); ++j)
{
PeptideHit& hit = all_hits[j];
vector<String> meta_keys;
hit.getKeys(meta_keys);
for (const String& key : meta_keys)
{ // ID-data stores a trace (feature index) which is used for a lookup
// to attach the converted IDs back to the specific feature.
if (key.hasPrefix("IDConverter_trace_"))
{
Size index = hit.getMetaValue(key);
hit.removeMetaValue(key);
ConsensusFeature* feat_ptr = &consensus.at(index);
features_to_hits[feat_ptr].insert(j);
assigned_hits[j] = true;
}
}
}
// copy peptide ID with corresponding hits to relevant features:
for (auto& pair : features_to_hits)
{
auto& feat_ids = pair.first->getPeptideIdentifications();
feat_ids.push_back(pep);
for (Size hit_index : pair.second)
{
feat_ids.back().getHits().push_back(all_hits[hit_index]);
}
}
bool all_assigned = all_of(assigned_hits.begin(), assigned_hits.end(),
[](bool b) { return b; });
if (all_assigned) // remove peptide ID from unassigned IDs
{
pep_ids.erase(pep_ids.begin() + i);
// @TODO: use "std::remove" to make this more efficient
}
else // only keep hits that weren't assigned:
{
for (Size j = 0; j < assigned_hits.size(); ++j)
{
if (!assigned_hits[j])
{
pep.getHits().push_back(all_hits[j]);
}
}
++i;
}
}
if (clear_original)
{
consensus.getIdentificationData().clear();
for (auto& feat : consensus)
{
feat.clearPrimaryID();
feat.getIDMatches().clear();
}
}
}
} // end namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/METADATA/ID/IdentificationData.cpp | .cpp | 51,728 | 1,427 | // 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/METADATA/ID/IdentificationData.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <numeric>
using namespace std;
namespace OpenMS
{
/// Check whether a reference points to an element in a container
template <typename RefType, typename ContainerType>
static bool isValidReference_(RefType ref, ContainerType& container)
{
for (auto it = container.begin(); it != container.end(); ++it)
{
if (ref == it) return true;
}
return false;
}
/// Check validity of a reference based on a look-up table of addresses
template <typename RefType>
static bool isValidHashedReference_(
RefType ref, const IdentificationData::AddressLookup& lookup)
{
return lookup.count(ref);
}
/// Remove elements from a set (or ordered multi_index_container) if they don't occur in a look-up table
template <typename ContainerType>
static void removeFromSetIfNotHashed_(
ContainerType& container, const IdentificationData::AddressLookup& lookup)
{
removeFromSetIf_(container, [&lookup](typename ContainerType::iterator it)
{
return !lookup.count(uintptr_t(&(*it)));
});
}
/// Recreate the address look-up table for a container
template <typename ContainerType>
static void updateAddressLookup_(const ContainerType& container,
IdentificationData::AddressLookup& lookup)
{
lookup.clear();
lookup.reserve(container.size());
for (const auto& element : container)
{
lookup.insert(uintptr_t(&element));
}
}
/// Helper function to add a meta value to an element in a multi-index container
template <typename RefType, typename ContainerType>
void setMetaValue_(const RefType ref, const String& key, const DataValue& value,
ContainerType& container, bool no_checks,
const IdentificationData::AddressLookup& lookup = IdentificationData::AddressLookup())
{
if (!no_checks && ((lookup.empty() && !isValidReference_(ref, container)) ||
(!lookup.empty() && !isValidHashedReference_(ref, lookup))))
{
String msg = "invalid reference for the given container";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
container.modify(ref, [&key, &value](typename ContainerType::value_type& element)
{
element.setMetaValue(key, value);
});
}
template <typename ContainerType, typename ElementType>
typename ContainerType::iterator IdentificationData::insertIntoMultiIndex_(
ContainerType& container, const ElementType& element,
AddressLookup& lookup)
{
typename ContainerType::iterator ref =
insertIntoMultiIndex_(container, element);
lookup.insert(uintptr_t(&(*ref)));
return ref;
}
template <typename ElementType>
struct IdentificationData::ModifyMultiIndexRemoveParentMatches
{
ModifyMultiIndexRemoveParentMatches(const AddressLookup& lookup):
lookup(lookup)
{
}
void operator()(ElementType& element)
{
removeFromSetIf_(element.parent_matches,
[&](const ParentMatches::iterator it)
{
return !lookup.count(it->first);
});
}
const AddressLookup& lookup;
};
template <typename ElementType>
struct IdentificationData::ModifyMultiIndexAddProcessingStep
{
ModifyMultiIndexAddProcessingStep(ProcessingStepRef step_ref):
step_ref(step_ref)
{
}
void operator()(ElementType& element)
{
element.addProcessingStep(step_ref);
}
ProcessingStepRef step_ref;
};
template <typename ElementType>
struct IdentificationData::ModifyMultiIndexAddScore
{
ModifyMultiIndexAddScore(ScoreTypeRef score_type_ref, double value):
score_type_ref(score_type_ref), value(value)
{
}
void operator()(ElementType& element)
{
if (element.steps_and_scores.empty())
{
element.addScore(score_type_ref, value);
}
else // add score to most recent step
{
element.addScore(score_type_ref, value,
element.steps_and_scores.back().processing_step_opt);
}
}
ScoreTypeRef score_type_ref;
double value;
};
void IdentificationData::checkScoreTypes_(const map<IdentificationData::ScoreTypeRef, double>&
scores) const
{
for (const auto& pair : scores)
{
if (!isValidReference_(pair.first, score_types_))
{
String msg = "invalid reference to a score type - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
}
void IdentificationData::checkAppliedProcessingSteps_(
const AppliedProcessingSteps& steps_and_scores) const
{
for (const auto& step : steps_and_scores)
{
if ((step.processing_step_opt != std::nullopt) &&
(!isValidReference_(*step.processing_step_opt, processing_steps_)))
{
String msg = "invalid reference to a data processing step - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
checkScoreTypes_(step.scores);
}
}
void IdentificationData::checkParentMatches_(const ParentMatches& matches,
MoleculeType expected_type) const
{
for (const auto& pair : matches)
{
if (!isValidHashedReference_(pair.first, parent_lookup_))
{
String msg = "invalid reference to a parent sequence - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
if (pair.first->molecule_type != expected_type)
{
String msg = "unexpected molecule type for parent sequence";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
}
IdentificationData::InputFileRef
IdentificationData::registerInputFile(const InputFile& file)
{
if (!no_checks_ && file.name.empty()) // key may not be empty
{
String msg = "input file must have a name";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
auto result = input_files_.insert(file);
if (!result.second) // existing element - merge in new information
{
input_files_.modify(result.first, [&file](InputFile& existing)
{
existing.merge(file);
});
}
return result.first;
}
IdentificationData::ProcessingSoftwareRef
IdentificationData::registerProcessingSoftware(
const ProcessingSoftware& software)
{
if (!no_checks_)
{
for (ScoreTypeRef score_ref : software.assigned_scores)
{
if (!isValidReference_(score_ref, score_types_))
{
String msg = "invalid reference to a score type - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
}
return processing_softwares_.insert(software).first;
}
IdentificationData::SearchParamRef
IdentificationData::registerDBSearchParam(const DBSearchParam& param)
{
// @TODO: any required information that should be checked?
return db_search_params_.insert(param).first;
}
IdentificationData::ProcessingStepRef
IdentificationData::registerProcessingStep(
const ProcessingStep& step)
{
return registerProcessingStep(step, db_search_params_.end());
}
IdentificationData::ProcessingStepRef
IdentificationData::registerProcessingStep(
const ProcessingStep& step, SearchParamRef search_ref)
{
if (!no_checks_)
{
// valid reference to software is required:
if (!isValidReference_(step.software_ref, processing_softwares_))
{
String msg = "invalid reference to data processing software - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
// if given, references to input files must be valid:
for (InputFileRef ref : step.input_file_refs)
{
if (!isValidReference_(ref, input_files_))
{
String msg = "invalid reference to input file - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
}
ProcessingStepRef step_ref = processing_steps_.insert(step).first;
// if given, reference to DB search param. must be valid:
if (search_ref != db_search_params_.end())
{
if (!no_checks_ && !isValidReference_(search_ref, db_search_params_))
{
String msg = "invalid reference to database search parameters - register those first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
db_search_steps_.insert(make_pair(step_ref, search_ref));
}
return step_ref;
}
IdentificationData::ScoreTypeRef
IdentificationData::registerScoreType(const ScoreType& score)
{
// @TODO: allow just an accession? (all look-ups are currently by name)
if (!no_checks_ && score.cv_term.getName().empty())
{
String msg = "score type must have a name (as part of its CV term)";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
pair<ScoreTypes::iterator, bool> result;
result = score_types_.insert(score);
if (!result.second && (score.higher_better != result.first->higher_better))
{
String msg = "score type already exists with opposite orientation";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
return result.first;
}
IdentificationData::ObservationRef
IdentificationData::registerObservation(const Observation& obs)
{
if (!no_checks_)
{
// reference to spectrum or feature is required:
if (obs.data_id.empty())
{
String msg = "missing identifier in observation";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
// ref. to input file must be valid:
if (!isValidReference_(obs.input_file, input_files_))
{
String msg = "invalid reference to an input file - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
// can't use "insertIntoMultiIndex_" because Observation doesn't have the
// "steps_and_scores" member (from ScoredProcessingResult)
auto result = observations_.insert(obs);
if (!result.second) // existing element - merge in new information
{
observations_.modify(result.first, [&obs](Observation& existing)
{
existing.merge(obs);
});
}
// add address of new element to look-up table (for existence checks):
observation_lookup_.insert(uintptr_t(&(*result.first)));
// @TODO: add processing step? (currently not supported by Observation)
return result.first;
}
IdentificationData::IdentifiedPeptideRef
IdentificationData::registerIdentifiedPeptide(const IdentifiedPeptide&
peptide)
{
if (!no_checks_)
{
if (peptide.sequence.empty())
{
String msg = "missing sequence for peptide";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
checkParentMatches_(peptide.parent_matches, MoleculeType::PROTEIN);
}
return insertIntoMultiIndex_(identified_peptides_, peptide,
identified_peptide_lookup_);
}
IdentificationData::IdentifiedCompoundRef
IdentificationData::registerIdentifiedCompound(const IdentifiedCompound&
compound)
{
if (!no_checks_ && compound.identifier.empty())
{
String msg = "missing identifier for compound";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
return insertIntoMultiIndex_(identified_compounds_, compound,
identified_compound_lookup_);
}
IdentificationData::IdentifiedOligoRef
IdentificationData::registerIdentifiedOligo(const IdentifiedOligo& oligo)
{
if (!no_checks_)
{
if (oligo.sequence.empty())
{
String msg = "missing sequence for oligonucleotide";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
checkParentMatches_(oligo.parent_matches, MoleculeType::RNA);
}
return insertIntoMultiIndex_(identified_oligos_, oligo,
identified_oligo_lookup_);
}
IdentificationData::ParentSequenceRef
IdentificationData::registerParentSequence(const ParentSequence& parent)
{
if (!no_checks_)
{
if (parent.accession.empty())
{
String msg = "missing accession for parent sequence";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
if ((parent.coverage < 0.0) || (parent.coverage > 1.0))
{
String msg = "parent sequence coverage must be between 0 and 1";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
return insertIntoMultiIndex_(parents_, parent,
parent_lookup_);
}
void IdentificationData::registerParentGroupSet(const ParentGroupSet& groups)
{
if (!no_checks_)
{
checkAppliedProcessingSteps_(groups.steps_and_scores);
for (const auto& group : groups.groups)
{
checkScoreTypes_(group.scores); // are the score types registered?
for (const auto& ref : group.parent_refs)
{
if (!isValidHashedReference_(ref, parent_lookup_))
{
String msg = "invalid reference to a parent sequence - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
}
}
parent_groups_.push_back(groups);
// add the current processing step?
if ((current_step_ref_ != processing_steps_.end()) &&
(groups.steps_and_scores.get<1>().find(current_step_ref_) ==
groups.steps_and_scores.get<1>().end()))
{
parent_groups_.back().steps_and_scores.push_back(
IdentificationDataInternal::AppliedProcessingStep(current_step_ref_));
}
}
IdentificationData::AdductRef
IdentificationData::registerAdduct(const AdductInfo& adduct)
{
// @TODO: require non-empty name? (auto-generate from formula?)
auto result = adducts_.insert(adduct);
if (!result.second && (result.first->getName() != adduct.getName()))
{
OPENMS_LOG_WARN << "Warning: adduct '" << adduct.getName()
<< "' is already known under the name '"
<< result.first->getName() << "'";
}
return result.first;
}
IdentificationData::ObservationMatchRef
IdentificationData::registerObservationMatch(const ObservationMatch& match)
{
if (!no_checks_)
{
if (const IdentifiedPeptideRef* ref_ptr =
std::get_if<IdentifiedPeptideRef>(&match.identified_molecule_var))
{
if (!isValidHashedReference_(*ref_ptr, identified_peptide_lookup_))
{
String msg = "invalid reference to an identified peptide - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
else if (const IdentifiedCompoundRef* ref_ptr =
std::get_if<IdentifiedCompoundRef>(&match.identified_molecule_var))
{
if (!isValidHashedReference_(*ref_ptr, identified_compound_lookup_))
{
String msg = "invalid reference to an identified compound - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
else if (const IdentifiedOligoRef* ref_ptr =
std::get_if<IdentifiedOligoRef>(&match.identified_molecule_var))
{
if (!isValidHashedReference_(*ref_ptr, identified_oligo_lookup_))
{
String msg = "invalid reference to an identified oligonucleotide - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
if (!isValidHashedReference_(match.observation_ref, observation_lookup_))
{
String msg = "invalid reference to an observation - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
if (match.adduct_opt && !isValidReference_(*match.adduct_opt, adducts_))
{
String msg = "invalid reference to an adduct - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
return insertIntoMultiIndex_(observation_matches_, match,
observation_match_lookup_);
}
IdentificationData::MatchGroupRef
IdentificationData::registerObservationMatchGroup(const ObservationMatchGroup& group)
{
if (!no_checks_)
{
for (const auto& ref : group.observation_match_refs)
{
if (!isValidHashedReference_(ref, observation_match_lookup_))
{
String msg = "invalid reference to an input match - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
}
}
return insertIntoMultiIndex_(observation_match_groups_, group);
}
void IdentificationData::addScore(ObservationMatchRef match_ref,
ScoreTypeRef score_ref, double value)
{
if (!no_checks_ && !isValidReference_(score_ref, score_types_))
{
String msg = "invalid reference to a score type - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
ModifyMultiIndexAddScore<ObservationMatch> modifier(score_ref, value);
observation_matches_.modify(match_ref, modifier);
}
void IdentificationData::setCurrentProcessingStep(ProcessingStepRef step_ref)
{
if (!no_checks_ && !isValidReference_(step_ref, processing_steps_))
{
String msg = "invalid reference to a processing step - register that first";
throw Exception::IllegalArgument(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
current_step_ref_ = step_ref;
}
IdentificationData::ProcessingStepRef
IdentificationData::getCurrentProcessingStep()
{
return current_step_ref_;
}
void IdentificationData::clearCurrentProcessingStep()
{
current_step_ref_ = processing_steps_.end();
}
IdentificationData::ScoreTypeRef
IdentificationData::findScoreType(const String& score_name) const
{
for (ScoreTypeRef it = score_types_.begin(); it != score_types_.end(); ++it)
{
if (it->cv_term.getName() == score_name)
{
return it;
}
}
return score_types_.end();
}
vector<IdentificationData::ObservationMatchRef>
IdentificationData::getBestMatchPerObservation(ScoreTypeRef score_ref,
bool require_score) const
{
vector<ObservationMatchRef> results;
pair<double, bool> best_score = make_pair(0.0, false);
ObservationMatchRef best_ref = observation_matches_.end();
Size n_matches = 1; // number of matches for current observation
// matches for same observation appear consecutively, so just iterate:
for (ObservationMatchRef ref = observation_matches_.begin();
ref != observation_matches_.end(); ++ref, ++n_matches)
{
pair<double, bool> current_score = ref->getScore(score_ref);
if (current_score.second && (!best_score.second ||
score_ref->isBetterScore(current_score.first,
best_score.first)))
{
// new best score for the current observation:
best_score = current_score;
best_ref = ref;
}
// peek ahead:
ObservationMatchRef next = ref;
++next;
if ((next == observation_matches_.end()) ||
(next->observation_ref != ref->observation_ref))
{
// last match for this observation - finalize:
if (best_score.second)
{
results.push_back(best_ref);
}
else if (!require_score && (n_matches == 1))
{
results.push_back(ref); // only match for this observation
}
best_score.second = false;
n_matches = 0; // will be incremented by for-loop
}
}
return results;
}
pair<IdentificationData::ObservationMatchRef, IdentificationData::ObservationMatchRef>
IdentificationData::getMatchesForObservation(ObservationRef obs_ref) const
{
return observation_matches_.equal_range(obs_ref);
}
void IdentificationData::calculateCoverages(bool check_molecule_length)
{
// aggregate parent matches by parent:
struct ParentData
{
Size length = 0;
double coverage = 0.0;
vector<pair<Size, Size>> fragments;
};
map<ParentSequenceRef, ParentData> parent_info;
// go through all peptides:
for (const auto& molecule : identified_peptides_)
{
Size molecule_length = check_molecule_length ?
molecule.sequence.size() : 0;
for (const auto& pair : molecule.parent_matches)
{
auto pos = parent_info.find(pair.first);
if (pos == parent_info.end()) // new parent sequence
{
ParentData pd;
pd.length = AASequence::fromString(pair.first->sequence).size();
if (pd.length == 0)
{
break; // sequence not available
}
pos = parent_info.insert(make_pair(pair.first, pd)).first;
}
Size parent_length = pos->second.length; // always check this
for (const auto& match : pair.second)
{
if (match.hasValidPositions(molecule_length, parent_length))
{
pos->second.fragments.emplace_back(match.start_pos,
match.end_pos);
}
}
}
}
// go through all oligonucleotides:
for (const auto& molecule : identified_oligos_)
{
Size molecule_length = check_molecule_length ?
molecule.sequence.size() : 0;
for (const auto& pair : molecule.parent_matches)
{
auto pos = parent_info.find(pair.first);
if (pos == parent_info.end()) // new parent sequence
{
ParentData pd;
pd.length = NASequence::fromString(pair.first->sequence).size();
if (pd.length == 0)
{
break; // sequence not available
}
pos = parent_info.insert(make_pair(pair.first, pd)).first;
}
Size parent_length = pos->second.length; // always check this
for (const auto& match : pair.second)
{
if (match.hasValidPositions(molecule_length, parent_length))
{
pos->second.fragments.emplace_back(match.start_pos,
match.end_pos);
}
}
}
}
// calculate coverage for each parent:
for (auto& pair : parent_info)
{
vector<bool> covered(pair.second.length, false);
for (const auto& fragment : pair.second.fragments)
{
fill(covered.begin() + fragment.first,
covered.begin() + fragment.second + 1, true);
}
pair.second.coverage = (accumulate(covered.begin(), covered.end(), 0) /
double(pair.second.length));
}
// set coverage:
for (ParentSequenceRef ref = parents_.begin();
ref != parents_.end(); ++ref)
{
auto pos = parent_info.find(ref);
double coverage = (pos == parent_info.end()) ? 0.0 : pos->second.coverage;
parents_.modify(ref, [coverage](ParentSequence& parent)
{
parent.coverage = coverage;
});
}
}
void IdentificationData::cleanup(bool require_observation_match,
bool require_identified_sequence,
bool require_parent_match,
bool require_parent_group,
bool require_match_group)
{
// we expect that only "primary results" (stored in classes derived from
// "ScoredProcessingResult") will be directly removed (by filters) - not
// meta data (incl. score types, processing steps etc.)
// remove parent sequences based on parent groups:
if (require_parent_group)
{
parent_lookup_.clear(); // will become invalid anyway
for (const auto& groups: parent_groups_)
{
for (const auto& group : groups.groups)
{
for (const auto& ref : group.parent_refs)
{
parent_lookup_.insert(ref);
}
}
}
removeFromSetIfNotHashed_(parents_, parent_lookup_);
}
// update look-up table of parent sequence addresses (in case parent
// molecules were removed):
updateAddressLookup_(parents_, parent_lookup_);
// remove parent matches based on parent sequences:
ModifyMultiIndexRemoveParentMatches<IdentifiedPeptide>
pep_modifier(parent_lookup_);
for (auto it = identified_peptides_.begin();
it != identified_peptides_.end(); ++it)
{
identified_peptides_.modify(it, pep_modifier);
}
ModifyMultiIndexRemoveParentMatches<IdentifiedOligo>
oli_modifier(parent_lookup_);
for (auto it = identified_oligos_.begin();
it != identified_oligos_.end(); ++it)
{
identified_oligos_.modify(it, oli_modifier);
}
// remove identified molecules based on parent matches:
if (require_parent_match)
{
removeFromSetIf_(identified_peptides_, [](IdentifiedPeptides::iterator it)
{
return it->parent_matches.empty();
});
removeFromSetIf_(identified_oligos_, [](IdentifiedOligos::iterator it)
{
return it->parent_matches.empty();
});
}
// remove observation matches based on identified molecules:
set<IdentifiedMolecule> id_vars;
for (IdentifiedPeptideRef it = identified_peptides_.begin();
it != identified_peptides_.end(); ++it)
{
id_vars.insert(it);
}
for (IdentifiedCompoundRef it = identified_compounds_.begin();
it != identified_compounds_.end(); ++it)
{
id_vars.insert(it);
}
for (IdentifiedOligoRef it = identified_oligos_.begin();
it != identified_oligos_.end(); ++it)
{
id_vars.insert(it);
}
removeFromSetIf_(observation_matches_, [&](ObservationMatches::iterator it)
{
return !id_vars.count(it->identified_molecule_var);
});
// remove observation matches based on observation match groups:
if (require_match_group)
{
observation_match_lookup_.clear(); // will become invalid anyway
for (const auto& group : observation_match_groups_)
{
for (const auto& ref : group.observation_match_refs)
{
observation_match_lookup_.insert(ref);
}
}
removeFromSetIfNotHashed_(observation_matches_, observation_match_lookup_);
}
// update look-up table of input match addresses:
updateAddressLookup_(observation_matches_, observation_match_lookup_);
// remove id'd molecules, observations and adducts based on observation matches:
if (require_observation_match)
{
observation_lookup_.clear();
identified_peptide_lookup_.clear();
identified_compound_lookup_.clear();
identified_oligo_lookup_.clear();
set<AdductRef> adduct_refs;
for (const auto& match : observation_matches_)
{
observation_lookup_.insert(match.observation_ref);
const IdentifiedMolecule& molecule_var = match.identified_molecule_var;
switch (molecule_var.getMoleculeType())
{
case IdentificationData::MoleculeType::PROTEIN:
identified_peptide_lookup_.insert(molecule_var.getIdentifiedPeptideRef());
break;
case IdentificationData::MoleculeType::COMPOUND:
identified_compound_lookup_.insert(molecule_var.getIdentifiedCompoundRef());
break;
case IdentificationData::MoleculeType::RNA:
identified_oligo_lookup_.insert(molecule_var.getIdentifiedOligoRef());
}
if (match.adduct_opt) adduct_refs.insert(*match.adduct_opt);
}
removeFromSetIfNotHashed_(observations_, observation_lookup_);
removeFromSetIfNotHashed_(identified_peptides_,
identified_peptide_lookup_);
removeFromSetIfNotHashed_(identified_compounds_,
identified_compound_lookup_);
removeFromSetIfNotHashed_(identified_oligos_, identified_oligo_lookup_);
removeFromSetIf_(adducts_, [&](Adducts::iterator it)
{
return !adduct_refs.count(it);
});
}
// update look-up tables of addresses:
updateAddressLookup_(observations_, observation_lookup_);
updateAddressLookup_(identified_peptides_, identified_peptide_lookup_);
updateAddressLookup_(identified_compounds_, identified_compound_lookup_);
updateAddressLookup_(identified_oligos_, identified_oligo_lookup_);
// remove parent sequences based on identified molecules:
if (require_identified_sequence)
{
parent_lookup_.clear(); // will become invalid anyway
for (const auto& peptide : identified_peptides_)
{
for (const auto& parent_pair : peptide.parent_matches)
{
parent_lookup_.insert(parent_pair.first);
}
}
for (const auto& oligo : identified_oligos_)
{
for (const auto& parent_pair : oligo.parent_matches)
{
parent_lookup_.insert(parent_pair.first);
}
}
removeFromSetIfNotHashed_(parents_, parent_lookup_);
// update look-up table of parent sequence addresses (again):
updateAddressLookup_(parents_, parent_lookup_);
}
// remove entries from parent sequence groups based on parent sequences
// (if a parent sequence doesn't exist anymore, remove it from any groups):
bool warn = false;
for (auto& group_set : parent_groups_)
{
for (auto group_it = group_set.groups.begin();
group_it != group_set.groups.end(); )
{
Size old_size = group_it->parent_refs.size();
group_set.groups.modify(group_it, [&](ParentGroup& group)
{
removeFromSetIfNotHashed_(group.parent_refs, parent_lookup_);
});
if (group_it->parent_refs.empty())
{
group_it = group_set.groups.erase(group_it);
}
else
{
if (group_it->parent_refs.size() != old_size)
{
warn = true;
}
++group_it;
}
}
// @TODO: if no group is left, remove the whole grouping?
}
if (warn)
{
OPENMS_LOG_WARN << "Warning: filtering removed elements from parent sequence groups - associated scores may not be valid any more" << endl;
}
// remove entries from input match groups based on input matches:
warn = false;
for (auto group_it = observation_match_groups_.begin();
group_it != observation_match_groups_.end(); )
{
Size old_size = group_it->observation_match_refs.size();
observation_match_groups_.modify(group_it, [&](ObservationMatchGroup& group)
{
removeFromSetIfNotHashed_(group.observation_match_refs, observation_match_lookup_);
});
if (group_it->observation_match_refs.empty())
{
group_it = observation_match_groups_.erase(group_it);
}
else
{
if (group_it->observation_match_refs.size() != old_size)
{
warn = true;
}
++group_it;
}
}
if (warn)
{
OPENMS_LOG_WARN << "Warning: filtering removed elements from observation match groups - associated scores may not be valid any more" << endl;
}
}
bool IdentificationData::empty() const
{
return (input_files_.empty() && processing_softwares_.empty() &&
processing_steps_.empty() && db_search_params_.empty() &&
db_search_steps_.empty() && score_types_.empty() &&
observations_.empty() && parents_.empty() &&
parent_groups_.empty() &&
identified_peptides_.empty() && identified_compounds_.empty() &&
identified_oligos_.empty() && adducts_.empty() &&
observation_matches_.empty() && observation_match_groups_.empty());
}
void IdentificationData::mergeScoredProcessingResults_(
IdentificationData::ScoredProcessingResult& result,
const IdentificationData::ScoredProcessingResult& other,
const RefTranslator& trans)
{
result.MetaInfoInterface::operator=(other);
for (const AppliedProcessingStep& applied : other.steps_and_scores)
{
AppliedProcessingStep copy;
if (applied.processing_step_opt)
{
// need to reference a processing step in 'result', not the original one
// from 'other', so find the corresponding one:
copy.processing_step_opt = trans.processing_step_refs.at(*applied.processing_step_opt);
}
for (const auto& pair : applied.scores)
{
// need to reference a score type in 'result', not the original one from
// 'other', so find the corresponding one:
ScoreTypeRef score_ref = trans.score_type_refs.at(pair.first);
copy.scores[score_ref] = pair.second;
}
result.addProcessingStep(copy);
}
}
IdentificationData::RefTranslator
IdentificationData::merge(const IdentificationData& other)
{
RefTranslator trans;
// incoming data (stored in IdentificationData) is guaranteed to be consistent,
// so no need to check for consistency again:
no_checks_ = true;
// input files:
for (InputFileRef other_ref = other.getInputFiles().begin();
other_ref != other.getInputFiles().end(); ++other_ref)
{
trans.input_file_refs[other_ref] = registerInputFile(*other_ref);
}
// score types:
for (ScoreTypeRef other_ref = other.getScoreTypes().begin();
other_ref != other.getScoreTypes().end(); ++other_ref)
{
trans.score_type_refs[other_ref] = registerScoreType(*other_ref);
}
// processing software:
for (ProcessingSoftwareRef other_ref = other.getProcessingSoftwares().begin();
other_ref != other.getProcessingSoftwares().end(); ++other_ref)
{
// update internal references:
ProcessingSoftware copy = *other_ref;
for (ScoreTypeRef& score_ref : copy.assigned_scores)
{
score_ref = trans.score_type_refs[score_ref];
}
trans.processing_software_refs[other_ref] = registerProcessingSoftware(copy);
}
// search params:
for (SearchParamRef other_ref = other.getDBSearchParams().begin();
other_ref != other.getDBSearchParams().end(); ++other_ref)
{
trans.search_param_refs[other_ref] = registerDBSearchParam(*other_ref);
}
// processing steps:
for (ProcessingStepRef other_ref = other.getProcessingSteps().begin();
other_ref != other.getProcessingSteps().end(); ++other_ref)
{
// update internal references:
ProcessingStep copy = *other_ref;
copy.software_ref = trans.processing_software_refs[copy.software_ref];
for (InputFileRef& file_ref : copy.input_file_refs)
{
file_ref = trans.input_file_refs[file_ref];
}
trans.processing_step_refs[other_ref] = registerProcessingStep(copy);
}
// search steps:
for (const auto& pair : other.getDBSearchSteps())
{
ProcessingStepRef step_ref = trans.processing_step_refs[pair.first];
SearchParamRef param_ref = trans.search_param_refs[pair.second];
db_search_steps_[step_ref] = param_ref;
}
// observations:
for (ObservationRef other_ref = other.getObservations().begin();
other_ref != other.getObservations().end(); ++other_ref)
{
// update internal references:
Observation copy = *other_ref;
copy.input_file = trans.input_file_refs[copy.input_file];
trans.observation_refs[other_ref] = registerObservation(copy);
}
// parent sequences:
for (ParentSequenceRef other_ref = other.getParentSequences().begin();
other_ref != other.getParentSequences().end(); ++other_ref)
{
// don't copy processing steps and scores yet:
ParentSequence copy(other_ref->accession, other_ref->molecule_type,
other_ref->sequence, other_ref->description,
other_ref->coverage, other_ref->is_decoy);
// now copy precessing steps and scores while updating references:
mergeScoredProcessingResults_(copy, *other_ref, trans);
trans.parent_sequence_refs[other_ref] = registerParentSequence(copy);
}
// identified peptides:
for (IdentifiedPeptideRef other_ref = other.getIdentifiedPeptides().begin();
other_ref != other.getIdentifiedPeptides().end(); ++other_ref)
{
// don't copy parent matches, steps/scores yet:
IdentifiedPeptide copy(other_ref->sequence, ParentMatches());
// now copy steps/scores and parent matches while updating references:
mergeScoredProcessingResults_(copy, *other_ref, trans);
for (const auto& pair : other_ref->parent_matches)
{
ParentSequenceRef parent_ref = trans.parent_sequence_refs[pair.first];
copy.parent_matches[parent_ref] = pair.second;
}
trans.identified_peptide_refs[other_ref] = registerIdentifiedPeptide(copy);
}
// identified oligonucleotides:
for (IdentifiedOligoRef other_ref = other.getIdentifiedOligos().begin();
other_ref != other.getIdentifiedOligos().end(); ++other_ref)
{
// don't copy parent matches, steps/scores yet:
IdentifiedOligo copy(other_ref->sequence, ParentMatches());
// now copy steps/scores and parent matches while updating references:
mergeScoredProcessingResults_(copy, *other_ref, trans);
for (const auto& pair : other_ref->parent_matches)
{
ParentSequenceRef parent_ref = trans.parent_sequence_refs[pair.first];
copy.parent_matches[parent_ref] = pair.second;
}
trans.identified_oligo_refs[other_ref] = registerIdentifiedOligo(copy);
}
// identified compounds:
for (IdentifiedCompoundRef other_ref = other.getIdentifiedCompounds().begin();
other_ref != other.getIdentifiedCompounds().end(); ++other_ref)
{
IdentifiedCompound copy(other_ref->identifier, other_ref->formula,
other_ref->name, other_ref->smile, other_ref->inchi);
mergeScoredProcessingResults_(copy, *other_ref, trans);
trans.identified_compound_refs[other_ref] = registerIdentifiedCompound(copy);
}
// adducts:
for (AdductRef other_ref = other.getAdducts().begin();
other_ref != other.getAdducts().end(); ++other_ref)
{
trans.adduct_refs[other_ref] = registerAdduct(*other_ref);
}
// observation matches:
for (ObservationMatchRef other_ref = other.getObservationMatches().begin();
other_ref != other.getObservationMatches().end(); ++other_ref)
{
IdentifiedMolecule molecule_var =
trans.translate(other_ref->identified_molecule_var);
ObservationRef obs_ref = trans.observation_refs[other_ref->observation_ref];
ObservationMatch copy(molecule_var, obs_ref, other_ref->charge);
if (other_ref->adduct_opt)
{
copy.adduct_opt = trans.adduct_refs[*other_ref->adduct_opt];
}
for (const auto& pair : other_ref->peak_annotations)
{
std::optional<ProcessingStepRef> opt_ref;
if (pair.first)
{
opt_ref = trans.processing_step_refs[*pair.first];
}
copy.peak_annotations[opt_ref] = pair.second;
}
mergeScoredProcessingResults_(copy, *other_ref, trans);
trans.observation_match_refs[other_ref] = registerObservationMatch(copy);
}
// parent sequence groups:
// @TODO: does this need to be more sophisticated?
for (const ParentGroupSet& groups : other.parent_groups_)
{
ParentGroupSet copy(groups.label);
mergeScoredProcessingResults_(copy, groups, trans);
for (const ParentGroup& group : groups.groups)
{
ParentGroup group_copy;
for (const auto& pair : group.scores)
{
ScoreTypeRef score_ref = trans.score_type_refs[pair.first];
group_copy.scores[score_ref] = pair.second;
}
for (ParentSequenceRef parent_ref : group.parent_refs)
{
group_copy.parent_refs.insert(trans.parent_sequence_refs[parent_ref]);
}
copy.groups.insert(group_copy);
}
registerParentGroupSet(copy);
}
no_checks_ = false;
return trans;
}
// copy constructor
IdentificationData::IdentificationData(const IdentificationData& other):
MetaInfoInterface(other)
{
// don't add a processing step during merging:
current_step_ref_ = processing_steps_.end();
RefTranslator trans = merge(other);
if (other.current_step_ref_ != other.processing_steps_.end())
{
current_step_ref_ = trans.processing_step_refs[other.current_step_ref_];
}
no_checks_ = other.no_checks_;
}
// copy assignment
IdentificationData& IdentificationData::operator=(const IdentificationData& other)
{
if (this != &other)
{
IdentificationData tmp(other);
tmp.swap(*this);
}
return *this;
}
// move constructor
IdentificationData::IdentificationData(IdentificationData&& other) noexcept
{
*this = std::move(other);
}
// move assignment
IdentificationData& IdentificationData::operator=(IdentificationData&& other) noexcept
{
MetaInfoInterface::operator=(std::move(other));
input_files_ = std::move(other.input_files_);
processing_softwares_ = std::move(other.processing_softwares_);
processing_steps_ = std::move(other.processing_steps_);
db_search_params_ = std::move(other.db_search_params_);
db_search_steps_ = std::move(other.db_search_steps_);
score_types_ = std::move(other.score_types_);
observations_ = std::move(other.observations_);
parents_ = std::move(other.parents_);
parent_groups_ = std::move(other.parent_groups_);
identified_peptides_ = std::move(other.identified_peptides_);
identified_compounds_ = std::move(other.identified_compounds_);
identified_oligos_ = std::move(other.identified_oligos_);
adducts_ = std::move(other.adducts_);
observation_matches_ = std::move(other.observation_matches_);
observation_match_groups_ = std::move(other.observation_match_groups_);
current_step_ref_ = std::move(other.current_step_ref_);
no_checks_ = std::move(other.no_checks_);
// look-up tables:
observation_lookup_ = std::move(other.observation_lookup_);
parent_lookup_ = std::move(other.parent_lookup_);
identified_peptide_lookup_ = std::move(other.identified_peptide_lookup_);
identified_compound_lookup_ = std::move(other.identified_compound_lookup_);
identified_oligo_lookup_ = std::move(other.identified_oligo_lookup_);
observation_match_lookup_ = std::move(other.observation_match_lookup_);
return *this;
}
void IdentificationData::swap(IdentificationData& other)
{
MetaInfoInterface::swap(other);
input_files_.swap(other.input_files_);
processing_softwares_.swap(other.processing_softwares_);
processing_steps_.swap(other.processing_steps_);
db_search_params_.swap(other.db_search_params_);
db_search_steps_.swap(other.db_search_steps_);
score_types_.swap(other.score_types_);
observations_.swap(other.observations_);
parents_.swap(other.parents_);
parent_groups_.swap(other.parent_groups_);
identified_peptides_.swap(other.identified_peptides_);
identified_compounds_.swap(other.identified_compounds_);
identified_oligos_.swap(other.identified_oligos_);
adducts_.swap(other.adducts_);
observation_matches_.swap(other.observation_matches_);
observation_match_groups_.swap(other.observation_match_groups_);
std::swap(current_step_ref_, other.current_step_ref_);
std::swap(no_checks_, other.no_checks_);
// look-up tables:
observation_lookup_.swap(other.observation_lookup_);
parent_lookup_.swap(other.parent_lookup_);
identified_peptide_lookup_.swap(other.identified_peptide_lookup_);
identified_compound_lookup_.swap(other.identified_compound_lookup_);
identified_oligo_lookup_.swap(other.identified_oligo_lookup_);
observation_match_lookup_.swap(other.observation_match_lookup_);
}
void IdentificationData::clear()
{
IdentificationData tmp;
swap(tmp);
}
void IdentificationData::setMetaValue(const ObservationMatchRef ref, const String& key,
const DataValue& value)
{
setMetaValue_(ref, key, value, observation_matches_, no_checks_, observation_match_lookup_);
}
void IdentificationData::setMetaValue(const ObservationRef ref, const String& key,
const DataValue& value)
{
setMetaValue_(ref, key, value, observations_, no_checks_, observation_lookup_);
}
void IdentificationData::setMetaValue(const IdentifiedMolecule& var, const String& key,
const DataValue& value)
{
switch (var.getMoleculeType())
{
case MoleculeType::PROTEIN:
setMetaValue_(var.getIdentifiedPeptideRef(), key, value,
identified_peptides_, no_checks_, identified_peptide_lookup_);
break;
case MoleculeType::COMPOUND:
setMetaValue_(var.getIdentifiedCompoundRef(), key, value,
identified_compounds_, no_checks_, identified_compound_lookup_);
break;
case MoleculeType::RNA:
setMetaValue_(var.getIdentifiedOligoRef(), key, value,
identified_oligos_, no_checks_, identified_oligo_lookup_);
}
}
void IdentificationData::removeMetaValue(const ObservationMatchRef ref, const String& key)
{
if (!no_checks_ && ((observation_match_lookup_.empty() && !isValidReference_(ref, observation_matches_)) ||
(!observation_match_lookup_.empty() && !isValidHashedReference_(ref, observation_match_lookup_))))
{
String msg = "invalid reference to an observation match";
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, msg);
}
observation_matches_.modify(ref, [&key](ObservationMatch& element)
{
element.removeMetaValue(key);
});
}
IdentificationData::IdentifiedMolecule IdentificationData::RefTranslator::translate(IdentifiedMolecule old) const
{
switch (old.getMoleculeType())
{
case MoleculeType::PROTEIN:
{
auto pos = identified_peptide_refs.find(old.getIdentifiedPeptideRef());
if (pos != identified_peptide_refs.end()) return pos->second;
}
break;
case MoleculeType::COMPOUND:
{
auto pos = identified_compound_refs.find(old.getIdentifiedCompoundRef());
if (pos != identified_compound_refs.end()) return pos->second;
}
break;
case MoleculeType::RNA:
{
auto pos = identified_oligo_refs.find(old.getIdentifiedOligoRef());
if (pos != identified_oligo_refs.end()) return pos->second;
}
break;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"invalid molecule type",
String(old.getMoleculeType()));
}
if (allow_missing) return old;
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"no match for reference");
}
IdentificationData::ObservationMatchRef IdentificationData::RefTranslator::translate(ObservationMatchRef old) const
{
auto pos = observation_match_refs.find(old);
if (pos != observation_match_refs.end()) return pos->second;
if (allow_missing) return old;
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"no match for reference");
}
template <typename ContainerType, typename ElementType>
typename ContainerType::iterator IdentificationData::insertIntoMultiIndex_(
ContainerType& container, const ElementType& element)
{
checkAppliedProcessingSteps_(element.steps_and_scores);
auto result = container.insert(element);
if (!result.second) // existing element - merge in new information
{
container.modify(result.first, [&element](ElementType& existing)
{
existing.merge(element);
});
}
// add current processing step (if necessary):
if (current_step_ref_ != processing_steps_.end())
{
ModifyMultiIndexAddProcessingStep<ElementType>
modifier(current_step_ref_);
container.modify(result.first, modifier);
}
return result.first;
}
} // end namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/SYSTEM/File.cpp | .cpp | 28,183 | 970 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Andreas Bertsch, Chris Bielow, Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/openms_data_path.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/DATASTRUCTURES/DateTime.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtNetwork/QHostInfo>
#include <atomic>
#ifdef OPENMS_WINDOWSPLATFORM
#include <Windows.h> // for GetCurrentProcessId() && GetModuleFileName()
#endif
#ifdef OPENMS_HAS_UNISTD_H
#include <unistd.h> // for readLink() and getpid()
#endif
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#include <QtCore/QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QtCore/QUrl>
#include <QtCore/QDateTime>
#include <QtCore/QFile>
#include <QtCore/QDebug>
#include <OpenMS/SYSTEM/NetworkGetRequest.h>
#include <QtCore/QDir>
#include <QtCore/QCoreApplication>
#include <QtCore/QDateTime>
#include <QtCore/QTimer>
using namespace std;
namespace OpenMS
{
File::TempDir::TempDir(bool keep_dir)
: keep_dir_(keep_dir)
{
temp_dir_ = File::getTempDirectory() + "/" + File::getUniqueName() + "/";
OPENMS_LOG_DEBUG << "Creating temporary directory '" << temp_dir_ << "'\n";
QDir d;
d.mkpath(temp_dir_.toQString());
};
File::TempDir::~TempDir()
{
if (keep_dir_)
{
OPENMS_LOG_DEBUG << "Keeping temporary files in directory '" << temp_dir_ << '\n';
return;
}
File::removeDirRecursively(temp_dir_);
};
const String& File::TempDir::getPath() const
{
return temp_dir_;
}
String File::getExecutablePath()
{
// see http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe/1024937#1024937 for more OS' (if needed)
// Use immediately evaluated lambda to protect static variable from concurrent access.
static const String spath = [&]() -> String {
String rpath = "";
char path[1024]; // maximum path length
#ifdef OPENMS_WINDOWSPLATFORM
int size = sizeof(path);
if (GetModuleFileNameA(NULL, path, size))
#elif defined(__APPLE__)
uint size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0)
#else // LINUX
// note: implementation as suggested by readlink man page
ssize_t len = ::readlink("/proc/self/exe", path, sizeof(path)-1);
if (len != -1) //add 0 terminator at end
{
path[len] = '\0';
}
if (len != -1)
#endif
{
rpath = File::path(String(path));
if (File::exists(rpath)) // check if directory exists
{
// ensure path ends with a "/", such that we can just write path + "ToolX", and to not worry about if its empty or a path.
rpath.ensureLastChar('/');
}
else
{
std::cerr << "Path '" << rpath << "' extracted from Executable Path '" << path << "' does not exist! Returning empty string!\n";
rpath = "";
}
} else {
std::cerr << "Cannot get Executable Path! Not using a path prefix!\n";
}
return rpath;
}();
return spath;
}
bool File::exists(const String& file)
{
QFileInfo fi(file.toQString());
return fi.exists();
}
bool File::empty(const String& file)
{
QFileInfo fi(file.toQString());
return !fi.exists() || fi.size() == 0;
}
bool File::executable(const String& file)
{
QFileInfo fi(file.toQString());
return fi.exists() && fi.isExecutable();
}
UInt64 File::fileSize(const String& file)
{
if (!File::exists(file)) return -1;
return QFile(file.toQString()).size();
}
bool File::rename(const String& from, const String& to, bool overwrite_existing, bool verbose)
{
// check for equality
if (QFileInfo(from.c_str()).canonicalFilePath() == QFileInfo(to.c_str()).canonicalFilePath())
{ // same file; no need to to anything
return true;
}
// existing file? Qt won't overwrite, so try to remove it:
if (overwrite_existing && exists(to) && !remove(to))
{
if (verbose)
{
OPENMS_LOG_ERROR << "Error: Could not overwrite existing file '" << to << "'\n";
}
return false;
}
// move the file to the actual destination:
if (!QFile::rename(from.toQString(), to.toQString()))
{
if (verbose)
{
OPENMS_LOG_ERROR << "Error: Could not move '" << from << "' to '" << to << "'\n";
}
return false;
}
return true;
}
// https://stackoverflow.com/questions/2536524/copy-directory-using-qt
bool File::copyDirRecursively(const QString& from_dir, const QString& to_dir, File::CopyOptions option)
{
QDir source_dir(from_dir);
QDir target_dir(to_dir);
QString canonical_source_dir = source_dir.canonicalPath();
QString canonical_target_dir = target_dir.canonicalPath();
// check canonical path
if (canonical_source_dir == canonical_target_dir)
{
OPENMS_LOG_ERROR << "Error: Could not copy " << from_dir.toStdString() << " to " << to_dir.toStdString() << ". Same path given.\n";
return false;
}
// make directory if not present
if (!target_dir.exists())
{
target_dir.mkpath(to_dir);
}
// copy folder recursively
QFileInfoList file_list = source_dir.entryInfoList();
for (const QFileInfo& entry : file_list)
{
if (entry.fileName() == "." || entry.fileName() == "..")
{
continue;
}
if (entry.isDir())
{
if (!copyDirRecursively(entry.filePath(), target_dir.filePath(entry.fileName()), option))
{
return false;
}
}
else
{
if (target_dir.exists(entry.fileName()))
{
switch (option)
{
case CopyOptions::CANCEL:
return false;
case CopyOptions::SKIP:
OPENMS_LOG_WARN << "The file " << entry.fileName().toStdString() << " was skipped.\n";
continue;
case CopyOptions::OVERWRITE:
target_dir.remove(entry.fileName());
}
}
if (!QFile::copy(entry.filePath(), target_dir.filePath(entry.fileName())))
{
return false;
}
}
}
return true;
}
bool File::copy(const String& from, const String& to)
{
return QFile::copy(from.toQString(), to.toQString());
}
bool File::remove(const String& file)
{
if (!exists(file))
{
return true;
}
if (std::remove(file.c_str()) != 0)
{
return false;
}
return true;
}
bool File::removeDir(const QString& dir_name)
{
bool result = true;
QDir dir(dir_name);
if (dir.exists(dir_name))
{
Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst))
{
if (info.isDir())
{
result = removeDir(info.absoluteFilePath());
}
else
{
result = QFile::remove(info.absoluteFilePath());
}
if (!result)
{
return result;
}
}
result = dir.rmdir(dir_name);
}
return result;
}
bool File::makeDir(const String& dir_name)
{
QDir dir;
return dir.mkpath(dir_name.toQString());
}
bool File::removeDirRecursively(const String& dir_name)
{
bool fail = false;
QString path = dir_name.toQString();
QDir dir(path);
QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
foreach(const QString &file_name, files)
{
if (!dir.remove(file_name))
{
OPENMS_LOG_WARN << "Could not remove file " << String(file_name) << "!\n";
fail = true;
}
}
QStringList contained_dirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach(const QString &contained_dir, contained_dirs)
{
if (!removeDirRecursively(path + QDir::separator() + contained_dir))
{
fail = true;
}
}
QDir parent_dir(path);
if (parent_dir.cdUp())
{
if (!parent_dir.rmdir(path))
{
std::cerr << "Could not remove directory " << String(dir.dirName()) << "!" << std::endl;
fail = true;
}
}
return !fail;
}
String File::absolutePath(const String& file)
{
QFileInfo fi(file.toQString());
return fi.absoluteFilePath();
}
String File::basename(const String& file)
{ // using well-defined overflow of unsigned ints here if path separator is not found
return file.substr(file.find_last_of("\\/") + 1);
}
String File::path(const String& file)
{
size_t pos = file.find_last_of("\\/");
// do NOT return an empty string, because this leads to issues when in generic code you do:
// String new_path = path("a.txt") + '/' + basename("a.txt");
// , as this would lead to "/a.txt", i.e. create a wrong absolute path from a relative name
String no_path = ".";
return pos == string::npos ? no_path : file.substr(0, pos);
}
bool File::readable(const String& file)
{
QFileInfo fi(file.toQString());
return fi.exists() && fi.isReadable();
}
bool File::writable(const String& file)
{
QFileInfo fi(file.toQString());
bool tmp = false;
if (fi.exists())
{
tmp = fi.isWritable();
}
else
{
QFile f;
f.setFileName(file.toQString());
f.open(QIODevice::WriteOnly);
tmp = f.isWritable();
f.remove();
}
return tmp;
}
String File::find(const String& filename, StringList directories)
{
// maybe we do not need to do anything?!
// This check is required since calling File::find(File::find("CHEMISTRY/unimod.xml")) will otherwise fail
// because the outer call receives an absolute path already
if (exists(filename))
{
return filename;
}
String filename_new = filename;
// empty string cannot be found, so throw Exception.
// The code below would return success on empty string, since a path is prepended and thus the location exists
if (filename_new.trim().empty())
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
//add data dir in OpenMS data path
directories.push_back(getOpenMSDataPath());
//add path suffix to all specified directories
String path = File::path(filename);
if (!path.empty())
{
for (String& str : directories)
{
str.ensureLastChar('/');
str += path;
}
filename_new = File::basename(filename);
}
//look up file
for (const String& str : directories)
{
String loc = str;
loc.ensureLastChar('/');
loc = loc + filename_new;
if (exists(loc))
{
return String(QDir::cleanPath(loc.toQString()));
}
}
//if the file was not found, throw an exception
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
bool File::fileList(const String& dir, const String& file_pattern, StringList& output, bool full_path)
{
QDir d(dir.toQString(), file_pattern.toQString(), QDir::Name, QDir::Files);
QFileInfoList list = d.entryInfoList();
//clear and check if empty
output.clear();
if (list.empty())
{
return false;
}
//resize output
output.resize(list.size());
//fill output
UInt i = 0;
for (QFileInfoList::const_iterator it = list.constBegin(); it != list.constEnd(); ++it)
{
output[i++] = full_path ? it->filePath() : it->fileName();
}
return true;
}
String File::findDoc(const String& filename)
{
StringList search_dirs;
search_dirs.push_back(String(OPENMS_BINARY_PATH) + "/../../doc/");
// source path is host/openms so doc is ../doc
search_dirs.push_back(String(OPENMS_SOURCE_PATH) + "/../../doc/");
search_dirs.push_back(getOpenMSDataPath() + "/../../doc/");
search_dirs.push_back(OPENMS_DOC_PATH);
search_dirs.push_back(OPENMS_INSTALL_DOC_PATH);
// needed for OpenMS Mac OS X packages where documentation is stored in <package-root>/Documentation
#if defined(__APPLE__)
search_dirs.push_back(String(OPENMS_BINARY_PATH) + "/Documentation/");
search_dirs.push_back(String(OPENMS_SOURCE_PATH) + "/Documentation/");
search_dirs.push_back(getOpenMSDataPath() + "/../../Documentation/");
#endif
return File::find(filename, search_dirs);
}
String File::getUniqueName(bool include_hostname)
{
DateTime now = DateTime::now();
String pid;
#ifdef OPENMS_WINDOWSPLATFORM
pid = (String)GetCurrentProcessId();
#else
pid = (String)getpid();
#endif
static std::atomic_int number = 0;
return now.getDate().remove('-') + "_" + now.getTime().remove(':') + "_" + (include_hostname ? String(QHostInfo::localHostName()) + "_" : "") + pid + "_" + (++number);
}
String File::getOpenMSDataPath()
{
// Use immediately evaluated lambda to protect static variable from concurrent access.
static const String path = [&]() -> String {
String path;
bool path_checked = false;
String found_path_from;
bool from_env(false);
if (getenv("OPENMS_DATA_PATH") != nullptr)
{
path = getenv("OPENMS_DATA_PATH");
from_env = true;
path_checked = isOpenMSDataPath_(path);
if (path_checked)
{
found_path_from = "OPENMS_DATA_PATH (environment)";
}
}
// probe the install path
if (!path_checked)
{
path = OPENMS_INSTALL_DATA_PATH;
path_checked = isOpenMSDataPath_(path);
if (path_checked)
{
found_path_from = "OPENMS_INSTALL_DATA_PATH (compiled)";
}
}
// probe the OPENMS_DATA_PATH macro
if (!path_checked)
{
path = OPENMS_DATA_PATH;
path_checked = isOpenMSDataPath_(path);
if (path_checked) found_path_from = "OPENMS_DATA_PATH (compiled)";
}
#if defined(__APPLE__)
// try to find it relative to the executable in the bundle (e.g. TOPPView)
if (!path_checked)
{
path = getExecutablePath() + "../../../share/OpenMS";
path_checked = isOpenMSDataPath_(path);
if (path_checked) found_path_from = "bundle path (run time)";
}
#endif
// On Linux and Apple check relative from the executable
if (!path_checked)
{
path = getExecutablePath() + "../share/OpenMS";
path_checked = isOpenMSDataPath_(path);
if (path_checked)
{
found_path_from = "tool path (run time)";
}
}
// make its a proper path:
path = path.substitute("\\", "/").ensureLastChar('/').chop(1);
if (!path_checked) // - now we're in big trouble as './share' is not were its supposed to be...
{ // - do NOT use OPENMS_LOG_ERROR or similar for the messages below! (it might not even usable at this point)
std::cerr << "OpenMS FATAL ERROR!\n Cannot find shared data! OpenMS cannot function without it!\n";
if (from_env)
{
String p = getenv("OPENMS_DATA_PATH");
std::cerr << " The environment variable 'OPENMS_DATA_PATH' currently points to '" << p << "', which is incorrect!\n";
}
#ifdef OPENMS_WINDOWSPLATFORM
String share_dir = R"(c:\Program Files\OpenMS\share\OpenMS)";
#else
String share_dir = "/usr/share/OpenMS";
#endif
std::cerr << " To resolve this, set the environment variable 'OPENMS_DATA_PATH' to the OpenMS share directory (e.g., '" + share_dir + "').\n";
std::cerr << "Exiting now.\n";
exit(1);
}
return path;
}();
return path;
}
bool File::isOpenMSDataPath_(const String& path)
{
bool found = exists(path + "/CHEMISTRY/unimod.xml");
return found;
}
bool File::isDirectory(const String& path)
{
QFileInfo fi(path.toQString());
return fi.isDir();
}
String File::getTempDirectory()
{
Param p = getSystemParameters();
String dir;
if (getenv("OPENMS_TMPDIR") != nullptr)
{
dir = getenv("OPENMS_TMPDIR");
}
else if (p.exists("temp_dir") && !String(p.getValue("temp_dir").toString()).trim().empty())
{
dir = p.getValue("temp_dir").toString();
}
else
{
dir = String(QDir::tempPath());
}
return dir;
}
/// The current OpenMS user data path (for result files)
String File::getUserDirectory()
{
Param p = getSystemParameters();
String dir;
if (getenv("OPENMS_HOME_PATH") != nullptr)
{
dir = getenv("OPENMS_HOME_PATH");
}
else if (p.exists("home_dir") && !String(p.getValue("home_dir").toString()).trim().empty())
{
dir = p.getValue("home_dir").toString();
}
else
{
dir = String(QDir::homePath());
}
dir.ensureLastChar('/');
return dir;
}
String File::findDatabase(const String& db_name)
{
Param sys_p = getSystemParameters();
String full_db_name;
try
{
full_db_name = find(db_name, ListUtils::toStringList<std::string>(sys_p.getValue("id_db_dir")));
OPENMS_LOG_INFO << "Augmenting database name '" << db_name << "' with path given in 'OpenMS.ini:id_db_dir'. Full name is now: '" << full_db_name << "'\n";
}
catch (Exception::FileNotFound& e)
{
OPENMS_LOG_ERROR << "Input database '" + db_name + "' not found (" << e.what() << "). Make sure it exists (and check 'OpenMS.ini:id_db_dir' if you used relative paths. Aborting!\n";
throw;
}
return full_db_name;
}
String File::getOpenMSHomePath()
{
String home_path;
// set path where OpenMS.ini is found from environment or use default
if (getenv("OPENMS_HOME_PATH") != nullptr)
{
home_path = getenv("OPENMS_HOME_PATH");
}
else
{
home_path = String(QDir::homePath());
}
return home_path;
}
Param File::getSystemParameters()
{
String home_path = File::getOpenMSHomePath();
String filename;
//Comply with https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html on unix identifying systems
#ifdef __unix__
if (getenv("XDG_CONFIG_HOME"))
{
filename = String(getenv("XDG_CONFIG_HOME")) + "/OpenMS/OpenMS.ini";
}
else
{
filename = File::getOpenMSHomePath() + "/.config/OpenMS/OpenMS.ini";
}
#else
filename = home_path + "/.OpenMS/OpenMS.ini";
#endif
Param p;
if (!File::readable(filename)) // no file, lets keep it that way
{
p = getSystemParameterDefaults_();
}
else
{
ParamXMLFile paramFile;
paramFile.load(filename, p);
// check version
if (!p.exists("version") || (p.getValue("version") != VersionInfo::getVersion()))
{
if (!p.exists("version"))
{
OPENMS_LOG_WARN << "Broken file '" << filename << "' discovered. The 'version' tag is missing.\n";
}
else // old version
{
OPENMS_LOG_WARN << "File '" << filename << "' is deprecated.\n";
}
OPENMS_LOG_WARN << "Updating missing/wrong entries in '" << filename << "' with defaults!\n";
Param p_new = getSystemParameterDefaults_();
p.setValue("version", VersionInfo::getVersion()); // update old version, such that p_new:version does not get overwritten during update()
p_new.update(p);
// no new version is stored
}
}
return p;
}
Param File::getSystemParameterDefaults_()
{
Param p;
p.setValue("version", VersionInfo::getVersion());
p.setValue("home_dir", ""); // only active when user enters something in this value
p.setValue("temp_dir", ""); // only active when user enters something in this value
p.setValue("id_db_dir", std::vector<std::string>(),
String("Default directory for FASTA and psq files used as databased for id engines. ") + \
"This allows you to specify just the filename of the DB in the " + \
"respective TOPP tool, and the database will be searched in the directories specified here " + \
""); // only active when user enters something in this value
p.setValue("threads", 1);
return p;
}
#ifdef OPENMS_WINDOWSPLATFORM
StringList File::executableExtensions_(const String& ext)
{
// check if content of env-var %PATHEXT% makes sense
StringList exts;
ext.split(';', exts);
// sanity check
if (ListUtils::contains(exts, ".exe", ListUtils::CASE::INSENSITIVE)) return exts;
// .. use fallback otherwise
else return {".exe", ".bat" };
}
#endif
StringList File::getPathLocations(const String& path)
{
// split by ":" or ";", depending on platform
StringList paths;
#ifdef OPENMS_WINDOWSPLATFORM
path.split(';', paths);
#else
path.split(':', paths);
#endif
// ensure it ends with '/'
for (String& p : paths) p.substitute('\\', '/').ensureLastChar('/');
return paths;
}
bool File::findExecutable(OpenMS::String& exe_filename)
{
if (exists(exe_filename) && !isDirectory(exe_filename))
{
return true;
}
StringList paths = getPathLocations();
StringList exe_filenames = { exe_filename };
#ifdef OPENMS_WINDOWSPLATFORM
// try extensions like .exe on Windows
if (!exe_filename.has('.'))
{
StringList exts = executableExtensions_();
for (String& ext : exts) ext = exe_filename + ext;
exe_filenames = exts;
}
#endif
// try all filenames (on Windows its potentially more than one) in each path...
for (const String& p : paths)
{
for (const String& fn : exe_filenames)
{
if (exists(p + fn) && !isDirectory(p + fn))
{
exe_filename = p + fn;
return true;
}
}
}
return false;
}
String File::findSiblingTOPPExecutable(const OpenMS::String& toolName)
{
// we first try the executablePath
String exec = File::getExecutablePath() + toolName;
#if OPENMS_WINDOWSPLATFORM
if (!exec.hasSuffix(".exe")) exec += ".exe";
#endif
if (File::exists(exec))
{
return exec;
}
#if defined(__APPLE__)
// check if we are in one of the bundles (only built, not installed)
exec = File::getExecutablePath() + "../../../" + toolName;
if (File::exists(exec)) return exec;
// check if we are in one of the bundles in an installed bundle (old bundles)
exec = File::getExecutablePath() + "../../../TOPP/" + toolName;
if (File::exists(exec)) return exec;
// check if we are in one of the bundles in an installed bundle (new bundles)
exec = File::getExecutablePath() + "../../../bin/" + toolName;
if (File::exists(exec)) return exec;
#endif
// TODO(aiche): probe in PATH
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, toolName);
}
String File::getTemporaryFile(const String& alternative_file)
{
// take no action
if (!alternative_file.empty())
{
return alternative_file;
}
// create temporary (and schedule for deletion)
return temporary_files_.newFile();
}
File::TemporaryFiles_::TemporaryFiles_()
: filenames_()
{
}
String File::TemporaryFiles_::newFile()
{
String s = getTempDirectory().ensureLastChar('/') + getUniqueName();
std::lock_guard<std::mutex> _(mtx_);
filenames_.push_back(s);
// do NOT return filenames_.back() by ref, since another thread might resize the vector and invalidate the reference!
return s; // uses RVO, so its efficient
}
File::TemporaryFiles_::~TemporaryFiles_()
{
std::lock_guard<std::mutex> _(mtx_);
for (Size i = 0; i < filenames_.size(); ++i)
{
if (File::exists(filenames_[i]) && !File::remove(filenames_[i]))
{
std::cerr << "Warning: unable to remove temporary file '" << filenames_[i] << "'" << std::endl;
}
}
}
File::MatchingFileListsStatus File::validateMatchingFileNames(const StringList& sl1,
const StringList& sl2,
bool basename,
bool ignore_extension)
{
// Different counts means different sets
if (sl1.size() != sl2.size())
{
return MatchingFileListsStatus::SET_MISMATCH;
}
set<String> sl1_set;
set<String> sl2_set;
bool different_name_at_index = false;
// Process and compare each filename
for (size_t i = 0; i != sl1.size(); ++i)
{
String sl1_name = sl1[i];
String sl2_name = sl2[i];
if (basename)
{
sl1_name = File::basename(sl1_name);
sl2_name = File::basename(sl2_name);
}
if (ignore_extension)
{
sl1_name = FileHandler::stripExtension(sl1_name);
sl2_name = FileHandler::stripExtension(sl2_name);
}
sl1_set.insert(sl1_name);
sl2_set.insert(sl2_name);
if (sl1_name != sl2_name)
{
different_name_at_index = true;
}
}
bool same_set = (sl1_set == sl2_set);
// Check if it's an order mismatch or complete mismatch
if (same_set)
{
return different_name_at_index ?
MatchingFileListsStatus::ORDER_MISMATCH :
MatchingFileListsStatus::MATCH;
}
return MatchingFileListsStatus::SET_MISMATCH;
}
File::TemporaryFiles_ File::temporary_files_;
// construct a filename. Add number if already exists.
QString saveFileName_(const QUrl &url)
{
QString path = url.path();
QString basename = QFileInfo(path).fileName();
if (basename.isEmpty())
basename = "download";
if (QFile::exists(basename)) {
// already exists, don't overwrite
int i = 0;
basename += '.';
while (QFile::exists(basename + QString::number(i)))
++i;
basename += QString::number(i);
}
return basename;
}
// static
void File::download(const std::string& url, const std::string& download_folder)
{
// We need to use a QCoreApplication to fire up the QEventLoop to process the signals and slots.
char const * argv2[] = { "dummyname", nullptr };
int argc = 1;
QCoreApplication event_loop(argc, const_cast<char**>(argv2));
NetworkGetRequest* query = new NetworkGetRequest(&event_loop);
auto qURL = QUrl(QString::fromUtf8(url.c_str()));
query->setUrl(qURL);
QObject::connect(query, SIGNAL(done()), &event_loop, SLOT(quit()));
QTimer::singleShot(1000, query, SLOT(run()));
QTimer::singleShot(600000, query, SLOT(timeOut())); // 10 minutes timeout
event_loop.exec();
if (!query->hasError())
{
QString folder = download_folder.empty() ? QString("./") : QString(download_folder.c_str());
QString filename = QString(folder) + "/" + saveFileName_(qURL);
QFile file(filename);
file.open(QIODevice::ReadWrite);
file.write(query->getResponseBinary().data(), query->getResponseBinary().size());
file.close();
OPENMS_LOG_INFO << "Download of '" << url << "' successful." << endl;
OPENMS_LOG_INFO << "Stored as '" << filename.toStdString() << "'." << endl;
}
else
{
String error = "Download of '" + url + "' failed!. Error: " + String(query->getErrorString()) + '\n';
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, error);
}
delete query;
event_loop.quit();
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/SYSTEM/BuildInfo.cpp | .cpp | 1,214 | 55 | // 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/SYSTEM/BuildInfo.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <simde/simde-arch.h>
using namespace std;
namespace OpenMS
{
String Internal::OpenMSOSInfo::getActiveSIMDExtensions()
{
StringList ret;
#ifdef SIMDE_ARCH_ARM_NEON
ret.push_back("neon");
#endif
#ifdef SIMDE_ARCH_X86_SSE
ret.push_back("SSE");
#endif
#ifdef SIMDE_ARCH_X86_SSE2
ret.push_back("SSE2");
#endif
#ifdef SIMDE_ARCH_X86_SSE3
ret.push_back("SSE3");
#endif
#ifdef SIMDE_ARCH_X86_SSE4_1
ret.push_back("SSE4.1");
#endif
#ifdef SIMDE_ARCH_X86_SSE4_2
ret.push_back("SSE4.2");
#endif
#ifdef SIMDE_ARCH_X86_AVX
ret.push_back("AVX");
#endif
#ifdef SIMDE_ARCH_X86_AVX2
ret.push_back("AVX2");
#endif
#ifdef SIMDE_ARCH_X86_FMA
ret.push_back("FMA");
#endif
return ListUtils::concatenate(ret, ", ");
}
} // namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms/source/SYSTEM/UpdateCheck.cpp | .cpp | 5,600 | 168 | // 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/SYSTEM/UpdateCheck.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CONCEPT/LogStream.h>
#ifdef OPENMS_WINDOWSPLATFORM
#include <sys/utime.h>
#elif __APPLE__
#include <utime.h>
#else
#include <utime.h>
#endif
#include <sys/stat.h>
#include <OpenMS/SYSTEM/NetworkGetRequest.h>
#include <QtCore/QDir>
#include <QtCore/QCoreApplication>
#include <QtCore/QDateTime>
#include <QtCore/QTimer>
#include <OpenMS/CONCEPT/VersionInfo.h>
using namespace std;
namespace OpenMS
{
void UpdateCheck::run(const String& tool_name, const String& version, int debug_level)
{
String architecture = QSysInfo::WordSize == 32 ? "32" : "64";
// if the revision info is meaningful, show it as well
String revision("UNKNOWN");
if (!VersionInfo::getRevision().empty() && VersionInfo::getRevision() != "exported")
{
revision = VersionInfo::getRevision();
}
String platform;
#ifdef OPENMS_WINDOWSPLATFORM
platform = "Win";
#elif __APPLE__
platform = "Mac";
#elif __linux__
platform = "Linux";
#elif __unix__
platform = "Unix";
#else
platform = "unknown";
#endif
// write to tmp + userid folder
// e.g.: OpenMS_Default_Win_64_FeatureFinderCentroided_2.0.0
String tool_version_string;
String config_path;
//Comply with https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html on unix identifying systems
#ifdef __unix__
if (getenv("XDG_CONFIG_HOME"))
{
config_path = String(getenv("XDG_CONFIG_HOME")) + "/OpenMS";
}
else
{
config_path = File::getOpenMSHomePath() + "/.config/OpenMS";
}
#else
config_path = File::getOpenMSHomePath() + "/.OpenMS";
#endif
tool_version_string = String("OpenMS") + "_" + "Default_" + platform + "_" + architecture + "_" + tool_name + "_" + version;
String version_file_name = config_path + "/" + tool_name + ".ver";
// create version file if it doesn't exist yet
bool first_run(false);
if (!File::exists(version_file_name) || !File::readable(version_file_name))
{
// create OpenMS folder for .ver files
QDir dir(config_path.toQString());
if (!dir.exists())
{
dir.mkpath(".");
}
// touch file to create it and set initial modification time stamp
QFile f;
f.setFileName(version_file_name.toQString());
f.open(QIODevice::WriteOnly);
f.close();
first_run = true;
}
if (File::readable(version_file_name))
{
QDateTime last_modified_dt = QFileInfo(version_file_name.toQString()).lastModified();
QDateTime current_dt = QDateTime::currentDateTime();
// check if at least one day passed since last request
if (first_run || current_dt > last_modified_dt.addDays(1))
{
// update modification time stamp
struct stat old_stat;
struct utimbuf new_times;
stat(version_file_name.c_str(), &old_stat);
new_times.actime = old_stat.st_atime; // keep accession time unchanged
new_times.modtime = time(nullptr); // mod time to current time
utime(version_file_name.c_str(), &new_times);
if (debug_level > 0)
{
OPENMS_LOG_INFO << "The OpenMS team is collecting usage statistics for quality control and funding purposes." << endl;
OPENMS_LOG_INFO << "We will never give out your personal data, but you may disable this functionality by " << endl;
OPENMS_LOG_INFO << "setting the environmental variable OPENMS_DISABLE_UPDATE_CHECK to ON." << endl;
}
// We need to use a QCoreApplication to fire up the QEventLoop to process the signals and slots.
char const * argv2[] = { "dummyname", nullptr };
int argc = 1;
QCoreApplication event_loop(argc, const_cast<char**>(argv2));
NetworkGetRequest* query = new NetworkGetRequest(&event_loop);
query->setUrl(QUrl(QString("http://openms-update.cs.uni-tuebingen.de/check/") + tool_version_string.toQString()));
QObject::connect(query, SIGNAL(done()), &event_loop, SLOT(quit()));
QTimer::singleShot(1000, query, SLOT(run()));
QTimer::singleShot(5000, query, SLOT(timeOut()));
event_loop.exec();
if (!query->hasError())
{
if (debug_level > 0)
{
OPENMS_LOG_INFO << "Connecting to REST server successful. " << endl;
}
QString response = query->getResponse();
VersionInfo::VersionDetails server_version = VersionInfo::VersionDetails::create(response);
if (server_version != VersionInfo::VersionDetails::EMPTY)
{
if (VersionInfo::getVersionStruct() < server_version)
{
OPENMS_LOG_INFO << "Version " + version + " of " + tool_name + " is available at www.OpenMS.de" << endl;
}
}
}
else
{
if (debug_level > 0)
{
OPENMS_LOG_INFO << "Connecting to REST server failed. Skipping update check." << endl;
OPENMS_LOG_INFO << "Error: " << String(query->getErrorString()) << endl;
}
}
delete query;
event_loop.quit();
}
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/SYSTEM/RWrapper.cpp | .cpp | 4,400 | 144 | // 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/SYSTEM/RWrapper.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtCore/QProcess>
namespace OpenMS
{
bool RWrapper::runScript( const String& script_file, const QStringList& cmd_args, const QString& executable /*= "Rscript"*/, bool find_R /*= false */, bool verbose /*= true */)
{
if (find_R && !findR(executable, verbose))
{
return false;
}
String fullscript;
try
{
fullscript = findScript(script_file, verbose);
}
catch (...)
{
return false;
}
if (verbose)
{
OPENMS_LOG_INFO << "Running R script '" << fullscript << "' ...";
}
QStringList args;
args << "--vanilla" << "--quiet" << fullscript.toQString();
args.append(cmd_args);
QProcess p;
p.start(executable, args);
p.waitForFinished(-1);
if (p.error() == QProcess::FailedToStart || p.exitStatus() == QProcess::CrashExit || p.exitCode() != 0)
{
if (verbose)
{
OPENMS_LOG_INFO << " failed" << std::endl;
OPENMS_LOG_ERROR << "\n--- ERROR MESSAGES ---\n";
OPENMS_LOG_ERROR << QString(p.readAllStandardError()).toStdString();
OPENMS_LOG_ERROR << "\n--- OTHER MESSAGES ---\n";
OPENMS_LOG_ERROR << QString(p.readAllStandardOutput()).toStdString();
OPENMS_LOG_ERROR << "\n\nScript failed. See above for an error description. " << std::endl;
}
return false;
}
if (verbose)
{
OPENMS_LOG_INFO << " success" << std::endl;
}
return true;
}
bool RWrapper::findR( const QString& executable /*= "Rscript"*/, bool verbose /*= true*/ )
{
if (verbose) OPENMS_LOG_INFO << "Finding R interpreter 'Rscript' ...";
QStringList args(QStringList() << "--vanilla" << "-e" << "sessionInfo()");
QProcess p;
p.setProcessChannelMode(QProcess::MergedChannels); // stdout receives all messages (stderr is empty)
p.start(executable, args);
p.waitForFinished(-1);
if (p.error() == QProcess::FailedToStart)
{
if (verbose)
{
OPENMS_LOG_INFO << " failed" << std::endl;
String out = QString(p.readAllStandardOutput()).toStdString();
OPENMS_LOG_ERROR << "Error: Could not find or run '" << executable.toStdString() << "' executable (FailedToStart).\n";
if (!out.empty())
{
OPENMS_LOG_ERROR << "Output was:\n------>\n"
<< out
<< "\n<------\n";
}
OPENMS_LOG_ERROR << "Please install 'Rscript', make sure it's in PATH and is flagged as executable." << std::endl;
}
return false;
}
if (verbose)
{
OPENMS_LOG_INFO << " success" << std::endl;
}
if (verbose)
{
OPENMS_LOG_INFO << "Trying to invoke 'Rscript' ...";
}
if (p.exitStatus() != QProcess::NormalExit || p.exitCode() != 0)
{
if (verbose)
{
OPENMS_LOG_INFO << " failed" << std::endl;
OPENMS_LOG_ERROR << "Error: 'Rscript' executable returned with error (command: 'Rscript " << args.join(" ").toStdString() << "')\n"
<< "Output was:\n------>\n"
<< QString(p.readAllStandardOutput()).toStdString()
<< "\n<------\n"
<< "Make sure 'Rscript' is installed properly." << std::endl;
}
return false;
}
if (verbose)
{
OPENMS_LOG_INFO << " success" << std::endl;
}
return true;
}
OpenMS::String RWrapper::findScript( const String& script_file, bool verbose /*= true*/ )
{
String s;
try
{
s = File::find(script_file, StringList(1, File::getOpenMSDataPath().ensureLastChar('/') + "SCRIPTS"));
}
catch (...)
{
if (verbose)
{
OPENMS_LOG_ERROR << "\n\nCould not find R script '" << script_file << "'!\n" << std::endl;
}
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, script_file);
}
return s;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/SYSTEM/ExternalProcess.cpp | .cpp | 4,732 | 158 | // 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/SYSTEM/ExternalProcess.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QProcess>
#include <QtCore/QStringList>
#include <utility>
namespace OpenMS
{
/// default Ctor; callbacks for stdout/stderr are empty
ExternalProcess::ExternalProcess()
: ExternalProcess([&](const String& /*out*/) {}, [&](const String& /*out*/) {}) // call other Ctor to connect signals!
{
}
ExternalProcess::ExternalProcess(std::function<void(const String&)> callbackStdOut, std::function<void(const String&)> callbackStdErr)
: qp_(new QProcess),
callbackStdOut_(std::move(callbackStdOut)),
callbackStdErr_(std::move(callbackStdErr))
{
connect(qp_, &QProcess::readyReadStandardOutput, this, &ExternalProcess::processStdOut_);
connect(qp_, &QProcess::readyReadStandardError, this, &ExternalProcess::processStdErr_);
}
ExternalProcess::~ExternalProcess()
{
delete qp_;
}
/// re-wire the callbacks used using run()
void ExternalProcess::setCallbacks(std::function<void(const String&)> callbackStdOut, std::function<void(const String&)> callbackStdErr)
{
callbackStdOut_ = std::move(callbackStdOut);
callbackStdErr_ = std::move(callbackStdErr);
}
ExternalProcess::RETURNSTATE ExternalProcess::run(const QString& exe, const QStringList& args, const QString& working_dir, const bool verbose, IO_MODE io_mode, const std::map<QString, QString>& env)
{
String error_msg;
return run(exe, args, working_dir, verbose, error_msg, io_mode, env);
}
ExternalProcess::RETURNSTATE ExternalProcess::run(const QString& exe, const QStringList& args, const QString& working_dir, const bool verbose, String& error_msg, IO_MODE io_mode, const std::map<QString, QString>& env)
{
// pass environment variables to child process
QProcessEnvironment process_env = QProcessEnvironment::systemEnvironment();
// Add custom environment variables
for (const auto& kv : env)
{
process_env.insert(kv.first, kv.second);
}
qp_->setProcessEnvironment(process_env);
error_msg.clear();
if (!working_dir.isEmpty())
{
qp_->setWorkingDirectory(working_dir);
}
if (verbose)
{
callbackStdOut_("Running: " + (QStringList() << exe << args).join(' ') + '\n');
}
// Map IO_MODE enum value to QIODevice value
QIODevice::OpenModeFlag mode;
switch (io_mode)
{
case IO_MODE::NO_IO:
mode = QIODevice::NotOpen;
break;
case IO_MODE::READ_ONLY:
mode = QIODevice::ReadOnly;
break;
case IO_MODE::WRITE_ONLY:
mode = QIODevice::WriteOnly;
break;
default:
mode = QIODevice::ReadWrite;
}
qp_->start(exe, args, mode);
if (!(qp_->waitForStarted()))
{
error_msg = "Process '" + exe + "' failed to start. Does it exist? Is it executable?";
if (verbose)
{
callbackStdErr_(error_msg + '\n');
}
return RETURNSTATE::FAILED_TO_START;
}
while (qp_->state() == QProcess::Running)
{
QCoreApplication::processEvents();
if (qp_->waitForReadyRead(50)) // wait 50ms. Small enough to have the GUI repaint when switching windows
{
processStdOut_();
processStdErr_();
}
}
if (qp_->exitStatus() != QProcess::NormalExit)
{
error_msg = "Process '" + exe + "' crashed hard (segfault-like). Please check the log.";
if (verbose)
{
callbackStdErr_(error_msg + '\n');
}
return RETURNSTATE::CRASH;
}
else if (qp_->exitCode() != 0)
{
error_msg = "Process '" + exe + "' did not finish successfully (exit code: " + String(int(qp_->exitCode())).toQString() + "). Please check the log.";
if (verbose)
{
callbackStdErr_(error_msg + '\n');
}
return RETURNSTATE::NONZERO_EXIT;
}
if (verbose)
{
callbackStdOut_("Executed '" + String(exe) + "' successfully!\n");
}
return RETURNSTATE::SUCCESS;
}
void ExternalProcess::processStdOut_()
{
String s(QString(qp_->readAllStandardOutput()));
//std::cout << s << "\n";
callbackStdOut_(s);
}
void ExternalProcess::processStdErr_()
{
String s(QString(qp_->readAllStandardError()));
//std::cout << s << "\n";
callbackStdErr_(s);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/SYSTEM/StopWatch.cpp | .cpp | 10,588 | 357 | // 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/SYSTEM/StopWatch.h>
#include <OpenMS/CONCEPT/Exception.h>
#ifdef OPENMS_HAS_UNISTD_H
#include <unistd.h>
#endif
#ifdef OPENMS_HAS_SYS_TIMES_H
#include <sys/times.h>
#endif
#ifdef OPENMS_WINDOWSPLATFORM
#include <windows.h>
#include <sys/timeb.h>
#endif
namespace OpenMS
{
#ifdef OPENMS_WINDOWSPLATFORM
const long long StopWatch::SecondsTo100Nano_ = 10000000LL;
#else
const PointerSizeInt StopWatch::cpu_speed_ = sysconf(_SC_CLK_TCK);
#endif
void StopWatch::clear()
{ // stopped when running
*this = StopWatch(); // default init
}
void StopWatch::start()
{
if (is_running_)
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "StopWatch is already started!");
}
clear();
last_start_ = snapShot_();
is_running_ = true;
}
void StopWatch::stop()
{
if (!is_running_)
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "StopWatch cannot be stopped if not running!");
}
TimeDiff_ now = snapShot_();
auto diff = now - last_start_;
accumulated_times_ += diff;
is_running_ = false;
}
void StopWatch::resume()
{
if (is_running_)
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "StopWatch cannot be resumed if already running!");
}
last_start_ = snapShot_();
is_running_ = true;
}
void StopWatch::reset()
{
if (is_running_ == false)
{
clear();
}
else
{
clear();
start();
}
}
StopWatch::TimeDiff_ StopWatch::snapShot_() const
{
TimeDiff_ t;
#ifdef OPENMS_WINDOWSPLATFORM
LARGE_INTEGER lpFrequency; ///< counts of QueryPerformanceCounter per second; fixed at boot time;
QueryPerformanceFrequency(&lpFrequency);
LARGE_INTEGER tms;
//QueryPerformanceCounter returns values that represent time in units of 1 / (the frequency of the performance counter obtained from QueryPerformanceFrequency)
QueryPerformanceCounter(&tms);
t.start_time = tms.QuadPart / lpFrequency.QuadPart;
const double secToUsec = 1e6;
t.start_time_usec = (PointerSizeInt)((double)(tms.QuadPart - (t.start_time * lpFrequency.QuadPart)) / (double)(lpFrequency.QuadPart) * secToUsec);
FILETIME ct, et, kt, ut;
// ct is creation time of process, but et is end-time (which is undefined for running processes like ours);
// Thus so cannot be used to measure wall time and we need QueryPerformanceCounter from above
GetProcessTimes(GetCurrentProcess(), &ct, &et, &kt, &ut);
ULARGE_INTEGER kernel_time;
kernel_time.HighPart = kt.dwHighDateTime;
kernel_time.LowPart = kt.dwLowDateTime;
ULARGE_INTEGER user_time;
user_time.HighPart = ut.dwHighDateTime;
user_time.LowPart = ut.dwLowDateTime;
t.user_ticks = (TimeType)user_time.QuadPart;
t.kernel_ticks = (TimeType)kernel_time.QuadPart;
#else
struct timeval timeval_buffer;
struct timezone timezone_buffer;
gettimeofday(&timeval_buffer, &timezone_buffer);
t.start_time = timeval_buffer.tv_sec; // seconds since 1970-01-01 00:00
t.start_time_usec = timeval_buffer.tv_usec; // additional(!) usec
struct tms tms_buffer;
times(&tms_buffer);
t.user_ticks = tms_buffer.tms_utime; // reports value in CPU clock ticks
t.kernel_ticks = tms_buffer.tms_stime; // reports value in CPU clock ticks
#endif
return t;
}
//getClockTime returns the current amount of real (clock) time
//accumulated by this stop_watch. If the stop_watch is stopped, this is just
//the total accumulated time. If the stop_watch is running, this is the
//accumulated time + the time since the stop_watch was last started.
double StopWatch::getClockTime() const
{
if (is_running_ == false)
{
/* stop_watch is currently off, so just return accumulated time */
return accumulated_times_.clockTime();
}
/* stop_watch is currently running, so add the elapsed time since */
/* the stop_watch was last started to the accumulated time */
auto now = snapShot_();
auto diff = now - last_start_;
/* convert into floating point number of seconds */
return accumulated_times_.clockTime() + diff.clockTime();
}
//getUserTime reports the current amount of user cpu time
//accumulated by this StopWatch. If the stop_watch is currently off,
//this is just the accumulated time. If the StopWatch is running, this
//is the accumulated time plus the time since the stop_watch was last started.
double StopWatch::getUserTime() const
{
if (is_running_ == false)
{
/* stop_watch is currently off, so just return accumulated time */
return accumulated_times_.userTime();
}
/* stop_watch is currently running, so add the elapsed time since */
/* the stop_watch was last started to the accumulated time */
auto now = snapShot_();
auto diff = now - last_start_;
/* convert into floating point number of seconds */
return accumulated_times_.userTime() + diff.userTime();
}
// system_time reports the current amount of system cpu time
// accumulated by this StopWatch. If the stop_watch is currently off,
// this is just the accumulated time. If the StopWatch is running, this
// is the accumulated time plus the time since the stop_watch was last started
double StopWatch::getSystemTime() const
{
if (is_running_ == false)
{
/* stop_watch is currently off, so just return accumulated time */
return accumulated_times_.kernelTime();
}
/* stop_watch is currently running, so add the elapsed time since */
/* the stop_watch was last started to the accumulated time */
auto now = snapShot_();
auto diff = now - last_start_;
/* convert into floating point number of seconds */
return accumulated_times_.kernelTime() + diff.kernelTime();
}
bool StopWatch::operator==(const StopWatch& rhs) const
{
return accumulated_times_ == rhs.accumulated_times_
&& last_start_ == rhs.last_start_
&& is_running_ == rhs.is_running_;
}
String StopWatch::toString(const double time_in_seconds)
{
int d(0), h(0), m(0), s(0);
TimeType time_i = (TimeType)time_in_seconds; // trunc to integer
// compute days
d = int(time_i / (3600*24));
time_i -= d*(3600*24);
// hours
h = int(time_i / 3600);
time_i -= h*3600;
// minutes
m = int(time_i / 60);
time_i -= m*60;
s = int(time_i);
String s_d = String(d);
String s_h = String(h).fillLeft('0', 2) + ":";
String s_m = String(m).fillLeft('0', 2) + ":";
String s_s = String(s).fillLeft('0', 2); // if we show seconds in combination with minutes, we round to nominal
return ( (d>0 ? s_d + "d " + s_h + s_m + s_s + " h" :
(h>0 ? s_h + s_m + s_s + " h" :
(m>0 ? s_m + s_s + " m" :
( String::number(time_in_seconds, 2) + " s"))))); // second (shown by itself with no minutes) has two digits after decimal
}
String StopWatch::toString() const
{
return(
StopWatch::toString(this->getClockTime()) + " (wall), " +
StopWatch::toString(this->getCPUTime()) + " (CPU), " +
StopWatch::toString(this->getSystemTime()) + " (system), " +
StopWatch::toString(this->getUserTime()) + " (user)"
);
}
double StopWatch::getCPUTime() const
{
return getUserTime() + getSystemTime();
}
bool StopWatch::isRunning() const
{
return is_running_;
}
bool StopWatch::operator!=(const StopWatch & stop_watch) const
{
return !(*this == stop_watch);
}
bool StopWatch::operator<(const StopWatch & stop_watch) const
{
return getCPUTime() < stop_watch.getCPUTime();
}
bool StopWatch::operator<=(const StopWatch & stop_watch) const
{
return !(stop_watch < *this);
}
bool StopWatch::operator>=(const StopWatch & stop_watch) const
{
return !(*this < stop_watch);
}
bool StopWatch::operator>(const StopWatch & stop_watch) const
{
return stop_watch < *this;
}
inline double StopWatch::TimeDiff_::userTime() const
{
return ticksToSeconds_(user_ticks);
}
inline double StopWatch::TimeDiff_::kernelTime() const
{
return ticksToSeconds_(kernel_ticks);
}
inline double StopWatch::TimeDiff_::getCPUTime() const
{
return userTime() + kernelTime();
}
inline double StopWatch::TimeDiff_::clockTime() const
{
return (double)start_time + (double)start_time_usec / 1e6;
}
inline double StopWatch::TimeDiff_::ticksToSeconds_(TimeType in) const
{
#ifdef OPENMS_WINDOWSPLATFORM
return in / double(StopWatch::SecondsTo100Nano_);
#else
return in / double(StopWatch::cpu_speed_); // technically, this is inaccurate since CPU speed may not be constant (turbo-boost)... but finding a better solution is hard...
#endif
}
StopWatch::TimeDiff_ StopWatch::TimeDiff_::operator-(const StopWatch::TimeDiff_& earlier) const
{
TimeDiff_ diff(*this);
diff.kernel_ticks -= earlier.kernel_ticks;
diff.user_ticks -= earlier.user_ticks;
diff.start_time -= earlier.start_time;
diff.start_time_usec -= earlier.start_time_usec;
/* Adjust for the fact that the usec may be negative. */
/* If they are, take away 1 second and add 1 million */
/* microseconds until they are positive. */
while (diff.start_time_usec < 0L)
{
--diff.start_time;
diff.start_time_usec += 1000000L;
}
return diff;
}
StopWatch::TimeDiff_& StopWatch::TimeDiff_::operator+=(const StopWatch::TimeDiff_& other)
{
user_ticks += other.user_ticks;
kernel_ticks += other.kernel_ticks;
start_time += other.start_time;
start_time_usec += other.start_time_usec;
while (start_time_usec > 1000000L)
{
++start_time;
start_time_usec -= 1000000L;
}
return *this;
}
bool StopWatch::TimeDiff_::operator==(const TimeDiff_& rhs) const
{
return user_ticks == rhs.user_ticks &&
kernel_ticks == rhs.kernel_ticks &&
start_time == rhs.start_time &&
start_time_usec == rhs.start_time_usec;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/SYSTEM/SysInfo.cpp | .cpp | 6,518 | 232 | // 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/SYSTEM/SysInfo.h>
#include <array>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <sstream>
#ifdef OPENMS_WINDOWSPLATFORM
#include "windows.h"
#include "psapi.h"
#elif __APPLE__
#include <mach/mach.h>
#include <mach/mach_init.h>
#else
#define OMS_USELINUXMEMORYPLATFORM
#include <cstdio>
#include <unistd.h>
#ifdef OPENMS_HAS_SYS_RESOURCE_H
#include <sys/resource.h> // for rusage
#endif
#endif
namespace OpenMS
{
std::string bytesToHumanReadable(UInt64 bytes)
{
std::array units {"byte", "KiB", "MiB", "GiB", "TiB", "PiB"};
const int divisor = 1024;
double db = double(bytes);
for (const auto u : units)
{
if (db < divisor)
{
std::stringstream ss;
ss << std::setprecision(4) /* 4 digits overall, i.e. 1000 or 1.456 */ << db << ' ' << u;
return ss.str();
}
db /= divisor;
}
// wow ... you made it here...
return std::string("Congrats. That's a lot of bytes: ") + std::to_string(bytes);
}
#ifdef OMS_USELINUXMEMORYPLATFORM
// see http://stackoverflow.com/questions/1558402/memory-usage-of-current-process-in-c
typedef struct {
long size,resident,share,text,lib,data,dt;
} statm_t;
bool read_off_memory_status_linux(statm_t& result)
{
const char* statm_path = "/proc/self/statm";
FILE *f = fopen(statm_path,"r");
if (!f)
{
return false;
}
// get 'data size (heap + stack)' (residence size (vmRSS) is usually too
// small and not changing, total memory (vmSize) is changing but usually
// too large)
// From the proc(5) man-page:
//
// /proc/[pid]/statm
// Provides information about memory usage, measured in pages.
// The columns are:
//
// size total program size
// (same as VmSize in /proc/[pid]/status)
// resident resident set size
// (same as VmRSS in /proc/[pid]/status)
// share shared pages (from shared mappings)
// text text (code)
// lib library (unused in Linux 2.6)
// data data + stack
// dt dirty pages (unused in Linux 2.6)
if (7 != fscanf(f,"%ld %ld %ld %ld %ld %ld %ld",
&result.size,&result.resident,&result.share,&result.text,&result.lib,&result.data,&result.dt))
{
fclose(f);
return false;
}
fclose(f);
return true;
}
#endif
bool SysInfo::getProcessMemoryConsumption(size_t& mem_virtual)
{
mem_virtual = 0;
#ifdef OPENMS_WINDOWSPLATFORM
PROCESS_MEMORY_COUNTERS_EX pmc;
if (!GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)))
{
return false;
}
mem_virtual = pmc.WorkingSetSize / 1024; // byte to KB
#elif __APPLE__
struct task_basic_info_64 t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_64_COUNT;
if (KERN_SUCCESS != task_info(mach_task_self(),
TASK_BASIC_INFO_64, (task_info_t)&t_info,
&t_info_count))
{
return false;
}
mem_virtual = t_info.resident_size / 1024; // byte to KB
#else // Linux
statm_t mem;
if (!read_off_memory_status_linux(mem))
{
return false;
}
mem_virtual = (size_t)mem.resident * (size_t)sysconf(_SC_PAGESIZE) / 1024; // byte to KB
#endif
return true;
}
bool SysInfo::getProcessPeakMemoryConsumption(size_t& mem_virtual)
{
mem_virtual = 0;
#ifdef OPENMS_WINDOWSPLATFORM
PROCESS_MEMORY_COUNTERS_EX pmc;
if (!GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)))
{
return false;
}
mem_virtual = pmc.PeakWorkingSetSize / 1024; // byte to KB
return true;
#elif __APPLE__
rusage ru;
if (getrusage(0, &ru) == 0) // success;
{
mem_virtual = ru.ru_maxrss / 1024; // reported in bytes (whereas Linux is KB!). Convert to KB
return true;
}
return false;
#else // Linux
#ifdef OPENMS_HAS_SYS_RESOURCE_H
rusage ru;
if (getrusage(0, &ru) == 0) // success;
{
mem_virtual = ru.ru_maxrss; // in KB already
return true;
}
#endif
return false;
#endif
}
SysInfo::MemUsage::MemUsage()
: mem_before(0), mem_before_peak(0), mem_after(0), mem_after_peak(0)
{
before();
}
void SysInfo::MemUsage::reset()
{
mem_before = mem_before_peak = mem_after = mem_after_peak = 0;
}
void SysInfo::MemUsage::before()
{
SysInfo::getProcessMemoryConsumption(mem_before);
SysInfo::getProcessPeakMemoryConsumption(mem_before_peak);
}
void SysInfo::MemUsage::after()
{
SysInfo::getProcessMemoryConsumption(mem_after);
SysInfo::getProcessPeakMemoryConsumption(mem_after_peak);
}
String SysInfo::MemUsage::delta(const String& event)
{
if (mem_after == 0)
{
after(); // collect data if missing; do not test using mem_after_peak, since it might be unsupported on the platform
}
String s = String("Memory usage (") + event + "): ";
s += diff_str_(mem_before, mem_after) + " (working set delta)";
if (mem_after_peak > 0)
{ // only if supported
s+= ", " + diff_str_(mem_before_peak, mem_after_peak) + " (peak working set delta)";
}
return s;
}
String SysInfo::MemUsage::usage()
{
if (mem_after == 0)
{
after(); // collect data if missing; do not test using mem_after_peak, since it might be unsupported on the platform
}
String s("Memory usage: ");
s += diff_str_(0, mem_after) + " (working set)";
if (mem_after_peak > 0)
{ // only if supported
s += ", " + diff_str_(0, mem_after_peak) + " (peak working set)";
}
return s;
}
String SysInfo::MemUsage::diff_str_(size_t mem_before, size_t mem_after)
{
String s;
if (mem_after < mem_before)
{
s += String("-");
}
s = String(std::abs(((long long)mem_after - (long long)mem_before) / 1024)) + " MB";
return s;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/SYSTEM/PythonInfo.cpp | .cpp | 3,792 | 104 | // 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/SYSTEM/PythonInfo.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtCore/QProcess>
#include <QtCore/QDir>
#include <sstream>
using namespace std;
namespace OpenMS
{
bool PythonInfo::canRun(String& python_executable, String& error_msg)
{
stringstream ss;
String py_original = python_executable;
if (!File::findExecutable(python_executable))
{
ss << " Python not found at '" << python_executable << "'!\n"
<< " Make sure Python is installed and this location is correct.\n";
if (QDir::isRelativePath(python_executable.toQString()))
{
static String path;
if (path.empty())
{
path = getenv("PATH");
}
ss << " You might need to add the Python binary to your PATH variable\n"
<< " or use an absolute path+filename pointing to Python.\n"
<< " The current SYSTEM PATH is: '" << path << "'.\n\n";
#ifdef __APPLE__
ss << " On MacOSX, application bundles change the system PATH; Open your executable (e.g. KNIME/TOPPAS/TOPPView) from within the bundle (e.g. ./TOPPAS.app/Contents/MacOS/TOPPAS) to preserve the system PATH or use an absolute path to Python!\n";
#endif
}
error_msg = ss.str();
return false;
}
if (python_executable != py_original)
{
ss << "Python executable ('" << py_original << "') resolved to '" << python_executable << "'\n";
}
QProcess qp;
qp.start(python_executable.toQString(), QStringList() << "--version", QIODevice::ReadOnly);
bool success = qp.waitForFinished();
if (!success)
{
if (qp.error() == QProcess::Timedout)
{
ss << " Python was found at '" << python_executable << "' but the process timed out (can happen on very busy systems).\n"
<< " Please free some resources or if you want to run the TOPP tool nevertheless set the TOPP tools 'force' flag in order to avoid this check.\n";
}
else if (qp.error() == QProcess::FailedToStart)
{
ss << " Python found at '" << python_executable << "' but failed to run!\n"
<< " Make sure you have the rights to execute this binary file.\n";
}
else
{
ss << " Error executing '" << python_executable << "'!\n"
<< " Error description: '" << qp.errorString().toStdString() << "'.\n";
}
}
error_msg = ss.str();
return success;
}
bool PythonInfo::isPackageInstalled(const String& python_executable, const String& package_name)
{
QProcess qp;
qp.start(python_executable.toQString(), QStringList() << "-c" << (String("import ") + package_name).c_str(), QIODevice::ReadOnly);
bool success = qp.waitForFinished();
return (success && qp.exitStatus() == QProcess::ExitStatus::NormalExit && qp.exitCode() == 0);
}
String PythonInfo::getVersion(const String& python_executable)
{
String v;
QProcess qp;
qp.start(python_executable.toQString(), QStringList() << "--version", QIODevice::ReadOnly);
bool success = qp.waitForFinished();
if (success && qp.exitStatus() == QProcess::ExitStatus::NormalExit && qp.exitCode() == 0)
{
v = qp.readAllStandardOutput().toStdString(); // some pythons report is on stdout
v += qp.readAllStandardError().toStdString(); // ... some on stderr
v.trim(); // remove '\n'
}
return v;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/SYSTEM/JavaInfo.cpp | .cpp | 2,806 | 71 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/SYSTEM/JavaInfo.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtCore/QProcess>
#include <QtCore/QDir>
namespace OpenMS
{
bool JavaInfo::canRun(const String& java_executable, bool verbose_on_error)
{
QProcess qp;
qp.start(java_executable.toQString(), QStringList() << "-version", QIODevice::ReadOnly);
bool success = qp.waitForFinished();
if (!success && verbose_on_error)
{
OPENMS_LOG_ERROR << "Java-Check:\n";
if (qp.error() == QProcess::Timedout)
{
OPENMS_LOG_ERROR
<< " Java was found at '" << java_executable << "' but the process timed out (can happen on very busy systems).\n"
<< " Please free some resources or if you want to run the TOPP tool nevertheless set the TOPP tools 'force' flag in order to avoid this check." << std::endl;
}
else if (qp.error() == QProcess::FailedToStart)
{
OPENMS_LOG_ERROR
<< " Java not found at '" << java_executable << "'!\n"
<< " Make sure Java is installed and this location is correct.\n";
if (QDir::isRelativePath(java_executable.toQString()))
{
static String path;
if (path.empty())
{
path = getenv("PATH");
}
OPENMS_LOG_ERROR << " You might need to add the Java binary to your PATH variable\n"
<< " or use an absolute path+filename pointing to Java.\n"
<< " The current SYSTEM PATH is: '" << path << "'.\n\n"
#ifdef __APPLE__
<< " On MacOSX, application bundles change the system PATH; Open your executable (e.g. KNIME/TOPPAS/TOPPView) from within the bundle (e.g. ./TOPPAS.app/Contents/MacOS/TOPPAS) to preserve the system PATH or use an absolute path to Java!\n"
#endif
<< std::endl;
}
else
{
OPENMS_LOG_ERROR << " You gave an absolute path to Java. Please check if it's correct.\n"
<< " You can also try 'java' if your system path is correctly configured.\n"
<< std::endl;
}
}
else
{
OPENMS_LOG_ERROR << " Error executing '" << java_executable << "'!\n"
<< " Error description: '" << qp.errorString().toStdString() << "'.\n";
}
}
return success;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/SYSTEM/NetworkGetRequest.cpp | .cpp | 2,348 | 95 | // 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/SYSTEM/NetworkGetRequest.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <QtNetwork/QNetworkRequest>
#include <QtGui/QTextDocument>
using namespace std;
namespace OpenMS
{
NetworkGetRequest::NetworkGetRequest(QObject* parent) :
QObject(parent), reply_(nullptr)
{
manager_ = new QNetworkAccessManager(this);
}
NetworkGetRequest::~NetworkGetRequest() = default;
void NetworkGetRequest::setUrl(const QUrl& url)
{
url_ = url;
}
void NetworkGetRequest::run()
{
if (reply_ == nullptr)
{
error_ = QNetworkReply::NoError;
error_string_ = "";
QNetworkRequest request;
request.setUrl(url_);
request.setHeader(QNetworkRequest::ContentTypeHeader, "text/plain");
connect(manager_, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
reply_ = manager_->get(request);
}
}
void NetworkGetRequest::replyFinished(QNetworkReply* reply)
{
if (reply_ != nullptr)
{
error_ = reply->error();
error_string_ = error_ != QNetworkReply::NoError ? reply->errorString() : "";
response_bytes_ = reply->readAll(); // in case of error this will just read the error html from the server
reply->close();
reply->deleteLater();;
}
emit done();
}
void NetworkGetRequest::timeOut()
{
if (reply_ != nullptr)
{
error_ = QNetworkReply::TimeoutError;
error_string_ = "TimeoutError: the connection to the remote server timed out";
reply_->abort();
reply_->close();
reply_->deleteLater();
}
emit done();
}
const QByteArray& NetworkGetRequest::getResponseBinary() const
{
return response_bytes_;
}
QString NetworkGetRequest::getResponse() const
{
return QString(response_bytes_);
}
bool NetworkGetRequest::hasError() const
{
return error_ != QNetworkReply::NoError;
}
QString NetworkGetRequest::getErrorString() const
{
return error_string_;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/FileHandler.cpp | .cpp | 43,025 | 1,448 | // 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/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/DTAFile.h>
#include <OpenMS/FORMAT/DTA2DFile.h>
#include <OpenMS/FORMAT/EDTAFile.h>
#include <OpenMS/FORMAT/MzXMLFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FORMAT/FeatureXMLFile.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/FORMAT/MzDataFile.h>
#include <OpenMS/FORMAT/MascotGenericFile.h>
#include <OpenMS/FORMAT/MS2File.h>
#include <OpenMS/FORMAT/MSPFile.h>
#include <OpenMS/FORMAT/MSPGenericFile.h>
#include <OpenMS/FORMAT/MzIdentMLFile.h>
#include <OpenMS/FORMAT/MzQCFile.h>
#include <OpenMS/FORMAT/OMSSAXMLFile.h>
#include <OpenMS/FORMAT/OMSFile.h>
#include <OpenMS/FORMAT/ProtXMLFile.h>
#include <OpenMS/FORMAT/QcMLFile.h>
#include <OpenMS/FORMAT/SqMassFile.h>
#include <OpenMS/FORMAT/XMassFile.h>
#include <OpenMS/FORMAT/TraMLFile.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/FORMAT/TransformationXMLFile.h>
#include <OpenMS/FORMAT/XQuestResultXMLFile.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <OpenMS/METADATA/ID/IdentificationDataConverter.h>
#include <OpenMS/FORMAT/MsInspectFile.h>
#include <OpenMS/FORMAT/SpecArrayFile.h>
#include <OpenMS/FORMAT/KroenikFile.h>
#include <OpenMS/KERNEL/ChromatogramTools.h>
#include <OpenMS/FORMAT/GzipIfstream.h>
#include <OpenMS/FORMAT/Bzip2Ifstream.h>
#include <QtCore/QFile>
#include <QtCore/QCryptographicHash>
using namespace std;
namespace OpenMS
{
String allowedToString_(vector<FileTypes::Type> types)
{
String aStrings;
for (auto i : types)
{
if (i != FileTypes::SIZE_OF_TYPE)
{
aStrings += ", " + FileTypes::typeToName(i);
}
}
return aStrings;
}
FileTypes::Type FileHandler::getType(const String& filename)
{
FileTypes::Type type = getTypeByFileName(filename);
if (type == FileTypes::UNKNOWN)
{
type = getTypeByContent(filename);
}
return type;
}
FileTypes::Type FileHandler::getTypeByFileName(const String& filename)
{
String basename = File::basename(filename), tmp;
// special rules for "double extensions":
if (basename.hasSuffix(".pep.xml"))
{
return FileTypes::PEPXML;
}
if (basename.hasSuffix(".prot.xml"))
{
return FileTypes::PROTXML;
}
if (basename.hasSuffix(".xquest.xml"))
{
return FileTypes::XQUESTXML;
}
if (basename.hasSuffix(".spec.xml"))
{
return FileTypes::SPECXML;
}
try
{
tmp = basename.suffix('.');
}
// no '.' => unknown type
catch (Exception::ElementNotFound&)
{
// last chance, Bruker fid file
if (basename == "fid")
{
return FileTypes::XMASS;
}
return FileTypes::UNKNOWN;
}
tmp.toUpper();
if (tmp == "BZ2" || tmp == "GZ") // todo ZIP (not supported yet): || tmp == "ZIP"
{
// do not use getTypeByContent() here, as this is deadly for output files!
return getTypeByFileName(filename.prefix(filename.size() - tmp.size() - 1)); // check name without compression suffix (e.g. bla.mzML.gz --> bla.mzML)
}
return FileTypes::nameToType(tmp);
}
bool FileHandler::hasValidExtension(const String& filename, const FileTypes::Type type)
{
FileTypes::Type ft = FileHandler::getTypeByFileName(filename);
return (ft == type || ft == FileTypes::UNKNOWN);
}
String FileHandler::stripExtension(const String& filename)
{
if (!filename.has('.'))
{
return filename;
}
// we don't just search for the last '.' and remove the suffix, because this could be wrong, e.g. bla.mzML.gz would become bla.mzML
auto type = getTypeByFileName(filename);
auto s_type = FileTypes::typeToName(type);
size_t pos = String(filename).toLower().rfind(s_type.toLower()); // search backwards in entire string, because we could search for 'mzML' and have 'mzML.gz'
if (pos == string::npos) // file type was FileTypes::UNKNOWN and we did not find '.unknown' as ending
{
size_t ext_pos = filename.rfind('.');
size_t dir_sep = filename.find_last_of("/\\"); // look for '/' or '\'
if (dir_sep != string::npos && dir_sep > ext_pos) // we found a directory separator after the last '.', e.g. '/my.dotted.dir/filename'! Ouch!
{ // do not strip anything, because there is no extension to strip
return filename;
}
return filename.prefix(ext_pos);
}
return filename.prefix(pos - 1); // strip the '.' as well
}
String FileHandler::swapExtension(const String& filename, const FileTypes::Type new_type)
{
return stripExtension(filename) + "." + FileTypes::typeToName(new_type);
}
bool FileHandler::isSupported(FileTypes::Type type)
{
if (type == FileTypes::UNKNOWN || type == FileTypes::SIZE_OF_TYPE)
{
return false;
}
else
{
return true;
}
}
FileTypes::Type FileHandler::getConsistentOutputfileType(const String& output_filename, const String& requested_type)
{
FileTypes::Type t_file = getTypeByFileName(output_filename);
FileTypes::Type t_req = FileTypes::nameToType(requested_type);
// both UNKNOWN
if (t_file == FileTypes::Type::UNKNOWN && t_req == FileTypes::Type::UNKNOWN)
{
OPENMS_LOG_ERROR << "Type of '" << output_filename << "' and requested output type '" << requested_type << "' are both unknown." << std::endl;
return FileTypes::Type::UNKNOWN;
}
// or inconsistent (while both are known)
if ((t_file != t_req) && (t_file != FileTypes::Type::UNKNOWN) + (t_req != FileTypes::Type::UNKNOWN) == 2)
{
OPENMS_LOG_ERROR << "Type of '" << output_filename << "' and requested output type '" << requested_type << "' are inconsistent." << std::endl;
return FileTypes::Type::UNKNOWN;
}
if (t_file != FileTypes::Type::UNKNOWN)
{
return t_file;
}
else
{
return t_req;
}
}
FileTypes::Type FileHandler::getTypeByContent(const String& filename)
{
String first_line;
String two_five;
String all_simple;
// only the first five lines will be set for compressed files
// so far, compression is only supported for XML files
vector<String> complete_file;
// test whether the file is compressed (bzip2 or gzip)
ifstream compressed_file(filename.c_str());
char bz[2];
compressed_file.read(bz, 2);
char g1 = 0x1f;
char g2 = 0;
g2 |= 1 << 7;
g2 |= 1 << 3;
g2 |= 1 << 1;
g2 |= 1 << 0;
compressed_file.close();
if (bz[0] == 'B' && bz[1] == 'Z') // bzip2
{
Bzip2Ifstream bzip2_file(filename.c_str());
// read in 1024 bytes (keep last byte for zero to end string)
char buffer[1024];
size_t bytes_read = bzip2_file.read(buffer, 1024-1);
buffer[bytes_read] = '\0';
// get first five lines
String buffer_str(buffer);
vector<String> split;
buffer_str.split('\n', split);
split.resize(5);
first_line = split[0];
two_five = split[1] + ' ' + split[2] + ' ' + split[3] + ' ' + split[4];
all_simple = first_line + ' ' + two_five;
complete_file = split;
}
else if (bz[0] == g1 && bz[1] == g2) // gzip
{
GzipIfstream gzip_file(filename.c_str());
// read in 1024 bytes (keep last byte for zero to end string)
char buffer[1024];
size_t bytes_read = gzip_file.read(buffer, 1024-1);
buffer[bytes_read] = '\0';
// get first five lines
String buffer_str(buffer);
vector<String> split;
buffer_str.split('\n', split);
split.resize(5);
first_line = split[0];
two_five = split[1] + ' ' + split[2] + ' ' + split[3] + ' ' + split[4];
all_simple = first_line + ' ' + two_five;
complete_file = split;
}
//else {} // TODO: ZIP
else // uncompressed
{
//load first 5 lines
TextFile file(filename, true, 5);
TextFile::ConstIterator file_it = file.begin();
// file could be empty
if (file_it == file.end())
{
two_five = " ";
all_simple = " ";
first_line = " ";
}
else
{
// concat elements 2 to 5
two_five = "";
++file_it;
for (int i = 1; i < 5; ++i)
{
if (file_it != file.end())
{
two_five += *file_it;
++file_it;
}
else
{
two_five += "";
}
two_five += " ";
}
// remove trailing space
two_five = two_five.chop(1);
two_five.substitute('\t', ' ');
all_simple = *(file.begin()) + ' ' + two_five;
first_line = *(file.begin());
}
complete_file.insert(complete_file.end(), file.begin(), file.end());
}
//std::cerr << "\n Line1:\n" << first_line << "\nLine2-5:\n" << two_five << "\nall:\n" << all_simple << "\n\n";
//mzXML (all lines)
if (all_simple.hasSubstring("<mzXML"))
{
return FileTypes::MZXML;
}
//mzData (all lines)
if (all_simple.hasSubstring("<mzData"))
{
return FileTypes::MZDATA;
}
//mzML (all lines)
if (all_simple.hasSubstring("<mzML"))
{
return FileTypes::MZML;
}
//"analysisXML" aka. mzid (all lines)
if (all_simple.hasSubstring("<MzIdentML"))
{
return FileTypes::MZIDENTML;
}
//subject to change!
if (all_simple.hasSubstring("<MzQualityMLType"))
{
return FileTypes::QCML;
}
//pepXML (all lines)
if (all_simple.hasSubstring("xmlns=\"http://regis-web.systemsbiology.net/pepXML\""))
{
return FileTypes::PEPXML;
}
//protXML (all lines)
if (all_simple.hasSubstring("xmlns=\"http://regis-web.systemsbiology.net/protXML\""))
{
return FileTypes::PROTXML;
}
//feature map (all lines)
if (all_simple.hasSubstring("<featureMap"))
{
return FileTypes::FEATUREXML;
}
//idXML (all lines)
if (all_simple.hasSubstring("<IdXML"))
{
return FileTypes::IDXML;
}
//consensusXML (all lines)
if (all_simple.hasSubstring("<consensusXML"))
{
return FileTypes::CONSENSUSXML;
}
//TOPPAS (all lines)
if (all_simple.hasSubstring("<PARAMETERS") && all_simple.hasSubstring("<NODE name=\"info\"") && all_simple.hasSubstring("<ITEM name=\"num_vertices\""))
{
return FileTypes::TOPPAS;
}
//INI (all lines) (must be AFTER TOPPAS) - as this is less restrictive
if (all_simple.hasSubstring("<PARAMETERS"))
{
return FileTypes::INI;
}
//TrafoXML (all lines)
if (all_simple.hasSubstring("<TrafoXML"))
{
return FileTypes::TRANSFORMATIONXML;
}
//GelML (all lines)
if (all_simple.hasSubstring("<GelML"))
{
return FileTypes::GELML;
}
//traML (all lines)
if (all_simple.hasSubstring("<TraML"))
{
return FileTypes::TRAML;
}
//OMSSAXML file
if (all_simple.hasSubstring("<MSResponse"))
{
return FileTypes::OMSSAXML;
}
//MASCOTXML file
if (all_simple.hasSubstring("<mascot_search_results"))
{
return FileTypes::MASCOTXML;
}
if (all_simple.hasPrefix("{"))
{
return FileTypes::JSON;
}
//FASTA file
// .. check this fairly early on, because other file formats might be less specific
{
Size i = 0;
Size bigger_than = 0;
while (i < complete_file.size())
{
if (complete_file[i].trim().hasPrefix(">"))
{
++bigger_than;
++i;
}
else if (complete_file[i].trim().hasPrefix("#"))
{
++i;
}
else
{
break;
}
}
if (bigger_than > 0)
{
return FileTypes::FASTA;
}
}
// PNG file (to be really correct, the first eight bytes of the file would
// have to be checked; see e.g. the Wikipedia article)
if (first_line.substr(1, 3) == "PNG")
{
return FileTypes::PNG;
}
//MSP (all lines)
for (Size i = 0; i != complete_file.size(); ++i)
{
if (complete_file[i].hasPrefix("Name: ") && complete_file[i].hasSubstring("/"))
{
return FileTypes::MSP;
}
if (complete_file[i].hasPrefix("Num peaks: "))
{
return FileTypes::MSP;
}
}
//tokenize lines 2-5
vector<String> parts;
two_five.split(' ', parts);
//DTA
if (parts.size() == 8)
{
bool conversion_error = false;
try
{
for (Size i = 0; i < 8; ++i)
{
parts[i].toFloat();
}
}
catch ( Exception::ConversionError& )
{
conversion_error = true;
}
if (!conversion_error)
{
return FileTypes::DTA;
}
}
//DTA2D
if (parts.size() == 12)
{
bool conversion_error = false;
try
{
for (Size i = 0; i < 12; ++i)
{
parts[i].toFloat();
}
}
catch ( Exception::ConversionError& )
{
conversion_error = true;
}
if (!conversion_error)
{
return FileTypes::DTA2D;
}
}
// MGF (Mascot Generic Format)
if (two_five.hasSubstring("BEGIN IONS"))
{
return FileTypes::MGF;
}
else
{
for (Size i = 0; i != complete_file.size(); ++i)
{
if (complete_file[i].trim() == "FORMAT=Mascot generic" || complete_file[i].trim() == "BEGIN IONS")
{
return FileTypes::MGF;
}
}
}
// MS2 file format
if (all_simple.hasSubstring("CreationDate"))
{
if (!all_simple.empty() && all_simple[0] == 'H')
{
return FileTypes::MS2;
}
}
// mzTab file format
for (Size i = 0; i != complete_file.size(); ++i) {
if (complete_file[i].hasSubstring("MTD\tmzTab-version")) {
return FileTypes::MZTAB;
}
}
// msInspect file (.tsv)
for (Size i = 0; i != complete_file.size(); ++i)
{
if (complete_file[i].hasSubstring("scan\ttime\tmz\taccurateMZ\tmass\tintensity\tcharge\tchargeStates\tkl\tbackground\tmedian\tpeaks\tscanFirst\tscanLast\tscanCount\ttotalIntensity\tsumSquaresDist\tdescription"))
{
return FileTypes::TSV;
}
}
// specArray file (.pepList)
if (first_line.hasSubstring(" m/z\t rt(min)\t snr\t charge\t intensity"))
{
return FileTypes::PEPLIST;
}
// hardkloer file (.hardkloer)
/**
NOT IMPLEMENTED YET
if (first_line.hasSubstring("File First Scan Last Scan Num of Scans Charge Monoisotopic Mass Base Isotope Peak Best Intensity Summed Intensity First RTime Last RTime Best RTime Best Correlation Modifications"))
{
return FileTypes::HARDKLOER;
}
**/
// kroenik file (.kroenik)
if (first_line.hasSubstring("File\tFirst Scan\tLast Scan\tNum of Scans\tCharge\tMonoisotopic Mass\tBase Isotope Peak\tBest Intensity\tSummed Intensity\tFirst RTime\tLast RTime\tBest RTime\tBest Correlation\tModifications"))
{
return FileTypes::KROENIK;
}
// Percolator tab-delimited output (PSM level, .psms)
if (first_line.hasPrefix("PSMId\tscore\tq-value\tposterior_error_prob\tpeptide\tproteinIds"))
{
return FileTypes::PSMS;
}
// EDTA file
// hard to tell... so we don't even try...
return FileTypes::UNKNOWN;
}
PeakFileOptions& FileHandler::getOptions()
{
return options_;
}
const PeakFileOptions& FileHandler::getOptions() const
{
return options_;
}
void FileHandler::setOptions(const PeakFileOptions& options)
{
options_ = options;
}
FeatureFileOptions& FileHandler::getFeatOptions()
{
return f_options_;
}
const FeatureFileOptions& FileHandler::getFeatOptions() const
{
return f_options_;
}
void FileHandler::setFeatOptions(const FeatureFileOptions& f_options)
{
f_options_ = f_options;
}
String FileHandler::computeFileHash(const String& filename)
{
QCryptographicHash crypto(QCryptographicHash::Sha1);
QFile file(filename.toQString());
file.open(QFile::ReadOnly);
while (!file.atEnd())
{
crypto.addData(file.read(8192));
}
return String((QString)crypto.result().toHex());
}
void FileHandler::loadSpectrum(const String& filename, MSSpectrum& spec, const std::vector<FileTypes::Type> allowed_types)
{
// determine file type
FileTypes::Type type = getType(filename);
// If we have a restricted set of file types check that we match them
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for loading a spectrum. Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::DTA:
{
DTAFile().load(filename, spec);
}
break;
case FileTypes::XMASS:
{
XMassFile().load(filename, spec);
}
break;
default:
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) +" is not supported for loading a spectrum");
}
}
}
void FileHandler::storeSpectrum(const String& filename, MSSpectrum& spec, const std::vector<FileTypes::Type> allowed_types)
{
auto type = getTypeByFileName(filename);
if (type == FileTypes::Type::UNKNOWN && (allowed_types.size() == 1))
{ // filename is unspecific, but allowed_types is unambiguous (i.e. they do not contradict)
type = allowed_types[0];
}
// If we have a restricted set of file types check that we match them
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for storing an spectrum. Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::DTA:
{
DTAFile().store(filename, spec);
}
break;
case FileTypes::XMASS:
{
XMassFile().store(filename, spec);
}
break;
default:
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type is not supported for loading experiments");
}
}
}
void FileHandler::loadExperiment(const String& filename, PeakMap& exp, const std::vector<FileTypes::Type> allowed_types, ProgressLogger::LogType log, const bool rewrite_source_file,
const bool compute_hash)
{
// setting the flag for hash recomputation only works if source file entries are rewritten
OPENMS_PRECONDITION(rewrite_source_file || !compute_hash, "Can't compute hash if no SourceFile written");
// determine file type
FileTypes::Type type = getType(filename);
// If we have a restricted set of file types check that we match them
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for loading an experiment. Allowed types are: " + allowedToString_(allowed_types));
}
}
// load right file
switch (type)
{
case FileTypes::DTA:
{
exp.reset();
exp.resize(1);
DTAFile().load(filename, exp[0]);
}
break;
case FileTypes::DTA2D:
{
DTA2DFile f;
f.getOptions() = options_;
f.setLogType(log);
f.load(filename, exp);
}
break;
case FileTypes::MZXML:
{
MzXMLFile f;
f.getOptions() = options_;
f.setLogType(log);
f.load(filename, exp);
}
break;
case FileTypes::MZDATA:
{
MzDataFile f;
f.getOptions() = options_;
f.setLogType(log);
f.load(filename, exp);
}
break;
case FileTypes::MZML:
{
MzMLFile f;
f.getOptions() = options_;
f.setLogType(log);
f.load(filename, exp);
ChromatogramTools().convertSpectraToChromatograms<PeakMap>(exp, true);
}
break;
case FileTypes::MGF:
{
MascotGenericFile f;
f.setLogType(log);
f.load(filename, exp);
}
break;
case FileTypes::MS2:
{
MS2File f;
f.setLogType(log);
f.load(filename, exp);
}
break;
case FileTypes::SQMASS:
{
SqMassFile().load(filename, exp);
}
break;
case FileTypes::XMASS:
{
exp.reset();
exp.resize(1);
XMassFile().load(filename, exp[0]);
XMassFile().importExperimentalSettings(filename, exp);
}
break;
case FileTypes::MSP:
{
MSPGenericFile().load(filename, exp);
}
break;
default:
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type is not supported for loading experiments");
}
}
if (rewrite_source_file)
{
SourceFile src_file;
if (exp.getSourceFiles().empty()) // copy settings like native ID format
{
OPENMS_LOG_WARN << "No source file annotated." << endl;
}
else
{
if (exp.getSourceFiles().size() > 1)
{
OPENMS_LOG_WARN << "Expecting a single source file in mzML. Found " << exp.getSourceFiles().size() << " will take only first one for rewriting." << endl;
}
src_file = exp.getSourceFiles()[0];
}
src_file.setNameOfFile(File::basename(filename));
String path_to_file = File::path(File::absolutePath(filename)); // convert to absolute path and strip file name
// make sure we end up with at most 3 forward slashes
String uri = path_to_file.hasPrefix("/") ? String("file://") + path_to_file : String("file:///") + path_to_file;
src_file.setPathToFile(uri);
// this is more complicated since the data formats allowed by mzML are very verbose.
// this is prone to changing CV's... our writer will fall back to a default if the name given here is invalid.
src_file.setFileType(FileTypes::typeToMZML(type));
if (compute_hash)
{
src_file.setChecksum(computeFileHash(filename), SourceFile::ChecksumType::SHA1);
}
exp.getSourceFiles().clear();
exp.getSourceFiles().push_back(src_file);
}
}
void FileHandler::storeExperiment(const String& filename, const PeakMap& exp, const std::vector<FileTypes::Type> allowed_types, ProgressLogger::LogType log)
{
auto type = getTypeByFileName(filename);
if (type == FileTypes::Type::UNKNOWN && (allowed_types.size() == 1))
{ // filename is unspecific, but allowed_types is unambiguous (i.e. they do not contradict)
type = allowed_types[0];
}
// If we have a restricted set of file types check that we match them
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for storing an experiment. Allowed types are: " + allowedToString_(allowed_types));
}
}
// load right file
switch (type)
{
case FileTypes::DTA:
{
DTAFile().store(filename, exp[0]);
}
break;
case FileTypes::DTA2D:
{
DTA2DFile f;
f.getOptions() = options_;
f.setLogType(log);
f.store(filename, exp);
}
break;
case FileTypes::MGF:
{
MascotGenericFile f;
f.setLogType(log);
f.store(filename, exp);
}
break;
case FileTypes::MSP:
{
MSPGenericFile f;
// TODO add support for parameters
f.store(filename, exp);
}
break;
case FileTypes::MZXML:
{
MzXMLFile f;
f.getOptions() = options_;
f.setLogType(log);
if (!exp.getChromatograms().empty())
{
PeakMap exp2 = exp;
ChromatogramTools().convertChromatogramsToSpectra<PeakMap>(exp2);
f.store(filename, exp2);
}
else
{
f.store(filename, exp);
}
}
break;
case FileTypes::SQMASS:
{
SqMassFile f;
// f.setConfig()
f.store(filename, exp);
}
break;
case FileTypes::MZDATA:
{
MzDataFile f;
f.getOptions() = options_;
f.setLogType(log);
if (!exp.getChromatograms().empty())
{
PeakMap exp2 = exp;
ChromatogramTools().convertChromatogramsToSpectra<PeakMap>(exp2);
f.store(filename, exp2);
}
else
{
f.store(filename, exp);
}
}
break;
case FileTypes::MZML:
{
MzMLFile f;
f.getOptions() = options_;
f.setLogType(log);
f.store(filename, exp);
}
break;
default:
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not supported for storing experiments");
}
}
}
void FileHandler::loadFeatures(const String& filename, FeatureMap& map, const std::vector<FileTypes::Type> allowed_types, ProgressLogger::LogType log)
{
// determine file type
FileTypes::Type type = getType(filename);
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for loading features. Allowed types are: " + allowedToString_(allowed_types));
}
}
// load right file
switch (type)
{
case FileTypes::FEATUREXML:
{
FeatureXMLFile f;
f.setLogType(log);
f.getOptions() = f_options_;
f.load(filename, map);
}
break;
case FileTypes::TSV:
{
MsInspectFile().load(filename, map);
}
break;
case FileTypes::PEPLIST:
{
SpecArrayFile().load(filename, map);
}
break;
case FileTypes::KROENIK:
{
KroenikFile().load(filename, map);
}
break;
case FileTypes::OMS:
{
OMSFile f;
f.setLogType(log);
f.load(filename, map);
}
break;
default:
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename,"type: " + FileTypes::typeToName(type) + " is not supported for loading features");
}
}
}
void FileHandler::storeFeatures(const String& filename, const FeatureMap& map, const std::vector<FileTypes::Type> allowed_types, ProgressLogger::LogType log)
{
auto type = getTypeByFileName(filename);
if (type == FileTypes::Type::UNKNOWN && (allowed_types.size() == 1))
{ // filename is unspecific, but allowed_types is unambiguous (i.e. they do not contradict)
type = allowed_types[0];
}
// If we have a restricted set of file types check that we match them
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for storing features. Allowed types are: " + allowedToString_(allowed_types));
}
}
//store right file
switch (type)
{
case FileTypes::FEATUREXML:
{
FeatureXMLFile f;
f.setLogType(log);
f.getOptions() = f_options_;
f.store(filename, map);
}
break;
case FileTypes::EDTA:
{
EDTAFile f;
f.store(filename, map);
}
break;
case FileTypes::TSV:
{
MsInspectFile().store(filename, map);
}
break;
case FileTypes::OMS:
{
OMSFile f;
f.setLogType(log);
f.store(filename, map);
}
break;
case FileTypes::PEPLIST:
{
SpecArrayFile().store(filename, map);
}
break;
case FileTypes::KROENIK:
{
KroenikFile().store(filename, map);
}
break;
default:
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not supported for storing features");
}
}
}
void FileHandler::loadConsensusFeatures(const String& filename, ConsensusMap& map, const std::vector<FileTypes::Type> allowed_types, ProgressLogger::LogType log)
{
//determine file type
FileTypes::Type type = getType(filename);
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for loading consensus features, Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::CONSENSUSXML:
{
ConsensusXMLFile f;
f.getOptions() = options_;
f.setLogType(log);
f.load(filename, map);
}
break;
case FileTypes::EDTA:
{
EDTAFile f;
f.load(filename, map);
}
break;
case FileTypes::OMS:
{
OMSFile f;
f.setLogType(log);
f.load(filename, map);
}
break;
default:
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not supported for loading consensus features");
}
}
}
void FileHandler::storeConsensusFeatures(const String& filename, const ConsensusMap& map, const std::vector<FileTypes::Type> allowed_types, ProgressLogger::LogType log)
{
auto type = getTypeByFileName(filename);
if (type == FileTypes::Type::UNKNOWN && (allowed_types.size() == 1))
{ // filename is unspecific, but allowed_types is unambiguous (i.e. they do not contradict)
type = allowed_types[0];
}
// If we have a restricted set of file types check that we match them
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for storing an Consensus Features. Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::CONSENSUSXML:
{
ConsensusXMLFile f;
f.setLogType(log);
f.store(filename, map);
}
break;
case FileTypes::EDTA:
{
EDTAFile f;
f.store(filename, map);
}
break;
case FileTypes::OMS:
{
OMSFile f;
f.setLogType(log);
f.store(filename, map);
}
break;
default:
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not supported for storing consensus features");
}
}
}
void FileHandler::loadIdentifications(const String& filename, std::vector<ProteinIdentification>& additional_proteins, PeptideIdentificationList& additional_peptides, const std::vector<FileTypes::Type> allowed_types, ProgressLogger::LogType log)
{
//determine file type
FileTypes::Type type = getType(filename);
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for loading identifications, Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::IDXML:
{
IdXMLFile f;
f.setLogType(log);
f.load(filename, additional_proteins, additional_peptides);
}
break;
case FileTypes::MZIDENTML:
{
MzIdentMLFile f;
f.setLogType(log);
f.load(filename, additional_proteins, additional_peptides);
}
break;
case FileTypes::OMS:
{
OMSFile f;
f.setLogType(log);
IdentificationData idd;
f.load(filename, idd);
IdentificationDataConverter::exportIDs(idd, additional_proteins, additional_peptides);
}
break;
case FileTypes::XQUESTXML:
{
XQuestResultXMLFile f;
f.setLogType(log);
f.load(filename, additional_peptides, additional_proteins);
}
break;
case FileTypes::OMSSAXML:
{
additional_proteins.push_back(ProteinIdentification());
OMSSAXMLFile().load(filename, additional_proteins[0],
additional_peptides, true, true);
}
break;
/*case FileTypes::MASCOTXML:
{
OPENMS_LOG_ERROR << "File " << filename << " Loading Identifications is not yet supported for MASCOTXML files" << endl;
return false;
}*/
case FileTypes::PROTXML:
{
additional_proteins.push_back(ProteinIdentification());
additional_peptides.push_back(PeptideIdentification());
ProtXMLFile().load(filename, additional_proteins.back(), additional_peptides.back());
}
break;
default:
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not supported for loading identifications");
}
}
void FileHandler::storeIdentifications(const String& filename, const std::vector<ProteinIdentification>& additional_proteins, const PeptideIdentificationList& additional_peptides, const std::vector<FileTypes::Type> allowed_types, ProgressLogger::LogType log)
{
auto type = getTypeByFileName(filename);
if (type == FileTypes::Type::UNKNOWN && (allowed_types.size() == 1))
{ // filename is unspecific, but allowed_types is unambiguous (i.e. they do not contradict)
type = allowed_types[0];
}
// If we have a restricted set of file types check that we match them
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for storing identifications. Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::IDXML:
{
IdXMLFile f;
f.setLogType(log);
f.store(filename, additional_proteins, additional_peptides);
}
break;
case FileTypes::MZIDENTML:
{
MzIdentMLFile f;
f.setLogType(log);
f.store(filename, additional_proteins, additional_peptides);
}
break;
case FileTypes::OMS:
{
OMSFile f;
f.setLogType(log);
IdentificationData idd;
IdentificationDataConverter::importIDs(idd, additional_proteins, additional_peptides);
f.store(filename, idd);
}
break;
case FileTypes::XQUESTXML:
{
XQuestResultXMLFile f;
f.setLogType(log);
f.store(filename, additional_proteins, additional_peptides);
}
break;
default:
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not supported for storing Identifications");
}
}
}
void FileHandler::loadTransitions(const String& filename,TargetedExperiment& library, const std::vector<FileTypes::Type> allowed_types, ProgressLogger::LogType log)
{
//determine file type
FileTypes::Type type = getType(filename);
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for loading transitions, Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::TRAML:
{
TraMLFile f;
f.setLogType(log);
f.load(filename, library);
}
break;
default:
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename,"type: " + FileTypes::typeToName(type) + " is not supported for loading transitions");
}
}
}
void FileHandler::storeTransitions(const String& filename, const TargetedExperiment& library, const std::vector<FileTypes::Type> allowed_types, ProgressLogger::LogType log)
{
auto type = getTypeByFileName(filename);
if (type == FileTypes::Type::UNKNOWN && (allowed_types.size() == 1))
{ // filename is unspecific, but allowed_types is unambiguous (i.e. they do not contradict)
type = allowed_types[0];
}
// If we have a restricted set of file types check that we match them
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for storing transitions. Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::TRAML:
{
TraMLFile f;
f.setLogType(log);
f.store(filename, library);
}
break;
default:
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not supported for storing transitions");
}
}
}
void FileHandler::loadTransformations(const String& filename, TransformationDescription& map, bool fit_model, const std::vector<FileTypes::Type> allowed_types)
{
//determine file type
FileTypes::Type type = getType(filename);
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for loading transformations, Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::TRANSFORMATIONXML:
{
TransformationXMLFile().load(filename, map, fit_model);
}
break;
default:
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename,"type: " + FileTypes::typeToName(type) + " is not supported for loading transformations");
}
}
}
void FileHandler::storeTransformations(const String& filename, const TransformationDescription& map, const std::vector<FileTypes::Type> allowed_types)
{
auto type = getTypeByFileName(filename);
if (type == FileTypes::Type::UNKNOWN && (allowed_types.size() == 1))
{ // filename is unspecific, but allowed_types is unambiguous (i.e. they do not contradict)
type = allowed_types[0];
}
// If we have a restricted set of file types check that we match them
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for storing transformations. Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::TRANSFORMATIONXML:
{
TransformationXMLFile().store(filename, map);
}
break;
default:
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not supported for storing transformations");
}
}
}
void FileHandler::storeQC(const String& input_file,
const String& filename,
const MSExperiment& exp,
const FeatureMap& feature_map,
std::vector<ProteinIdentification>& prot_ids,
PeptideIdentificationList& pep_ids,
const ConsensusMap& consensus_map,
const String& contact_name,
const String& contact_address,
const String& description,
const String& label,
const bool remove_duplicate_features,
const std::vector<FileTypes::Type> allowed_types
)
{
auto type = getTypeByFileName(filename);
if (type == FileTypes::Type::UNKNOWN && (allowed_types.size() == 1))
{ // filename is unspecific, but allowed_types is unambiguous (i.e. they do not contradict)
type = allowed_types[0];
}
// If we have a restricted set of file types check that we match them
if (allowed_types.size() != 0)
{
if (!FileTypeList(allowed_types).contains(type))
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not allowed for storing QC data. Allowed types are: " + allowedToString_(allowed_types));
}
}
switch (type)
{
case FileTypes::QCML:
{
QcMLFile qcmlfile;
qcmlfile.collectQCData(prot_ids, pep_ids, feature_map,
consensus_map, input_file, remove_duplicate_features, exp);
qcmlfile.store(filename);
}
break;
case FileTypes::MZQC:
{
MzQCFile().store(input_file, filename, exp, contact_name, contact_address,
description, label, feature_map, prot_ids, pep_ids);
}
break;
default:
{
throw Exception::InvalidFileType(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "type: " + FileTypes::typeToName(type) + " is not supported for storing QC data");
}
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/IdXMLFile.cpp | .cpp | 37,384 | 1,077 | // 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/FORMAT/IdXMLFile.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/PrecisionWrapper.h>
#include <OpenMS/CONCEPT/UniqueIdGenerator.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/SYSTEM/File.h>
#include <fstream>
#include <unordered_map>
using namespace std;
namespace OpenMS
{
IdXMLFile::IdXMLFile() :
XMLHandler("", "1.5"),
XMLFile("/SCHEMAS/IdXML_1_5.xsd", "1.5"),
last_meta_(nullptr),
document_id_(),
prot_id_in_run_(false)
{
}
void IdXMLFile::load(const String& filename, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids)
{
String document_id;
load(filename, protein_ids, peptide_ids, document_id);
}
void IdXMLFile::load(const String& filename, std::vector<ProteinIdentification>& protein_ids,
PeptideIdentificationList& peptide_ids, String& document_id)
{
startProgress(0, 0, "Loading idXML");
//Filename for error messages in XMLHandler
file_ = filename;
protein_ids.clear();
peptide_ids.clear();
prot_ids_ = &protein_ids;
pep_ids_ = &peptide_ids;
document_id_ = &document_id;
parse_(filename, this);
//reset members
prot_ids_ = nullptr;
pep_ids_ = nullptr;
last_meta_ = nullptr;
parameters_.clear();
param_ = ProteinIdentification::SearchParameters();
id_ = "";
prot_id_ = ProteinIdentification();
pep_id_ = PeptideIdentification();
prot_hit_ = ProteinHit();
pep_hit_ = PeptideHit();
proteinid_to_accession_.clear();
endProgress();
}
void IdXMLFile::store(const String& filename, const std::vector<ProteinIdentification>& protein_ids, const PeptideIdentificationList& peptide_ids, const String& document_id)
{
if (!FileHandler::hasValidExtension(filename, FileTypes::IDXML))
{
throw Exception::UnableToCreateFile(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
filename,
"invalid file extension, expected '" + FileTypes::typeToName(FileTypes::IDXML) + "'");
}
//set filename for the handler. Just in case (e.g. when fatalError function is used).
file_ = filename;
//open stream
std::ofstream os(filename.c_str());
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
startProgress(0, peptide_ids.size(), "Storing idXML");
os.precision(writtenDigits<double>(0.0));
// write header
os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
os << "<?xml-stylesheet type=\"text/xsl\" href=\"https://www.openms.de/xml-stylesheet/IdXML.xsl\" ?>\n";
os << "<IdXML version=\"" << getVersion() << "\"";
if (!document_id.empty())
{
os << " id=\"" << document_id << "\"";
}
os << " xsi:noNamespaceSchemaLocation=\"https://www.openms.de/xml-schema/IdXML_1_5.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
// look up different search parameters
std::vector<ProteinIdentification::SearchParameters> params;
for (std::vector<ProteinIdentification>::const_iterator it = protein_ids.begin(); it != protein_ids.end(); ++it)
{
if (find(params.begin(), params.end(), it->getSearchParameters()) == params.end())
{
params.push_back(it->getSearchParameters());
}
}
// write search parameters
for (Size i = 0; i != params.size(); ++i)
{
os << "\t<SearchParameters "
<< "id=\"SP_" << i << "\" "
<< "db=\"" << writeXMLEscape(params[i].db) << "\" "
<< "db_version=\"" << writeXMLEscape(params[i].db_version) << "\" "
<< "taxonomy=\"" << writeXMLEscape(params[i].taxonomy) << "\" ";
if (params[i].mass_type == ProteinIdentification::PeakMassType::MONOISOTOPIC)
{
os << "mass_type=\"monoisotopic\" ";
}
else if (params[i].mass_type == ProteinIdentification::PeakMassType::AVERAGE)
{
os << "mass_type=\"average\" ";
}
os << "charges=\"" << params[i].charges << "\" ";
String enzyme_name = params[i].digestion_enzyme.getName();
os << "enzyme=\"" << enzyme_name.toLower() << "\" ";
String precursor_unit = params[i].precursor_mass_tolerance_ppm ? "true" : "false";
String peak_unit = params[i].fragment_mass_tolerance_ppm ? "true" : "false";
os << "missed_cleavages=\"" << params[i].missed_cleavages << "\" "
<< "precursor_peak_tolerance=\"" << params[i].precursor_mass_tolerance << "\" ";
os << "precursor_peak_tolerance_ppm=\"" << precursor_unit << "\" ";
os << "peak_mass_tolerance=\"" << params[i].fragment_mass_tolerance << "\" ";
os << "peak_mass_tolerance_ppm=\"" << peak_unit << "\" ";
os << ">\n";
//modifications
for (Size j = 0; j != params[i].fixed_modifications.size(); ++j)
{
os << "\t\t<FixedModification name=\"" << writeXMLEscape(params[i].fixed_modifications[j]) << "\" />\n";
//Add MetaInfo, when modifications has it (Andreas)
}
for (Size j = 0; j != params[i].variable_modifications.size(); ++j)
{
os << "\t\t<VariableModification name=\"" << writeXMLEscape(params[i].variable_modifications[j]) << "\" />\n";
//Add MetaInfo, when modifications has it (Andreas)
}
writeUserParam_("UserParam", os, params[i], 4);
if (params[i].enzyme_term_specificity != EnzymaticDigestion::SPEC_UNKNOWN)
{
os << "\t\t\t\t<UserParam name=\"EnzymeTermSpecificity\" type=\"string\" value=\"" << EnzymaticDigestion::NamesOfSpecificity[params[i].enzyme_term_specificity] << "\" />\n";
}
os << "\t</SearchParameters>\n";
}
//empty search parameters
if (params.empty())
{
os << "<SearchParameters charges=\"+0, +0\" id=\"ID_1\" db_version=\"0\" mass_type=\"monoisotopic\" peak_mass_tolerance=\"0.0\" precursor_peak_tolerance=\"0.0\" db=\"Unknown\"/>\n";
}
// throws if protIDs are not unique, i.e. PeptideIDs will be randomly assigned (bad!)
checkUniqueIdentifiers_(protein_ids);
UInt prot_count = 0;
std::unordered_map<string, UInt> accession_to_id;
size_t protein_count{0};
for (const auto& pi : protein_ids)
{
protein_count += pi.getHits().size();
}
accession_to_id.reserve(protein_count); // expect this many keys (avoid rehashing)
// identifiers of protein identifications that are already written
std::vector<String> done_identifiers;
// write ProteinIdentification Runs
for (Size i = 0; i < protein_ids.size(); ++i)
{
done_identifiers.push_back(protein_ids[i].getIdentifier());
os << "\t<IdentificationRun ";
os << "date=\"" << protein_ids[i].getDateTime().getDate() << "T" << protein_ids[i].getDateTime().getTime() << "\" ";
os << "search_engine=\"" << writeXMLEscape(protein_ids[i].getSearchEngine()) << "\" ";
os << "search_engine_version=\"" << writeXMLEscape(protein_ids[i].getSearchEngineVersion()) << "\" ";
// identifier
for (Size j = 0; j != params.size(); ++j)
{
if (params[j] == protein_ids[i].getSearchParameters())
{
os << "search_parameters_ref=\"SP_" << j << "\" ";
break;
}
}
os << ">\n";
os << "\t\t<ProteinIdentification ";
os << "score_type=\"" << writeXMLEscape(protein_ids[i].getScoreType()) << "\" ";
if (protein_ids[i].isHigherScoreBetter())
{
os << "higher_score_better=\"true\" ";
}
else
{
os << "higher_score_better=\"false\" ";
}
double significance_threshold = protein_ids[i].getSignificanceThreshold();
os << "significance_threshold=\"" << String(significance_threshold) << "\" >\n";
// write protein hits
size_t hit_count { protein_ids[i].getHits().size() };
for (Size j = 0; j < hit_count; ++j)
{
os << "\t\t\t<ProteinHit "
<< "id=\"PH_" << String(prot_count) << "\" "
<< "accession=\"" << writeXMLEscape(protein_ids[i].getHits()[j].getAccession()) << "\" "
<< "score=\"" << String(protein_ids[i].getHits()[j].getScore()) << "\" ";
accession_to_id[protein_ids[i].getHits()[j].getAccession()] = prot_count;
++prot_count;
double coverage = protein_ids[i].getHits()[j].getCoverage();
if (coverage != ProteinHit::COVERAGE_UNKNOWN)
{
os << "coverage=\"" << String(coverage) << "\" ";
}
os << "sequence=\"" << writeXMLEscape(protein_ids[i].getHits()[j].getSequence()) << "\" >\n";
writeUserParam_("UserParam", os, protein_ids[i].getHits()[j], 4);
os << "\t\t\t</ProteinHit>\n";
}
// add ProteinGroup info to metavalues (hack)
MetaInfoInterface meta = protein_ids[i];
addProteinGroups_(meta, protein_ids[i].getProteinGroups(),
"protein_group", accession_to_id, STORE);
addProteinGroups_(meta, protein_ids[i].getIndistinguishableProteins(),
"indistinguishable_proteins", accession_to_id, STORE);
writeUserParam_("UserParam", os, meta, 3);
os << "\t\t</ProteinIdentification>\n";
//write PeptideIdentifications
Size count_wrong_id(0);
Size count_empty(0);
for (Size l = 0; l < peptide_ids.size(); ++l)
{
setProgress(l);
if (peptide_ids[l].getIdentifier() != protein_ids[i].getIdentifier())
{
++count_wrong_id;
continue;
}
else if (peptide_ids[l].getHits().empty())
{
++count_empty;
continue;
}
os << "\t\t<PeptideIdentification "
<< "score_type=\"" << writeXMLEscape(peptide_ids[l].getScoreType()) << "\" ";
if (peptide_ids[l].isHigherScoreBetter())
{
os << "higher_score_better=\"true\" ";
}
else
{
os << "higher_score_better=\"false\" ";
}
double significance_threshold = peptide_ids[l].getSignificanceThreshold();
os << "significance_threshold=\"" << String(significance_threshold) << "\" ";
// mz
if (peptide_ids[l].hasMZ())
{
os << "MZ=\"" << String(peptide_ids[l].getMZ()) << "\" ";
}
// rt
if (peptide_ids[l].hasRT())
{
os << "RT=\"" << String(peptide_ids[l].getRT()) << "\" ";
}
// spectrum_reference
const DataValue& dv = peptide_ids[l].getMetaValue("spectrum_reference");
if (dv != DataValue::EMPTY)
{
os << "spectrum_reference=\"" << writeXMLEscape(dv.toString()) << "\" ";
}
os << ">\n";
// write peptide hits
std::vector<String> protein_accessions;
// copy current hit
PeptideIdentification pep_id = peptide_ids[l];
// sort by score
pep_id.sort();
const vector<PeptideHit>& pep_hits = pep_id.getHits();
for (const PeptideHit& p_hit : pep_hits)
{
os << "\t\t\t<PeptideHit"
<< " score=\"" << String(p_hit.getScore()) << "\""
<< " sequence=\"" << writeXMLEscape(p_hit.getSequence().toString()) << "\""
<< " charge=\"" << String(p_hit.getCharge()) << "\"";
const std::vector<PeptideEvidence>& pes = p_hit.getPeptideEvidences();
createFlankingAAXMLString_(pes, os);
createPositionXMLString_(pes, os);
// Extract all protein accessions.
// Note: protein accessions correspond to neighboring AAs and start/end
// positions, so we have to keep the same order and allow duplicates
// (for peptides matching multiple times in the same protein)
protein_accessions.clear();
for (vector<PeptideEvidence>::const_iterator pe = pes.begin(); pe != pes.end(); ++pe)
{
const String& protein_accession = pe->getProteinAccession();
// empty accessions are not written out (legacy code)
if (!protein_accession.empty())
{
const auto acc = accession_to_id.find(protein_accession);
if (acc != accession_to_id.end())
{
protein_accessions.emplace_back("PH_" + String(acc->second));
}
else
{
throw Exception::ElementNotFound(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"No accession " + protein_accession + " found in run '" + protein_ids[i].getIdentifier() +
"' for PSM " + p_hit.getSequence().toString() + "_" + String(p_hit.getCharge()) +
". Please contact the maintainer of this tool e.g. on GitHub as this should not happen.");
}
}
}
if (!protein_accessions.empty())
{
os << " protein_refs=\"" << ListUtils::concatenate(protein_accessions, " ") << "\"";
}
os << " >\n";
writeFragmentAnnotations_("UserParam", os, p_hit.getPeakAnnotations(), 4);
writeUserParam_("UserParam", os, p_hit, 4);
os << "\t\t\t</PeptideHit>\n";
}
// do not write "spectrum_reference" or Constants::UserParam::SIGNIFICANCE_THRESHOLD since it is written as attribute already
pep_id.removeMetaValue("spectrum_reference");
pep_id.removeMetaValue(Constants::UserParam::SIGNIFICANCE_THRESHOLD);
writeUserParam_("UserParam", os, pep_id, 3);
os << "\t\t</PeptideIdentification>\n";
}
os << "\t</IdentificationRun>\n";
// on more than one protein Ids (=runs) there must be wrong mappings and the message would be useless. However, a single run should not have wrong mappings!
if (count_wrong_id && protein_ids.size() == 1) OPENMS_LOG_WARN << "Omitted writing of " << count_wrong_id << " peptide identifications due to wrong protein mapping." << std::endl;
if (count_empty) OPENMS_LOG_WARN << "Omitted writing of " << count_empty << " peptide identifications due to empty hits." << std::endl;
}
// empty protein ids parameters
if (protein_ids.empty())
{
os << "<IdentificationRun date=\"1900-01-01T01:01:01.0Z\" search_engine=\"Unknown\" search_parameters_ref=\"ID_1\" search_engine_version=\"0\"/>\n";
}
for (Size i = 0; i < peptide_ids.size(); ++i)
{
if (find(done_identifiers.begin(), done_identifiers.end(), peptide_ids[i].getIdentifier()) == done_identifiers.end())
{
warning(STORE, String("Omitting peptide identification because of missing ProteinIdentification with identifier '") + peptide_ids[i].getIdentifier() + "' while writing '" + filename + "'!");
}
}
// write footer
os << "</IdXML>\n";
// close stream
os.close();
endProgress();
//reset members
prot_ids_ = nullptr;
pep_ids_ = nullptr;
last_meta_ = nullptr;
parameters_.clear();
param_ = ProteinIdentification::SearchParameters();
id_ = "";
prot_id_ = ProteinIdentification();
pep_id_ = PeptideIdentification();
prot_hit_ = ProteinHit();
pep_hit_ = PeptideHit();
proteinid_to_accession_.clear();
}
void IdXMLFile::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes)
{
String tag = sm_.convert(qname);
//START
if (tag == "IdXML")
{
//check file version against schema version
String file_version = "";
prot_id_in_run_ = false;
optionalAttributeAsString_(file_version, attributes, "version");
if (file_version.empty())
{
file_version = "1.0"; //default version is 1.0
}
if (file_version.toDouble() > version_.toDouble())
{
warning(LOAD, "The XML file (" + file_version + ") is newer than the parser (" + version_ + "). This might lead to undefined program behavior.");
}
//document id
String document_id = "";
optionalAttributeAsString_(document_id, attributes, "id");
(*document_id_) = document_id;
}
//SEARCH PARAMETERS
else if (tag == "SearchParameters")
{
//store id
id_ = attributeAsString_(attributes, "id");
//reset parameters
param_ = ProteinIdentification::SearchParameters();
//load parameters
param_.db = attributeAsString_(attributes, "db");
param_.db_version = attributeAsString_(attributes, "db_version");
optionalAttributeAsString_(param_.taxonomy, attributes, "taxonomy");
param_.charges = attributeAsString_(attributes, "charges");
optionalAttributeAsUInt_(param_.missed_cleavages, attributes, "missed_cleavages");
param_.fragment_mass_tolerance = attributeAsDouble_(attributes, "peak_mass_tolerance");
String peak_unit;
optionalAttributeAsString_(peak_unit, attributes, "peak_mass_tolerance_ppm");
param_.fragment_mass_tolerance_ppm = peak_unit == "true" ? true : false;
param_.precursor_mass_tolerance = attributeAsDouble_(attributes, "precursor_peak_tolerance");
String precursor_unit;
optionalAttributeAsString_(precursor_unit, attributes, "precursor_peak_tolerance_ppm");
param_.precursor_mass_tolerance_ppm = precursor_unit == "true" ? true : false;
//mass type
String mass_type = attributeAsString_(attributes, "mass_type");
if (mass_type == "monoisotopic")
{
param_.mass_type = ProteinIdentification::PeakMassType::MONOISOTOPIC;
}
else if (mass_type == "average")
{
param_.mass_type = ProteinIdentification::PeakMassType::AVERAGE;
}
//enzyme
String enzyme;
optionalAttributeAsString_(enzyme, attributes, "enzyme");
if (ProteaseDB::getInstance()->hasEnzyme(enzyme))
{
param_.digestion_enzyme = *(ProteaseDB::getInstance()->getEnzyme(enzyme));
}
last_meta_ = ¶m_;
}
else if (tag == "FixedModification")
{
param_.fixed_modifications.push_back(attributeAsString_(attributes, "name"));
//change this line as soon as there is a MetaInfoInterface for modifications (Andreas)
last_meta_ = nullptr;
}
else if (tag == "VariableModification")
{
param_.variable_modifications.push_back(attributeAsString_(attributes, "name"));
//change this line as soon as there is a MetaInfoInterface for modifications (Andreas)
last_meta_ = nullptr;
}
// RUN
else if (tag == "IdentificationRun")
{
pep_id_ = PeptideIdentification();
prot_id_ = ProteinIdentification();
prot_id_.setSearchEngine(attributeAsString_(attributes, "search_engine"));
prot_id_.setSearchEngineVersion(attributeAsString_(attributes, "search_engine_version"));
//search parameters
String ref = attributeAsString_(attributes, "search_parameters_ref");
if (parameters_.find(ref) == parameters_.end())
{
fatalError(LOAD, String("Invalid search parameters reference '") + ref + "'");
}
prot_id_.setSearchParameters(parameters_[ref]);
//date
prot_id_.setDateTime(DateTime::fromString(attributeAsString_(attributes, "date")));
// set identifier (with UID to make downstream merging of prot_ids possible)
// Note: technically, it would be preferable to prefix the UID for faster string comparison, but this results in random write-orderings during file store (breaks tests)
prot_id_.setIdentifier(prot_id_.getSearchEngine() + '_' + attributeAsString_(attributes, "date") + '_' + String(UniqueIdGenerator::getUniqueId()));
}
//PROTEINS
else if (tag == "ProteinIdentification")
{
prot_id_.setScoreType(attributeAsString_(attributes, "score_type"));
//optional significance threshold
double tmp(0.0);
optionalAttributeAsDouble_(tmp, attributes, "significance_threshold");
if (tmp != 0.0)
{
prot_id_.setSignificanceThreshold(tmp);
}
//score orientation
prot_id_.setHigherScoreBetter(asBool_(attributeAsString_(attributes, "higher_score_better")));
last_meta_ = &prot_id_;
}
else if (tag == "ProteinHit")
{
prot_hit_ = ProteinHit();
String accession = attributeAsString_(attributes, "accession");
prot_hit_.setAccession(accession);
prot_hit_.setScore(attributeAsDouble_(attributes, "score"));
// coverage
double coverage = -std::numeric_limits<double>::max();
optionalAttributeAsDouble_(coverage, attributes, "coverage");
if (coverage != -std::numeric_limits<double>::max())
{
prot_hit_.setCoverage(coverage);
}
// sequence
String tmp;
optionalAttributeAsString_(tmp, attributes, "sequence");
prot_hit_.setSequence(std::move(tmp));
last_meta_ = &prot_hit_;
// insert id and accession to map
proteinid_to_accession_[attributeAsString_(attributes, "id")] = accession;
}
// PEPTIDES
else if (tag == "PeptideIdentification")
{
// check whether a prot id has been given, add "empty" one to list else
if (!prot_id_in_run_)
{
prot_ids_->push_back(prot_id_);
prot_id_in_run_ = true; // set to true, cause we have created one; will be reset for next run
}
//set identifier
pep_id_.setIdentifier(prot_ids_->back().getIdentifier());
pep_id_.setScoreType(attributeAsString_(attributes, "score_type"));
//optional significance threshold
double tmp(0.0);
optionalAttributeAsDouble_(tmp, attributes, "significance_threshold");
if (tmp != 0.0)
{
pep_id_.setSignificanceThreshold(tmp);
}
//score orientation
pep_id_.setHigherScoreBetter(asBool_(attributeAsString_(attributes, "higher_score_better")));
//MZ
double tmp2 = -std::numeric_limits<double>::max();
optionalAttributeAsDouble_(tmp2, attributes, "MZ");
if (tmp2 != -std::numeric_limits<double>::max())
{
pep_id_.setMZ(tmp2);
}
//RT
tmp2 = -std::numeric_limits<double>::max();
optionalAttributeAsDouble_(tmp2, attributes, "RT");
if (tmp2 != -std::numeric_limits<double>::max())
{
pep_id_.setRT(tmp2);
}
String tmp3;
optionalAttributeAsString_(tmp3, attributes, "spectrum_reference");
if (!tmp3.empty())
{
pep_id_.setSpectrumReference( tmp3);
}
last_meta_ = &pep_id_;
}
else if (tag == "PeptideHit")
{
pep_hit_ = PeptideHit();
peptide_evidences_.clear();
pep_hit_.setCharge(attributeAsInt_(attributes, "charge"));
pep_hit_.setScore(attributeAsDouble_(attributes, "score"));
pep_hit_.setSequence(AASequence::fromString(String(attributeAsString_(attributes, "sequence"))));
//parse optional protein ids to determine accessions
const XMLCh* refs = attributes.getValue(sm_.convert("protein_refs").c_str());
if (refs != nullptr)
{
String accession_string = sm_.convert(refs);
accession_string.trim();
std::vector<String> accessions;
accession_string.split(' ', accessions);
if (!accession_string.empty() && accessions.empty())
{
accessions.push_back(accession_string);
}
for (std::vector<String>::const_iterator it = accessions.begin(); it != accessions.end(); ++it)
{
const auto it2 = proteinid_to_accession_.find(*it);
if (it2 != proteinid_to_accession_.end())
{
PeptideEvidence pe;
pe.setProteinAccession(it2->second);
peptide_evidences_.push_back(std::move(pe));
}
else
{
fatalError(LOAD, String("Invalid protein reference '") + *it + "'");
}
}
}
//aa_before
String tmp;
optionalAttributeAsString_(tmp, attributes, "aa_before");
if (!tmp.empty())
{
std::vector<String> parts;
tmp.split(' ', parts);
if (peptide_evidences_.size() < parts.size())
{
peptide_evidences_.resize(parts.size());
}
for (Size i = 0; i != parts.size(); ++i)
{
peptide_evidences_[i].setAABefore(parts[i][0]);
}
}
//aa_after
tmp = "";
optionalAttributeAsString_(tmp, attributes, "aa_after");
if (!tmp.empty())
{
std::vector<String> parts;
tmp.split(' ', parts);
if (peptide_evidences_.size() < parts.size())
{
peptide_evidences_.resize(parts.size());
}
for (Size i = 0; i != parts.size(); ++i)
{
peptide_evidences_[i].setAAAfter(parts[i][0]);
}
}
//start
tmp = "";
optionalAttributeAsString_(tmp, attributes, "start");
if (!tmp.empty())
{
std::vector<String> parts;
tmp.split(' ', parts);
if (peptide_evidences_.size() < parts.size())
{
peptide_evidences_.resize(parts.size());
}
for (Size i = 0; i != parts.size(); ++i)
{
peptide_evidences_[i].setStart(parts[i].toInt());
}
}
//end
tmp = "";
optionalAttributeAsString_(tmp, attributes, "end");
if (!tmp.empty())
{
std::vector<String> parts;
tmp.split(' ', parts);
if (peptide_evidences_.size() < parts.size())
{
peptide_evidences_.resize(parts.size());
}
for (Size i = 0; i != parts.size(); ++i)
{
peptide_evidences_[i].setEnd(parts[i].toInt());
}
}
last_meta_ = &pep_hit_;
}
// USERPARAM
else if (tag == "UserParam")
{
if (last_meta_ == nullptr)
{
fatalError(LOAD, "Unexpected tag 'UserParam'!");
}
String name = attributeAsString_(attributes, "name");
String type = attributeAsString_(attributes, "type");
// Handle specially encoded pepXML analysis results
if (name.hasPrefix("_ar_"))
{
// must be in PeptideHit (indicated by special _ar_ prefix)
String sfx = name.substr(4, name.size());
String val_name = sfx.substr(sfx.find("_") + 1, sfx.size());
if (val_name.hasPrefix("subscore"))
{
String score_name = val_name.substr(val_name.find("_") + 1, val_name.size());
current_analysis_result_.sub_scores[score_name] = attributeAsDouble_(attributes, "value");
}
else if (val_name == "score_type")
{
if (!current_analysis_result_.score_type.empty())
{
pep_hit_.addAnalysisResults(current_analysis_result_);
}
current_analysis_result_.score_type = attributeAsString_(attributes, "value");
}
else if (val_name == "score")
{
current_analysis_result_.main_score = attributeAsDouble_(attributes, "value");
}
return;
}
if (type == "int")
{
last_meta_->setMetaValue(name, attributeAsInt_(attributes, "value"));
}
else if (type == "float")
{
last_meta_->setMetaValue(name, attributeAsDouble_(attributes, "value"));
}
else if (type == "string")
{
String value = (String)attributeAsString_(attributes, "value");
// TODO: check if we are parsing a peptide hit
if (name == Constants::UserParam::FRAGMENT_ANNOTATION_USERPARAM)
{
std::vector<PeptideHit::PeakAnnotation> annotations;
parseFragmentAnnotation_(value, annotations);
pep_hit_.setPeakAnnotations(annotations);
return;
}
last_meta_->setMetaValue(name, value);
}
else if (type == "intList")
{
last_meta_->setMetaValue(name, attributeAsIntList_(attributes, "value"));
}
else if (type == "floatList")
{
last_meta_->setMetaValue(name, attributeAsDoubleList_(attributes, "value"));
}
else if (type == "stringList")
{
last_meta_->setMetaValue(name, attributeAsStringList_(attributes, "value"));
}
else
{
fatalError(LOAD, String("Invalid UserParam type '") + type + "' of parameter '" + name + "'");
}
}
}
void IdXMLFile::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
String tag = sm_.convert(qname);
// START
if (tag == "IdXML")
{
prot_id_in_run_ = false;
}
// SEARCH PARAMETERS
else if (tag == "SearchParameters")
{
if (last_meta_->metaValueExists("EnzymeTermSpecificity"))
{
String spec = last_meta_->getMetaValue("EnzymeTermSpecificity");
if (spec != "unknown")
{
param_.enzyme_term_specificity = static_cast<EnzymaticDigestion::Specificity>(EnzymaticDigestion::getSpecificityByName(spec));
}
}
last_meta_ = nullptr;
parameters_[id_] = param_;
}
else if (tag == "FixedModification")
{
last_meta_ = ¶m_;
}
else if (tag == "VariableModification")
{
last_meta_ = ¶m_;
}
// PROTEIN IDENTIFICATIONS
else if (tag == "ProteinIdentification")
{
// post processing of ProteinGroups (hack)
getProteinGroups_(prot_id_.getProteinGroups(), "protein_group");
getProteinGroups_(prot_id_.getIndistinguishableProteins(),
"indistinguishable_proteins");
prot_ids_->push_back(prot_id_);
prot_id_ = ProteinIdentification();
last_meta_ = nullptr;
prot_id_in_run_ = true;
}
else if (tag == "IdentificationRun")
{
if (prot_ids_->empty())
{
// add empty <ProteinIdentification> if there was none so far (that's where the IdentificationRun parameters are stored)
prot_ids_->emplace_back(std::move(prot_id_));
}
prot_id_ = ProteinIdentification();
last_meta_ = nullptr;
prot_id_in_run_ = false;
}
else if (tag == "ProteinHit")
{
prot_id_.insertHit(std::move(prot_hit_));
last_meta_ = &prot_id_;
}
//PEPTIDES
else if (tag == "PeptideIdentification")
{
pep_ids_->emplace_back(std::move(pep_id_));
pep_id_ = PeptideIdentification();
last_meta_ = nullptr;
}
else if (tag == "PeptideHit")
{
pep_hit_.setPeptideEvidences(std::move(peptide_evidences_));
peptide_evidences_.clear(); // clear will reset the vector to a valid, known state
if (!current_analysis_result_.score_type.empty())
{
pep_hit_.addAnalysisResults(current_analysis_result_);
}
current_analysis_result_ = PeptideHit::PepXMLAnalysisResult();
pep_id_.insertHit(std::move(pep_hit_));
last_meta_ = &pep_id_;
}
}
void IdXMLFile::addProteinGroups_(
MetaInfoInterface& meta, const std::vector<ProteinIdentification::ProteinGroup>&
groups, const String& group_name, const std::unordered_map<string, UInt>& accession_to_id,
XMLHandler::ActionMode mode)
{
for (Size g = 0; g < groups.size(); ++g)
{
String name = group_name + "_" + String(g);
if (meta.metaValueExists(name))
{
warning(mode, String("Metavalue '") + name + "' already exists. Overwriting...");
}
String accessions;
for (StringList::const_iterator acc_it = groups[g].accessions.begin();
acc_it != groups[g].accessions.end(); ++acc_it)
{
if (acc_it != groups[g].accessions.begin())
{
accessions += ",";
}
const auto pos = accession_to_id.find(*acc_it);
if (pos != accession_to_id.end())
{
accessions += "PH_" + String(pos->second);
}
else
{
fatalError(mode, String("Invalid protein reference '") + *acc_it + "'");
}
}
String value = String(groups[g].probability) + "," + accessions;
meta.setMetaValue(name, value);
}
}
void IdXMLFile::getProteinGroups_(std::vector<ProteinIdentification::ProteinGroup>&
groups, const String& group_name)
{
groups.clear();
Size g_id = 0;
String current_meta = group_name + "_" + String(g_id);
StringList values;
while (last_meta_->metaValueExists(current_meta)) // assumes groups have incremental g_IDs
{
// convert to proper ProteinGroup
ProteinIdentification::ProteinGroup g;
String(last_meta_->getMetaValue(current_meta)).split(',', values);
if (values.size() < 2)
{
fatalError(LOAD, String("Invalid UserParam for ProteinGroups (not enough values)'"));
}
g.probability = values[0].toDouble();
for (Size i_ind = 1; i_ind < values.size(); ++i_ind)
{
g.accessions.push_back(proteinid_to_accession_[values[i_ind]]);
}
groups.push_back(std::move(g));
last_meta_->removeMetaValue(current_meta);
current_meta = group_name + "_" + String(++g_id);
}
}
std::ostream& IdXMLFile::createFlankingAAXMLString_(const std::vector<PeptideEvidence> & pes, std::ostream& os)
{
// Check if information on previous/following aa available. If not, we will not write it out
bool has_aa_before_information(false);
bool has_aa_after_information(false);
String aa_string;
for (const PeptideEvidence& it : pes)
{
if (it.getAABefore() != PeptideEvidence::UNKNOWN_AA)
{
has_aa_before_information = true;
}
if (it.getAAAfter() != PeptideEvidence::UNKNOWN_AA)
{
has_aa_after_information = true;
}
}
if (has_aa_before_information)
{
os << " aa_before=\"" << pes.begin()->getAABefore();;
for (std::vector<PeptideEvidence>::const_iterator it = pes.begin() + 1; it != pes.end(); ++it)
{
os << " " << it->getAABefore();
}
os << "\"";
}
if (has_aa_after_information)
{
os << " aa_after=\"" << pes.begin()->getAAAfter();
for (std::vector<PeptideEvidence>::const_iterator it = pes.begin() + 1; it != pes.end(); ++it)
{
os << " " << it->getAAAfter();
}
os << "\"";
}
return os;
}
std::ostream& IdXMLFile::createPositionXMLString_(const std::vector<PeptideEvidence>& pes, std::ostream& os)
{
bool has_aa_start_information(false);
bool has_aa_end_information(false);
for (const PeptideEvidence& it : pes)
{
if (it.getStart() != PeptideEvidence::UNKNOWN_POSITION)
{
has_aa_start_information = true;
}
if (it.getEnd() != PeptideEvidence::UNKNOWN_POSITION)
{
has_aa_end_information = true;
}
}
if (has_aa_start_information || has_aa_end_information)
{
if (has_aa_start_information)
{
os << " start=\"" << String(pes.begin()->getStart());
for (std::vector<PeptideEvidence>::const_iterator it = pes.begin() + 1; it != pes.end(); ++it)
{
os << " " << String(it->getStart());
}
os << "\"";
}
if (has_aa_end_information)
{
os << " end=\"" << String(pes.begin()->getEnd());
for (std::vector<PeptideEvidence>::const_iterator it = pes.begin() + 1; it != pes.end(); ++it)
{
os << " " << String(it->getEnd());
}
os << "\"";
}
}
return os;
}
void IdXMLFile::writeFragmentAnnotations_(const String & tag_name, std::ostream & os,
const std::vector<PeptideHit::PeakAnnotation>& annotations, UInt indent)
{
String val;
PeptideHit::PeakAnnotation::writePeakAnnotationsString_(val, annotations);
if (!val.empty())
{
os << String(indent, '\t') << "<" << writeXMLEscape(tag_name) << R"( type="string" name="fragment_annotation" value=")" << writeXMLEscape(val) << "\"/>" << "\n";
}
}
void IdXMLFile::parseFragmentAnnotation_(const String& s, std::vector<PeptideHit::PeakAnnotation> & annotations)
{
if (s.empty()) { return; }
StringList as;
s.split_quoted('|', as);
// for each peak annotation: split string and fill fragment annotation entries
StringList fields;
for (const auto& pa : as)
{
pa.split_quoted(',', fields);
if (fields.size() != 4)
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Invalid fragment annotation. Four comma-separated fields required. String is: '" + pa + "'");
}
PeptideHit::PeakAnnotation fa;
fa.mz = fields[0].toDouble();
fa.intensity = fields[1].toDouble();
fa.charge = fields[2].toInt();
fa.annotation = fields[3].unquote();
annotations.push_back(fa);
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/CompressedInputSource.cpp | .cpp | 4,583 | 142 | // 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/FORMAT/CompressedInputSource.h>
#include <OpenMS/FORMAT/GzipInputStream.h>
#include <OpenMS/FORMAT/Bzip2InputStream.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <xercesc/util/XMLUniDefs.hpp>
using namespace xercesc;
namespace OpenMS
{
CompressedInputSource::CompressedInputSource(const String & file_path, const String & header, MemoryManager * const manager) :
xercesc::InputSource(manager),
head_(header)
{
if (head_.size() < 2)
{
head_ = "\0\0";
}
//
// If the path is relative, then complete it according to the current
// working directory rules of the current platform. Else, just take
// it as is.
//
Internal::StringManager strman;
auto file = strman.convert(file_path.c_str());
if (xercesc::XMLPlatformUtils::isRelative(file.c_str(), manager))
{
XMLCh * curDir = xercesc::XMLPlatformUtils::getCurrentDirectory(manager);
XMLSize_t curDirLen = XMLString::stringLen(curDir);
XMLSize_t filePathLen = XMLString::stringLen(file.c_str());
XMLCh * fullDir = (XMLCh *) manager->allocate
(
(curDirLen + filePathLen + 2) * sizeof(XMLCh)
); //new XMLCh [ curDirLen + filePathLen + 2];
XMLString::copyString(fullDir, curDir);
fullDir[curDirLen] = chForwardSlash;
XMLString::copyString(&fullDir[curDirLen + 1], file.c_str());
XMLPlatformUtils::removeDotSlash(fullDir, manager);
XMLPlatformUtils::removeDotDotSlash(fullDir, manager);
setSystemId(fullDir);
manager->deallocate(curDir); //delete [] curDir;
manager->deallocate(fullDir); //delete [] fullDir;
}
else
{
XMLCh * tmpBuf = XMLString::replicate(file.c_str(), manager);
XMLPlatformUtils::removeDotSlash(tmpBuf, manager);
setSystemId(tmpBuf);
manager->deallocate(tmpBuf); //delete [] tmpBuf;
}
}
CompressedInputSource::CompressedInputSource(const XMLCh * const file, const String & header, MemoryManager * const manager) :
xercesc::InputSource(manager),
head_(header)
{
if (head_.size() < 2)
{
head_ = "\0\0";
}
//
// If the path is relative, then complete it according to the current
// working directory rules of the current platform. Else, just take
// it as is.
//
if (xercesc::XMLPlatformUtils::isRelative(file, manager))
{
XMLCh * curDir = xercesc::XMLPlatformUtils::getCurrentDirectory(manager);
XMLSize_t curDirLen = XMLString::stringLen(curDir);
XMLSize_t filePathLen = XMLString::stringLen(file);
XMLCh * fullDir = (XMLCh *) manager->allocate
(
(curDirLen + filePathLen + 2) * sizeof(XMLCh)
); //new XMLCh [ curDirLen + filePathLen + 2];
XMLString::copyString(fullDir, curDir);
fullDir[curDirLen] = chForwardSlash;
XMLString::copyString(&fullDir[curDirLen + 1], file);
XMLPlatformUtils::removeDotSlash(fullDir, manager);
XMLPlatformUtils::removeDotDotSlash(fullDir, manager);
setSystemId(fullDir);
manager->deallocate(curDir); //delete [] curDir;
manager->deallocate(fullDir); //delete [] fullDir;
}
else
{
XMLCh * tmpBuf = XMLString::replicate(file, manager);
XMLPlatformUtils::removeDotSlash(tmpBuf, manager);
setSystemId(tmpBuf);
manager->deallocate(tmpBuf); //delete [] tmpBuf;
}
}
CompressedInputSource::~CompressedInputSource() = default;
BinInputStream * CompressedInputSource::makeStream() const
{
if (head_[0] == 'B' && head_[1] == 'Z')
{
Bzip2InputStream * retStrm = new Bzip2InputStream(Internal::StringManager().convert(getSystemId()));
if (!retStrm->getIsOpen())
{
delete retStrm;
return nullptr;
}
return retStrm;
}
else /* (bz[0] == g1 && bz[1] == g2), where char g1 = 0x1f and char g2 = 0x8b */
{
GzipInputStream * retStrm = new GzipInputStream(Internal::StringManager().convert(getSystemId()));
if (!retStrm->getIsOpen())
{
delete retStrm;
return nullptr;
}
return retStrm;
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/FASTAFile.cpp | .cpp | 7,736 | 314 | // 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, Nora Wild $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CONCEPT/LogStream.h>
namespace OpenMS
{
using namespace std;
bool FASTAFile::readEntry_(std::string& id, std::string& description, std::string& seq)
{
std::streambuf* sb = infile_.rdbuf();
bool keep_reading = true;
bool description_exists = true;
// Skip leading whitespace (including newlines, tabs, spaces)
int c;
while ((c = sb->sgetc()) != std::streambuf::traits_type::eof() &&
(c == ' ' || c == '\t' || c == '\n' || c == '\r'))
{
sb->sbumpc();
}
if (sb->sbumpc() != '>')
{
return false;
}
while (keep_reading)// reading the ID
{
int c = sb->sbumpc();// get and advance to next char
switch (c)
{
case ' ':
case '\t':
if (!id.empty())
{
keep_reading = false; // ID finished
}
break;
case '\n': // ID finished and no description available
keep_reading = false;
description_exists = false;
break;
case '\r':
break;
case std::streambuf::traits_type::eof():
infile_.setstate(std::ios::eofbit);
return false;
default:
id += (char) c;
}
}
if (id.empty())
{
return false;
}
if (description_exists)
{
keep_reading = true;
}
// reading the description
while (keep_reading)
{
int c = sb->sbumpc(); // get and advance to next char
switch (c)
{
case '\n': // description finished
keep_reading = false;
break;
case '\r': // .. or
case '\t':
break;
case std::streambuf::traits_type::eof():
infile_.setstate(std::ios::eofbit);
return false;
default:
description += (char) c;
}
}
// reading the sequence
keep_reading = true;
while (keep_reading)
{
int c = sb->sbumpc(); // get and advance to next char
switch (c)
{
case '\n':
if (sb->sgetc() == '>')// reaching the beginning of the next protein-entry
{
keep_reading = false;
}
break;
case '\r': // not saving white spaces
case ' ':
case '\t':
break;
case std::streambuf::traits_type::eof():
infile_.setstate(std::ios::eofbit);
return !seq.empty();
default:
seq += (char) c;
}
}
return !seq.empty();
}
void FASTAFile::readStart(const String& filename)
{
if (!File::exists(filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
if (!File::readable(filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
if (infile_.is_open()) infile_.close(); // precaution
infile_.open(filename.c_str(), std::ios::binary | std::ios::in);
infile_.seekg(0, infile_.end);
fileSize_ = infile_.tellg();
infile_.seekg(0, infile_.beg);
std::streambuf *sb = infile_.rdbuf();
// Skip leading whitespace and PEFF headers
int c;
while ((c = sb->sgetc()) !=
std::streambuf::traits_type::eof())
{
if (c == '#')
{
infile_.ignore(numeric_limits<streamsize>::max(), '\n');
}
else if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
{
sb->sbumpc();
}
else
{
break;
}
}
entries_read_ = 0;
}
void FASTAFile::readStartWithProgress(const String& filename, const String& progress_label)
{
readStart(filename);
startProgress(0, fileSize_, progress_label);
}
bool FASTAFile::readNext(FASTAEntry &protein)
{
if (infile_.eof())
{
return false;
}
seq_.clear(); // Note: it is fine to clear() after std::move as it will turn the "valid but unspecified state" into a specified (the empty) one
id_.clear();
description_.clear();
if (!readEntry_(id_, description_, seq_))
{
if (entries_read_ == 0)
{
seq_ = "The first entry could not be read!";
}
else
{
seq_ = "Only " + String(entries_read_) + " proteins could be read. Parsing next record failed.";
}
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "",
"Error while parsing FASTA file! " + seq_ + " Please check the file!");
}
++entries_read_;
protein.identifier = std::move(id_);
protein.description = std::move(description_);
protein.sequence = std::move(seq_);
setProgress(infile_.tellg());
return true;
}
bool FASTAFile::readNextWithProgress(FASTAEntry& protein)
{
if (readNext(protein))
{
setProgress(position());
return true;
}
else
{
endProgress();
return false;
}
}
std::streampos FASTAFile::position()
{
return infile_.tellg();
}
bool FASTAFile::setPosition(const std::streampos &pos)
{
if (pos <= fileSize_)
{
infile_.clear(); // when end of file is reached, otherwise it gets -1
infile_.seekg(pos);
return true;
}
return false;
}
bool FASTAFile::atEnd()
{
return (infile_.peek() == std::streambuf::traits_type::eof());
}
void FASTAFile::load(const String &filename, vector<FASTAEntry> &data) const
{
startProgress(0, 1, "Loading FASTA file");
data.clear();
FASTAEntry p;
FASTAFile f;
f.readStart(filename);
while (f.readNext(p))
{
data.push_back(std::move(p));
}
endProgress();
}
void FASTAFile::writeStart(const String &filename)
{
if (!FileHandler::hasValidExtension(filename, FileTypes::FASTA))
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename,
"invalid file extension; expected '" +
FileTypes::typeToName(FileTypes::FASTA) + "'");
}
outfile_.open(filename.c_str(), ofstream::out);
if (!outfile_.good())
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
}
void FASTAFile::writeNext(const FASTAEntry &protein)
{
outfile_ << '>' << protein.identifier << ' ' << protein.description << "\n";
const String &tmp(protein.sequence);
int chunks(tmp.size() / 80); // number of complete chunks
Size chunk_pos(0);
while (--chunks >= 0)
{
outfile_.write(&tmp[chunk_pos], 80);
outfile_ << "\n";
chunk_pos += 80;
}
if (tmp.size() > chunk_pos)
{
outfile_.write(&tmp[chunk_pos], tmp.size() - chunk_pos);
outfile_ << "\n";
}
}
void FASTAFile::writeEnd()
{
outfile_.close();
}
void FASTAFile::store(const String &filename, const vector<FASTAEntry> &data) const
{
startProgress(0, data.size(), "Writing FASTA file");
FASTAFile f;
f.writeStart(filename);
for (const FASTAFile::FASTAEntry& it : data)
{
f.writeNext(it);
nextProgress();
}
f.writeEnd(); // close file
endProgress();
}
}// namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MSNumpressCoder.cpp | .cpp | 11,144 | 373 | // 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/FORMAT/MSNumpressCoder.h>
#include <OpenMS/FORMAT/Base64.h>
#include <OpenMS/FORMAT/MSNUMPRESS/MSNumpress.h>
#include <boost/math/special_functions/fpclassify.hpp> // std::isfinite
// #define NUMPRESS_DEBUG
#include <iostream>
namespace OpenMS
{
const std::string MSNumpressCoder::NamesOfNumpressCompression[] = {"none", "linear", "pic", "slof"};
void MSNumpressCoder::NumpressConfig::setCompression(const std::string& compression)
{
const std::string* match = std::find(NamesOfNumpressCompression,
NamesOfNumpressCompression + SIZE_OF_NUMPRESSCOMPRESSION, compression);
if (match == NamesOfNumpressCompression + SIZE_OF_NUMPRESSCOMPRESSION) // == end()
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Value '" + compression + "' is not a valid Numpress compression scheme.");
}
np_compression = (NumpressCompression)std::distance(NamesOfNumpressCompression, match);
}
using namespace ms; // numpress namespace
void MSNumpressCoder::encodeNP(const std::vector<double> & in, String & result,
bool zlib_compression, const NumpressConfig & config)
{
result.clear();
encodeNPRaw(in, result, config);
if (result.empty())
{
return;
}
// Encode in base64 and compress
std::vector<String> tmp;
tmp.push_back(result);
Base64::encodeStrings(tmp, result, zlib_compression, false);
}
void MSNumpressCoder::encodeNP(const std::vector<float> & in, String & result,
bool zlib_compression, const NumpressConfig & config)
{
std::vector<double> dvector(in.begin(), in.end());
encodeNP(dvector, result, zlib_compression, config);
}
void MSNumpressCoder::decodeNP(const String & in, std::vector<double> & out,
bool zlib_compression, const NumpressConfig & config)
{
String tmpstring;
Base64::decodeSingleString(in, tmpstring, zlib_compression);
// Create a temporary string (*not* null-terminated) to hold the data
decodeNPRaw(tmpstring, out, config);
// NOTE: it is possible (and likely faster) to call directly the const
// unsigned char * function but this would make it necessary to deal with
// reinterpret_cast ugliness here ...
//
// decodeNP_internal_(reinterpret_cast<const unsigned char*>(base64_uncompressed.constData()), base64_uncompressed.size(), out, config);
}
void MSNumpressCoder::encodeNPRaw(const std::vector<double>& in, String& result, const NumpressConfig & config)
{
if (in.empty())
{
return;
}
if (config.np_compression == NONE)
{
return;
}
Size dataSize = in.size();
// using MSNumpress, from johan.teleman@immun.lth.se
std::vector<unsigned char> numpressed;
double fixedPoint = config.numpressFixedPoint;
try
{
size_t byteCount = 0;
// 1. Resize the data
switch (config.np_compression)
{
case LINEAR:
numpressed.resize(dataSize * sizeof(std::vector<double>::value_type) + 8);
break;
case PIC:
numpressed.resize(dataSize * sizeof(std::vector<double>::value_type));
break;
case SLOF:
{
numpressed.resize(dataSize * 2 + 8);
break;
}
case NONE:
break;
default:
break;
}
// 2. Convert the data
std::vector<double> unpressed; // for checking excessive accuracy loss
switch (config.np_compression)
{
case LINEAR:
{
if (config.estimate_fixed_point)
{
// estimate fixed point either by mass accuracy or by using maximal permissible value
if (config.linear_fp_mass_acc > 0)
{
fixedPoint = numpress::MSNumpress::optimalLinearFixedPointMass(&in[0], dataSize, config.linear_fp_mass_acc);
// catch failure
if (fixedPoint < 0.0)
{
fixedPoint = numpress::MSNumpress::optimalLinearFixedPoint(&in[0], dataSize);
}
}
else
{
fixedPoint = numpress::MSNumpress::optimalLinearFixedPoint(&in[0], dataSize);
}
}
byteCount = numpress::MSNumpress::encodeLinear(&in[0], dataSize, &numpressed[0], fixedPoint);
numpressed.resize(byteCount);
if (config.numpressErrorTolerance > 0.0) // decompress to check accuracy loss
{
numpress::MSNumpress::decodeLinear(numpressed, unpressed);
}
break;
}
case PIC:
{
byteCount = numpress::MSNumpress::encodePic(&in[0], dataSize, &numpressed[0]);
numpressed.resize(byteCount);
if (config.numpressErrorTolerance > 0.0) // decompress to check accuracy loss
{
numpress::MSNumpress::decodePic(numpressed, unpressed);
}
break;
}
case SLOF:
{
if (config.estimate_fixed_point)
{
fixedPoint = numpress::MSNumpress::optimalSlofFixedPoint(&in[0], dataSize);
}
byteCount = numpress::MSNumpress::encodeSlof(&in[0], dataSize, &numpressed[0], fixedPoint);
numpressed.resize(byteCount);
if (config.numpressErrorTolerance > 0.0) // decompress to check accuracy loss
{
numpress::MSNumpress::decodeSlof(numpressed, unpressed);
}
break;
}
case NONE:
{
// already checked above ...
break;
}
default:
break;
}
#ifdef NUMPRESS_DEBUG
std::cout << "encodeNPRaw: numpressed array with with length " << numpressed.size() << '\n';
for (int i = 0; i < byteCount; i++)
{
std::cout << "array[" << i << "] : " << (int)numpressed[i] << '\n';
}
#endif
// 3. Now check to see if encoding introduces excessive error
int n = -1;
if (config.numpressErrorTolerance > 0.0)
{
if (PIC == config.np_compression) // integer rounding, abs accuracy is +- 0.5
{
for (n = static_cast<int>(dataSize)-1; n>=0; n-- ) // check for overflow, strange rounding
{
if ((!std::isfinite(unpressed[n])) || (fabs(in[n] - unpressed[n]) >= 1.0))
{
break;
}
}
}
else // check for tolerance as well as overflow
{
for (n=static_cast<int>(dataSize)-1; n>=0; n--)
{
double u = unpressed[n];
double d = in[n];
if (!std::isfinite(u) || !std::isfinite(d))
{
#ifdef NUMPRESS_DEBUG
std::cout << "infinite u: " << u << " d: " << d << '\n';
#endif
break;
}
if (!d)
{
if (fabs(u) > config.numpressErrorTolerance)
{
#ifdef NUMPRESS_DEBUG
std::cout << "fabs(u): " << fabs(u) << " > config.numpressErrorTolerance: " << config.numpressErrorTolerance << '\n';
#endif
break;
}
}
else if (!u)
{
if (fabs(d) > config.numpressErrorTolerance)
{
#ifdef NUMPRESS_DEBUG
std::cout << "fabs(d): " << fabs(d) << " > config.numpressErrorTolerance: " << config.numpressErrorTolerance << '\n';
#endif
break;
}
}
else if (fabs(1.0 - (d / u)) > config.numpressErrorTolerance)
{
#ifdef NUMPRESS_DEBUG
std::cout << "d: " << d << " u: " << u << '\n';
std::cout << "fabs(1.0 - (d / u)): " << fabs(1.0 - (d / u)) << " > config.numpressErrorTolerance: " << config.numpressErrorTolerance << '\n';
#endif
break;
}
}
}
}
if (n >= 0)
{
//Comment: throw?
std::cerr << "Error occurred at position n = " << n << ". Enable NUMPRESS_DEBUG to get more info." << std::endl;
}
else
{
result = String(std::string(reinterpret_cast<const char*>(&numpressed[0]), byteCount));
// Other solution:
// http://stackoverflow.com/questions/2840835/way-to-get-unsigned-char-into-a-stdstring-without-reinterpret-cast
// result = String( std::string(&numpressed[0], &numpressed[0] + byteCount) );
}
}
catch (int e)
{
std::cerr << "MSNumpress encoder threw exception: " << e << std::endl;
}
catch (char const * e)
{
std::cerr << "MSNumpress encoder threw exception: " << e << std::endl;
}
catch (...)
{
std::cerr << "Unknown exception while encoding " << dataSize << " doubles" << std::endl;
}
}
void MSNumpressCoder::decodeNPRaw(const std::string & in, std::vector<double>& out, const NumpressConfig & config)
{
decodeNPInternal_(reinterpret_cast<const unsigned char*>(in.c_str()), in.size(), out, config);
}
void MSNumpressCoder::decodeNPInternal_(const unsigned char* in, size_t in_size, std::vector<double>& out, const NumpressConfig & config)
{
out.clear();
if (in_size == 0) return;
size_t byteCount = in_size;
#ifdef NUMPRESS_DEBUG
std::cout << "decodeNPInternal_: array input with length " << in_size << '\n';
for (int i = 0; i < in_size; i++)
{
std::cout << "array[" << i << "] : " << (int)in[i] << '\n';
}
#endif
try
{
size_t initialSize;
switch (config.np_compression)
{
case LINEAR:
{
initialSize = byteCount * 2;
if (out.size() < initialSize)
{
out.resize(initialSize);
}
size_t count = numpress::MSNumpress::decodeLinear(in, byteCount, &out[0]);
out.resize(count);
break;
}
case PIC:
{
initialSize = byteCount * 2;
if (out.size() < initialSize)
{
out.resize(initialSize);
}
size_t count = numpress::MSNumpress::decodePic(in, byteCount, &out[0]);
out.resize(count);
break;
}
case SLOF:
{
initialSize = byteCount / 2;
if (out.size() < initialSize)
{
out.resize(initialSize);
}
size_t count = numpress::MSNumpress::decodeSlof(in, byteCount, &out[0]);
out.resize(count);
break;
}
case NONE:
{
return;
}
default:
break;
}
}
catch (...)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Error in Numpress decompression");
}
#ifdef NUMPRESS_DEBUG
std::cout << "decodeNPInternal_: output size " << out.size() << '\n';
for (int i = 0; i < out.size(); i++)
{
std::cout << "array[" << i << "] : " << out[i] << '\n';
}
#endif
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ProtXMLFile.cpp | .cpp | 10,006 | 274 | // 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/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/CHEMISTRY/ResidueDB.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/UniqueIdGenerator.h>
#include <OpenMS/FORMAT/ProtXMLFile.h>
using namespace std;
namespace OpenMS
{
ProtXMLFile::ProtXMLFile() :
XMLHandler("", "1.2"),
XMLFile("/SCHEMAS/protXML_v6.xsd", "6.0")
{
}
void ProtXMLFile::load(const String& filename, ProteinIdentification& protein_ids, PeptideIdentification& peptide_ids)
{
//Filename for error messages in XMLHandler
file_ = filename;
resetMembers_();
// reset incoming data
protein_ids = ProteinIdentification();
peptide_ids = PeptideIdentification();
// remember data link while parsing
prot_id_ = &protein_ids;
pep_id_ = &peptide_ids;
parse_(filename, this);
}
void ProtXMLFile::store(const String& /*filename*/, const ProteinIdentification& /*protein_ids*/, const PeptideIdentification& /*peptide_ids*/, const String& /*document_id*/)
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
// resetMembers_();
}
/// reset members
void ProtXMLFile::resetMembers_()
{
prot_id_ = nullptr;
pep_id_ = nullptr;
pep_hit_ = nullptr;
protein_group_ = ProteinGroup();
}
void ProtXMLFile::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes)
{
String tag = sm_.convert(qname);
if (tag == "protein_summary_header")
{
String db = attributeAsString_(attributes, "reference_database");
String enzyme = attributeAsString_(attributes, "sample_enzyme");
ProteinIdentification::SearchParameters sp = prot_id_->getSearchParameters();
sp.db = db;
// find a matching enzyme name
sp.digestion_enzyme = *(ProteaseDB::getInstance()->getEnzyme(enzyme));
prot_id_->setSearchParameters(sp);
prot_id_->setScoreType("ProteinProphet probability");
prot_id_->setHigherScoreBetter(true);
pep_id_->setScoreType("ProteinProphet probability");
pep_id_->setHigherScoreBetter(true);
}
// identifier for Protein & PeptideIdentification
// <program_details analysis="proteinprophet" time="2009-11-29T18:30:03" ...
if (tag == "program_details")
{
String analysis = attributeAsString_(attributes, "analysis");
String time = attributeAsString_(attributes, "time");
String version = attributeAsString_(attributes, "version");
DateTime date;
date.set(time);
if (!date.isValid())
{
OPENMS_LOG_WARN << "Warning: Cannot parse 'time'='" << time << "'.\n";
}
prot_id_->setDateTime(date);
prot_id_->setSearchEngine(analysis);
prot_id_->setSearchEngineVersion(version);
String id = String(UniqueIdGenerator::getUniqueId()); // was: analysis + "_" + time;
prot_id_->setIdentifier(id);
pep_id_->setIdentifier(id);
}
if (tag == "protein_group")
{
// we group all <protein>'s and <indistinguishable_protein>'s in our
// internal group structure
protein_group_ = ProteinGroup();
protein_group_.probability = attributeAsDouble_(attributes, "probability");
}
else if (tag == "protein")
{
// usually there will be just one <protein> per <protein_group>, but more
// are possible; each <protein> is distinguishable from the other, we
// nevertheless group them
String protein_name = attributeAsString_(attributes, "protein_name");
// open new "indistinguishable" group:
prot_id_->insertIndistinguishableProteins(ProteinGroup());
registerProtein_(protein_name); // create new protein
// fill protein with life
double pc_coverage;
if (optionalAttributeAsDouble_(pc_coverage, attributes, "percent_coverage"))
{
prot_id_->getHits().back().setCoverage(pc_coverage);
}
else
{
OPENMS_LOG_WARN << "Required attribute 'percent_coverage' missing\n";
}
prot_id_->getHits().back().setScore(attributeAsDouble_(attributes, "probability"));
}
else if (tag == "indistinguishable_protein")
{
String protein_name = attributeAsString_(attributes, "protein_name");
// current last protein is from the same "indistinguishable" group:
double score = prot_id_->getHits().back().getScore();
registerProtein_(protein_name);
// score of group leader might technically not be transferable (due to
// protein length etc.), but we still transfer it to allow filtering of
// proteins by score without disrupting the groups:
prot_id_->getHits().back().setScore(score);
}
else if (tag == "peptide")
{
// If a peptide is degenerate it will show in multiple groups, but have different statistics (e.g. 'nsp_adjusted_probability')
// We thus treat each instance as a separate peptide
// todo/improvement: link them by a group in PeptideIdentification?!
pep_hit_ = new PeptideHit;
pep_hit_->setSequence(AASequence::fromString(String(attributeAsString_(attributes, "peptide_sequence"))));
pep_hit_->setScore(attributeAsDouble_(attributes, "nsp_adjusted_probability"));
Int charge;
if (optionalAttributeAsInt_(charge, attributes, "charge"))
{
pep_hit_->setCharge(charge);
}
else
{
OPENMS_LOG_WARN << "Required attribute 'charge' missing\n";
}
// add accessions of all indistinguishable proteins the peptide belongs to
ProteinIdentification::ProteinGroup& indist = prot_id_->getIndistinguishableProteins().back();
for (StringList::const_iterator accession = indist.accessions.begin(); accession != indist.accessions.end(); ++accession)
{
PeptideEvidence pe;
pe.setProteinAccession(*accession);
pep_hit_->addPeptideEvidence(pe);
}
pep_hit_->setMetaValue("is_unique", String(attributeAsString_(attributes, "is_nondegenerate_evidence")) == "Y" ? 1 : 0);
pep_hit_->setMetaValue("is_contributing", String(attributeAsString_(attributes, "is_contributing_evidence")) == "Y" ? 1 : 0);
}
else if (tag == "mod_aminoacid_mass")
{
// relates to the last seen peptide (we hope)
Size position = attributeAsInt_(attributes, "position");
double mass = attributeAsDouble_(attributes, "mass");
AASequence temp_aa_sequence(pep_hit_->getSequence());
String temp_description = "";
String origin = temp_aa_sequence[position - 1].getOneLetterCode();
matchModification_(mass, origin, temp_description);
if (!temp_description.empty()) // only if a mod was found
{
// e.g. Carboxymethyl (C)
vector<String> mod_split;
temp_description.split(' ', mod_split);
if (mod_split.size() == 2)
{
if (mod_split[1] == "(C-term)" || ModificationsDB::getInstance()->getModification(temp_description)->getTermSpecificity() == ResidueModification::C_TERM)
{
temp_aa_sequence.setCTerminalModification(mod_split[0]);
}
else
{
if (mod_split[1] == "(N-term)" || ModificationsDB::getInstance()->getModification(temp_description)->getTermSpecificity() == ResidueModification::N_TERM)
{
temp_aa_sequence.setNTerminalModification(mod_split[0]);
}
else
{
// search this mod, if not directly use a general one
temp_aa_sequence.setModification(position - 1, mod_split[0]);
}
}
}
else
{
error(LOAD, String("Cannot parse modification '") + temp_description + "@" + position + "'");
}
}
else
{
error(LOAD, String("Cannot find modification '") + String(mass) + " " + String(origin) + "' @" + String(position));
}
pep_hit_->setSequence(temp_aa_sequence);
}
}
void ProtXMLFile::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
String tag = sm_.convert(qname);
if (tag == "protein_group")
{
prot_id_->insertProteinGroup(protein_group_);
}
else if (tag == "peptide")
{
pep_id_->insertHit(*pep_hit_);
delete pep_hit_;
}
}
void ProtXMLFile::registerProtein_(const String& protein_name)
{
ProteinHit hit;
hit.setAccession(protein_name);
prot_id_->insertHit(hit);
// add protein to groups
protein_group_.accessions.push_back(protein_name);
prot_id_->getIndistinguishableProteins().back().accessions.push_back(
protein_name);
}
void ProtXMLFile::matchModification_(const double mass, const String& origin, String& modification_description)
{
double mod_mass = mass - ResidueDB::getInstance()->getResidue(origin)->getMonoWeight(Residue::Internal);
vector<String> mods;
ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, mod_mass, 0.001, origin);
if (mods.size() == 1)
{
modification_description = mods[0];
}
else
{
if (!mods.empty())
{
String mod_str = mods[0];
for (vector<String>::const_iterator mit = ++mods.begin(); mit != mods.end(); ++mit)
{
mod_str += ", " + *mit;
}
error(LOAD, "Modification '" + String(mass) + "' is not uniquely defined by the given data. Using '" + mods[0] + "' to represent any of '" + mod_str + "'!");
modification_description = mods[0];
}
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/SqliteConnector.cpp | .cpp | 10,931 | 325 | // 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/FORMAT/SqliteConnector.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <sqlite3.h>
#include <cstring> // for strcmp
#include <iostream>
namespace OpenMS
{
SqliteConnector::SqliteConnector(const String& filename, const SqlOpenMode mode)
{
openDatabase_(filename, mode);
}
SqliteConnector::~SqliteConnector()
{
int rc = sqlite3_close_v2(db_);
if (rc != SQLITE_OK)
{
std::cout << " Encountered error in ~SqliteConnector: " << rc << std::endl;
}
}
void SqliteConnector::openDatabase_(const String& filename, const SqlOpenMode mode)
{
// Open database
int flags = 0;
switch (mode)
{
case SqlOpenMode::READONLY:
flags = SQLITE_OPEN_READONLY;
break;
case SqlOpenMode::READWRITE:
flags = SQLITE_OPEN_READWRITE;
break;
case SqlOpenMode::READWRITE_OR_CREATE:
flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
break;
}
int rc = sqlite3_open_v2(filename.c_str(), &db_, flags, nullptr);
if (rc)
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not open sqlite db '" + filename + "' in mode " + String(int(mode)));
}
}
bool SqliteConnector::columnExists(sqlite3 *db, const String& tablename, const String& colname)
{
bool found = false;
sqlite3_stmt* xcntstmt;
prepareStatement(db, &xcntstmt, "PRAGMA table_info(" + tablename + ")");
// Go through all columns and check whether the required column exists
sqlite3_step(xcntstmt);
while (sqlite3_column_type(xcntstmt, 0) != SQLITE_NULL)
{
if (strcmp(colname.c_str(), reinterpret_cast<const char*>(sqlite3_column_text(xcntstmt, 1))) == 0)
{
found = true;
break;
}
sqlite3_step(xcntstmt);
}
sqlite3_finalize(xcntstmt);
return found;
}
bool SqliteConnector::tableExists(sqlite3 *db, const String& tablename)
{
sqlite3_stmt* stmt;
prepareStatement(db, &stmt, "SELECT 1 FROM sqlite_master WHERE type='table' AND name='" + tablename + "';");
sqlite3_step(stmt);
// if we get a row back, the table exists:
bool found = (sqlite3_column_type(stmt, 0) != SQLITE_NULL);
sqlite3_finalize(stmt);
return found;
}
Size SqliteConnector::countTableRows(const String& table_name)
{
sqlite3_stmt* stmt;
String select_runs = "SELECT count(*) FROM " + table_name + ";";
this->prepareStatement(&stmt, select_runs);
sqlite3_step(stmt);
if (sqlite3_column_type(stmt, 0) == SQLITE_NULL)
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not retrieve " + table_name + " table count!");
}
Size res = sqlite3_column_int64(stmt, 0);
sqlite3_finalize(stmt);
return res;
}
void SqliteConnector::executeStatement(sqlite3 *db, const String& statement)
{
char *zErrMsg = nullptr;
int rc = sqlite3_exec(db, statement.c_str(), nullptr /* callback */, nullptr, &zErrMsg);
if (rc != SQLITE_OK)
{
String error(zErrMsg);
std::cerr << "Error message after sqlite3_exec" << std::endl;
std::cerr << "Prepared statement " << statement << std::endl;
sqlite3_free(zErrMsg);
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, error);
}
}
void SqliteConnector::prepareStatement(sqlite3 *db, sqlite3_stmt** stmt, const String& prepare_statement)
{
int rc = sqlite3_prepare_v2(db, prepare_statement.c_str(), (int)prepare_statement.size(), stmt, nullptr);
if (rc != SQLITE_OK)
{
std::cerr << "Error message after sqlite3_prepare_v2" << std::endl;
std::cerr << "Prepared statement " << prepare_statement << std::endl;
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, sqlite3_errmsg(db));
}
}
void SqliteConnector::executeBindStatement(sqlite3 *db, const String& prepare_statement, const std::vector<String>& data)
{
int rc;
sqlite3_stmt *stmt = nullptr;
prepareStatement(db, &stmt, prepare_statement);
for (Size k = 0; k < data.size(); k++)
{
// Fifth argument is a destructor for the blob.
// SQLITE_STATIC because the statement is finalized
// before the buffer is freed:
rc = sqlite3_bind_blob(stmt, k+1, data[k].c_str(), (int)data[k].size(), SQLITE_STATIC);
if (rc != SQLITE_OK)
{
std::cerr << "SQL error after sqlite3_bind_blob at iteration " << k << std::endl;
std::cerr << "Prepared statement " << prepare_statement << std::endl;
// TODO this is a mem-leak (missing sqlite3_finalize())
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, sqlite3_errmsg(db));
}
}
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE)
{
std::cerr << "SQL error after sqlite3_step" << std::endl;
std::cerr << "Prepared statement " << prepare_statement << std::endl;
// TODO this is a mem-leak (missing sqlite3_finalize())
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, sqlite3_errmsg(db));
}
// free memory
sqlite3_finalize(stmt);
}
namespace Internal::SqliteHelper
{
template <> bool extractValue<double>(double* dst, sqlite3_stmt* stmt, int pos) //explicit specialization
{
if (sqlite3_column_type(stmt, pos) != SQLITE_NULL)
{
*dst = sqlite3_column_double(stmt, pos);
return true;
}
return false;
}
template <> bool extractValue<int>(Int32* dst, sqlite3_stmt* stmt, int pos) //explicit specialization
{
if (sqlite3_column_type(stmt, pos) != SQLITE_NULL)
{
*dst = sqlite3_column_int(stmt, pos); // sqlite3_column_int returns 32bit integers
return true;
}
return false;
}
template <> bool extractValue<Int64>(Int64* dst, sqlite3_stmt* stmt, int pos) //explicit specialization
{
if (sqlite3_column_type(stmt, pos) != SQLITE_NULL)
{
*dst = sqlite3_column_int64(stmt, pos);
return true;
}
return false;
}
template <> bool extractValue<String>(String* dst, sqlite3_stmt* stmt, int pos) //explicit specialization
{
if (sqlite3_column_type(stmt, pos) != SQLITE_NULL)
{
*dst = String(reinterpret_cast<const char*>(sqlite3_column_text(stmt, pos)));
return true;
}
return false;
}
template <> bool extractValue<std::string>(std::string* dst, sqlite3_stmt* stmt, int pos) //explicit specialization
{
if (sqlite3_column_type(stmt, pos) != SQLITE_NULL)
{
*dst = std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, pos)));
return true;
}
return false;
}
SqlState nextRow(sqlite3_stmt* stmt, SqlState current)
{
if (current != SqlState::SQL_ROW)
{ // querying a new row after the last invocation gave 'SQL_DONE' might loop around
// to the first entry and give an infinite loop!!!
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Sql operation requested on SQL_DONE/SQL_ERROR state. This should never happen. Please file a bug report!");
}
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW)
{
return SqlState::SQL_ROW;
}
if (rc == SQLITE_DONE)
{
return SqlState::SQL_DONE;
}
if (rc == SQLITE_ERROR)
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Sql operation failed with SQLITE_ERROR!");
}
if (rc == SQLITE_BUSY)
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Sql operation failed with SQLITE_BUSY!");
}
if (rc == SQLITE_MISUSE)
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Sql operation failed with SQLITE_MISUSE!");
}
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Sql operation failed with unexpected error code!");
}
/// Special case: store integer in a string data value
bool extractValueIntStr(String* dst, sqlite3_stmt* stmt, int pos)
{
if (sqlite3_column_type(stmt, pos) == SQLITE_INTEGER)
{
*dst = sqlite3_column_int(stmt, pos);
return true;
}
return false;
}
double extractDouble(sqlite3_stmt* stmt, int pos)
{
double res;
if (!extractValue<double>(&res, stmt, pos))
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Conversion of column " + String(pos) + " to double failed");
}
return res;
}
float extractFloat(sqlite3_stmt* stmt, int pos)
{
double res; // there is no sqlite3_column_float.. so we extract double and convert
if (!extractValue<double>(&res, stmt, pos))
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Conversion of column " + String(pos) + " to double/float failed");
}
return (float)res;
}
int extractInt(sqlite3_stmt* stmt, int pos)
{
int res;
if (!extractValue<int>(&res, stmt, pos))
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Conversion of column " + String(pos) + " to int failed");
}
return res;
}
Int64 extractInt64(sqlite3_stmt* stmt, int pos)
{
Int64 res;
if (!extractValue<Int64>(&res, stmt, pos))
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Conversion of column " + String(pos) + " to Int64 failed");
}
return res;
}
String extractString(sqlite3_stmt* stmt, int pos)
{
String res;
if (!extractValue<String>(&res, stmt, pos))
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Conversion of column " + String(pos) + " to String failed");
}
return res;
}
char extractChar(sqlite3_stmt* stmt, int pos)
{
return extractString(stmt, pos)[0];
}
bool extractBool(sqlite3_stmt* stmt, int pos)
{
return extractInt(stmt, pos) != 0;
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/AbsoluteQuantitationStandardsFile.cpp | .cpp | 2,345 | 61 | // 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/FORMAT/AbsoluteQuantitationStandardsFile.h>
namespace OpenMS
{
void AbsoluteQuantitationStandardsFile::load(
const String& filename,
std::vector<AbsoluteQuantitationStandards::runConcentration>& run_concentrations
) const
{
CsvFile csv(filename);
StringList sl;
std::map<String, Size> headers;
if (csv.rowCount() > 0) // avoid accessing a row in an empty file
{
csv.getRow(0, sl);
}
for (Size i = 0; i < sl.size(); ++i)
{
headers[sl[i]] = i; // for each header found, assign an index value to it
}
run_concentrations.clear();
for (Size i = 1; i < csv.rowCount(); ++i)
{
csv.getRow(i, sl);
run_concentrations.push_back(extractRunFromLine_(sl, headers));
}
}
AbsoluteQuantitationStandards::runConcentration AbsoluteQuantitationStandardsFile::extractRunFromLine_(
const StringList& line,
const std::map<String, Size>& headers
) const
{
AbsoluteQuantitationStandards::runConcentration rc;
std::map<String, Size>::const_iterator it;
it = headers.find("sample_name");
rc.sample_name = it != headers.end() ? line[it->second] : "";
it = headers.find("component_name");
rc.component_name = it != headers.end() ? line[it->second] : "";
it = headers.find("IS_component_name");
rc.IS_component_name = it != headers.end() ? line[it->second] : "";
it = headers.find("actual_concentration");
rc.actual_concentration = it != headers.end() ? line[it->second].toDouble() : 0.0;
it = headers.find("IS_actual_concentration");
rc.IS_actual_concentration = it != headers.end() ? line[it->second].toDouble() : 0.0;
it = headers.find("concentration_units");
rc.concentration_units = it != headers.end() ? line[it->second] : "";
it = headers.find("dilution_factor");
rc.dilution_factor = it != headers.end() ? line[it->second].toDouble() : 1.0;
return rc;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/PepXMLFileMascot.cpp | .cpp | 6,349 | 209 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Nico Pfeifer $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/PepXMLFileMascot.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
using namespace std;
namespace OpenMS
{
PepXMLFileMascot::PepXMLFileMascot() :
XMLHandler("", "1.8"),
XMLFile("/SCHEMAS/PepXML_1_8.xsd", "1.8"),
peptides_(nullptr)
{
}
void PepXMLFileMascot::load(const String & filename, map<String, vector<AASequence> > & peptides)
{
//Filename for error messages in XMLHandler
file_ = filename;
peptides.clear();
peptides_ = &peptides;
parse_(filename, this);
//reset members
actual_title_ = "";
actual_sequence_ = "";
actual_modifications_ = vector<pair<String, UInt> >();
peptides_ = nullptr;
variable_modifications_ = vector<pair<String, double> >();
fixed_modifications_ = vector<String>();
}
void PepXMLFileMascot::matchModification_(double mass, String & modification_description)
{
UInt i = 0;
bool found = false;
while (i < variable_modifications_.size() && !found)
{
double difference = variable_modifications_[i].second - mass;
if (difference < 0)
{
difference *= -1;
}
if (difference < 0.001)
{
modification_description = variable_modifications_[i].first;
found = true;
}
++i;
}
}
void PepXMLFileMascot::startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes)
{
String element = sm_.convert(qname);
//cout << "Start: " << element << "\n";
//SEARCH PARAMETERS
if (element == "aminoacid_modification")
{
String temp_string = attributeAsString_(attributes, "variable");
if (temp_string == "Y")
{
variable_modifications_.emplace_back(attributeAsString_(attributes, "description"),
attributeAsDouble_(attributes, "mass"));
}
else
{
fixed_modifications_.push_back(attributeAsString_(attributes, "description"));
}
}
// <terminal_modification terminus="n" massdiff="+108.05" mass="109.06" variable="N" protein_terminus="" description="dNIC (N-term)"/>
if (element == "terminal_modification")
{
String temp_string = attributeAsString_(attributes, "variable");
if (temp_string == "Y")
{
variable_modifications_.emplace_back(attributeAsString_(attributes, "description"),
attributeAsDouble_(attributes, "mass"));
}
else
{
fixed_modifications_.push_back(attributeAsString_(attributes, "description"));
}
}
//PEPTIDES
else if (element == "spectrum_query")
{
actual_title_ = attributeAsString_(attributes, "spectrum");
}
else if (element == "search_hit")
{
actual_sequence_ = attributeAsString_(attributes, "peptide");
}
else if (element == "mod_aminoacid_mass")
{
String temp_description = "";
UInt modification_position = attributeAsInt_(attributes, "position");
double modification_mass = attributeAsDouble_(attributes, "mass");
matchModification_(modification_mass, temp_description);
// the modification position is 1-based
actual_modifications_.emplace_back(temp_description, modification_position);
}
}
void PepXMLFileMascot::endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname)
{
String element = sm_.convert(qname);
///SEARCH PARAMETERS
if (element == "search_hit")
{
AASequence temp_aa_sequence = AASequence::fromString(actual_sequence_);
// modification position is 1-based
for (vector<pair<String, UInt> >::const_iterator it = actual_modifications_.begin(); it != actual_modifications_.end(); ++it)
{
// e.g. Carboxymethyl (C)
vector<String> mod_split;
it->first.split(' ', mod_split);
if (it->first.hasSubstring("C-term"))
{
temp_aa_sequence.setCTerminalModification(it->first);
}
else if (it->first.hasSubstring("N-term"))
{
temp_aa_sequence.setNTerminalModification(it->first);
}
if (mod_split.size() == 2)
{
temp_aa_sequence.setModification(it->second - 1, mod_split[0]);
}
else
{
error(LOAD, String("Cannot parse modification '") + it->first + "@" + it->second + "'");
}
}
// fixed modifications
for (const String& it : fixed_modifications_)
{
// e.g. Carboxymethyl (C)
vector<String> mod_split;
it.split(' ', mod_split);
if (mod_split.size() == 2)
{
if (mod_split[1] == "(C-term)")
{
temp_aa_sequence.setCTerminalModification(mod_split[0]);
}
else
{
if (mod_split[1] == "(N-term)")
{
temp_aa_sequence.setNTerminalModification(mod_split[0]);
}
else
{
String origin = mod_split[1];
origin.remove(')');
origin.remove('(');
for (Size i = 0; i != temp_aa_sequence.size(); ++i)
{
// best way we can check; because origin can be e.g. (STY)
if (origin.hasSubstring(temp_aa_sequence[i].getOneLetterCode()))
{
temp_aa_sequence.setModification(i, mod_split[0]);
}
}
}
}
}
else
{
error(LOAD, String("Cannot parse fixed modification '") + it + "'");
}
}
actual_aa_sequences_.push_back(temp_aa_sequence);
actual_modifications_.clear();
}
else if (element == "spectrum_query")
{
peptides_->insert(make_pair(actual_title_, actual_aa_sequences_));
actual_aa_sequences_.clear();
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MzTab.cpp | .cpp | 116,938 | 3,175 | // 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/FORMAT/MzTab.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/METADATA/MetaInfoInterfaceUtils.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideHit.h>
#include <OpenMS/METADATA/ProteinHit.h>
#include <OpenMS/METADATA/ExperimentalDesign.h>
#include <OpenMS/PROCESSING/ID/IDFilter.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <tuple>
using namespace std;
namespace OpenMS
{
MzTabModification::MzTabModification() = default;
bool MzTabModification::isNull() const
{
return pos_param_pairs_.empty() && mod_identifier_.isNull();
}
void MzTabModification::setNull(bool b)
{
if (b)
{
pos_param_pairs_.clear();
mod_identifier_.setNull(true);
}
}
void MzTabModification::setPositionsAndParameters(const std::vector<std::pair<Size, MzTabParameter> >& ppp)
{
pos_param_pairs_ = ppp;
}
std::vector<std::pair<Size, MzTabParameter> > MzTabModification::getPositionsAndParameters() const
{
return pos_param_pairs_;
}
void MzTabModification::setModificationIdentifier(const MzTabString& mod_id)
{
mod_identifier_ = mod_id;
}
MzTabString MzTabModification::getModOrSubstIdentifier() const
{
assert(!isNull());
return mod_identifier_;
}
String MzTabModification::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String pos_param_string;
for (Size i = 0; i != pos_param_pairs_.size(); ++i)
{
pos_param_string += pos_param_pairs_[i].first;
// attach MzTabParameter if available
if (!pos_param_pairs_[i].second.isNull())
{
pos_param_string += pos_param_pairs_[i].second.toCellString();
}
// add | as separator (except for last one)
if (i < pos_param_pairs_.size() - 1)
{
pos_param_string += String("|");
}
}
// quick sanity check
if (mod_identifier_.isNull())
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Modification or Substitution identifier MUST NOT be null or empty in MzTabModification"));
}
String res;
// only add '-' if we have position information
if (!pos_param_string.empty())
{
res = pos_param_string + "-" + mod_identifier_.toCellString();
}
else
{
res = mod_identifier_.toCellString();
}
return res;
}
}
void MzTabModification::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
if (!lower.hasSubstring("-")) // no positions? simply use s as mod identifier
{
mod_identifier_.set(String(s).trim());
}
else
{
String ss = s;
ss.trim();
std::vector<String> fields;
ss.split("-", fields);
if (fields.size() != 2)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Can't convert to MzTabModification from '") + s);
}
mod_identifier_.fromCellString(fields[1].trim());
std::vector<String> position_fields;
fields[0].split("|", position_fields);
for (Size i = 0; i != position_fields.size(); ++i)
{
Size spos = position_fields[i].find_first_of("[");
if (spos == std::string::npos) // only position information and no parameter
{
pos_param_pairs_.emplace_back(position_fields[i].toInt(), MzTabParameter());
}
else
{
// extract position part
Int pos = String(position_fields[i].begin(), position_fields[i].begin() + spos).toInt();
// extract [,,,] part
MzTabParameter param;
param.fromCellString(position_fields[i].substr(spos));
pos_param_pairs_.emplace_back(pos, param);
}
}
}
}
}
bool MzTabModificationList::isNull() const
{
return entries_.empty();
}
void MzTabModificationList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabModificationList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabModification>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += ",";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabModificationList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
if (!ss.hasSubstring("[")) // no parameters
{
ss.split(",", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabModification ms;
ms.fromCellString(fields[i]);
entries_.push_back(ms);
}
}
else
{
// example string: 3|4[a,b,,v]|8[,,"blabla, [bla]",v],1|2|3[a,b,,v]-mod:123
// we don't want to split at the , inside of [ ] MzTabParameter brackets.
// Additionally, and we don't want to recognise quoted brackets inside the MzTabParameter where they can occur in quoted text (see example string)
bool in_param_bracket = false;
bool in_quotes = false;
for (Size pos = 0; pos != ss.size(); ++pos)
{
// param_bracket state
if (ss[pos] == '[' && !in_quotes)
{
in_param_bracket = true;
continue;
}
if (ss[pos] == ']' && !in_quotes)
{
in_param_bracket = false;
continue;
}
// quote state
if (ss[pos] == '\"')
{
in_quotes = !in_quotes;
continue;
}
// comma in param bracket
if (ss[pos] == ',' && !in_quotes && in_param_bracket)
{
ss[pos] = ((char)007); // use ASCII bell as temporary separator
continue;
}
}
// now the split at comma is save
ss.split(",", fields);
for (Size i = 0; i != fields.size(); ++i)
{
fields[i].substitute(((char)007), ','); // resubstitute comma after split
MzTabModification ms;
ms.fromCellString(fields[i]);
entries_.push_back(ms);
}
}
}
}
std::vector<MzTabModification> MzTabModificationList::get() const
{
return entries_;
}
void MzTabModificationList::set(const std::vector<MzTabModification>& entries)
{
entries_ = entries;
}
MzTabProteinSectionRow::MzTabProteinSectionRow()
{
// use "," as list separator because "|" can be used for go terms and protein accessions
go_terms.setSeparator(',');
ambiguity_members.setSeparator(',');
}
MzTabMetaData::MzTabMetaData()
{
mz_tab_version.fromCellString(String("1.0.0"));
}
// static method remapping the target/decoy column from an opt_ to a standardized column
static void remapTargetDecoyPSMAndPeptideSection_(std::vector<MzTabOptionalColumnEntry>& opt_entries)
{
const String old_header("opt_global_target_decoy");
const String new_header("opt_global_cv_MS:1002217_decoy_peptide"); // for PRIDE
for (auto &opt_entry : opt_entries)
{
if (opt_entry.first == old_header || opt_entry.first == new_header)
{
opt_entry.first = new_header;
const String ¤t_value = opt_entry.second.get();
if (current_value == "target" || current_value == "target+decoy")
{
opt_entry.second = MzTabString("0");
}
else if (current_value == "decoy")
{
opt_entry.second = MzTabString("1");
}
}
}
}
// static method remapping the target/decoy column from an opt_ to a standardized column
static void remapTargetDecoyProteinSection_(std::vector<MzTabOptionalColumnEntry>& opt_entries)
{
const String old_header("opt_global_target_decoy");
const String new_header("opt_global_cv_PRIDE:0000303_decoy_hit"); // for PRIDE
for (auto &opt_entry : opt_entries)
{
if (opt_entry.first == old_header || opt_entry.first == new_header)
{
opt_entry.first = new_header;
const String ¤t_value = opt_entry.second.get();
if (current_value == "target" || current_value == "target+decoy")
{
opt_entry.second = MzTabString("0");
}
else if (current_value == "decoy")
{
opt_entry.second = MzTabString("1");
}
}
}
}
const MzTabMetaData& MzTab::getMetaData() const
{
return meta_data_;
}
void MzTab::setMetaData(const MzTabMetaData& md)
{
meta_data_ = md;
}
MzTabProteinSectionRows& MzTab::getProteinSectionRows()
{
return protein_data_;
}
const MzTabProteinSectionRows& MzTab::getProteinSectionRows() const
{
return protein_data_;
}
void MzTab::setProteinSectionRows(const MzTabProteinSectionRows& psd)
{
protein_data_ = psd;
}
MzTabPeptideSectionRows& MzTab::getPeptideSectionRows()
{
return peptide_data_;
}
const MzTabPeptideSectionRows& MzTab::getPeptideSectionRows() const
{
return peptide_data_;
}
void MzTab::setPeptideSectionRows(const MzTabPeptideSectionRows& psd)
{
peptide_data_ = psd;
}
const MzTabPSMSectionRows& MzTab::getPSMSectionRows() const
{
return psm_data_;
}
MzTabPSMSectionRows& MzTab::getPSMSectionRows()
{
return psm_data_;
}
size_t MzTab::getNumberOfPSMs() const
{
std::unordered_set<Int> psm_ids;
for (const auto& psm : psm_data_)
{
psm_ids.insert(psm.PSM_ID.get());
}
return psm_ids.size();
}
void MzTab::setPSMSectionRows(const MzTabPSMSectionRows& psd)
{
psm_data_ = psd;
}
const MzTabSmallMoleculeSectionRows& MzTab::getSmallMoleculeSectionRows() const
{
return small_molecule_data_;
}
void MzTab::setSmallMoleculeSectionRows(const MzTabSmallMoleculeSectionRows& smsd)
{
small_molecule_data_ = smsd;
}
const MzTabNucleicAcidSectionRows& MzTab::getNucleicAcidSectionRows() const
{
return nucleic_acid_data_;
}
void MzTab::setNucleicAcidSectionRows(const MzTabNucleicAcidSectionRows& nasd)
{
nucleic_acid_data_ = nasd;
}
const MzTabOligonucleotideSectionRows& MzTab::getOligonucleotideSectionRows() const
{
return oligonucleotide_data_;
}
void MzTab::setOligonucleotideSectionRows(const MzTabOligonucleotideSectionRows& onsd)
{
oligonucleotide_data_ = onsd;
}
const MzTabOSMSectionRows& MzTab::getOSMSectionRows() const
{
return osm_data_;
}
void MzTab::setOSMSectionRows(const MzTabOSMSectionRows& osd)
{
osm_data_ = osd;
}
void MzTab::setCommentRows(const std::map<Size, String>& com)
{
comment_rows_ = com;
}
void MzTab::setEmptyRows(const std::vector<Size>& empty)
{
empty_rows_ = empty;
}
const std::vector<Size>& MzTab::getEmptyRows() const
{
return empty_rows_;
}
const std::map<Size, String>& MzTab::getCommentRows() const
{
return comment_rows_;
}
std::vector<String> MzTab::getProteinOptionalColumnNames() const
{
return getOptionalColumnNames_(protein_data_);
}
std::vector<String> MzTab::getPeptideOptionalColumnNames() const
{
return getOptionalColumnNames_(peptide_data_);
}
std::vector<String> MzTab::getPSMOptionalColumnNames() const
{
return getOptionalColumnNames_(psm_data_);
}
std::vector<String> MzTab::getSmallMoleculeOptionalColumnNames() const
{
return getOptionalColumnNames_(small_molecule_data_);
}
std::vector<String> MzTab::getNucleicAcidOptionalColumnNames() const
{
return getOptionalColumnNames_(nucleic_acid_data_);
}
std::vector<String> MzTab::getOligonucleotideOptionalColumnNames() const
{
return getOptionalColumnNames_(oligonucleotide_data_);
}
std::vector<String> MzTab::getOSMOptionalColumnNames() const
{
return getOptionalColumnNames_(osm_data_);
}
void MzTabPSMSectionRow::addPepEvidenceToRows(const vector<PeptideEvidence>& peptide_evidences)
{
if (peptide_evidences.empty())
{
// report without pep evidence information
pre = MzTabString();
post = MzTabString();
start = MzTabString();
end = MzTabString();
return;
}
String pre, post, start, end, accession;
for (Size i = 0; i != peptide_evidences.size(); ++i)
{
// get AABefore and AAAfter as well as start and end for all pep evidences
// pre/post
// from spec: Amino acid preceding the peptide (coming from the PSM) in the protein
// sequence. If unknown “null” MUST be used, if the peptide is N-terminal “-“
// MUST be used.
if (peptide_evidences[i].getAABefore() == PeptideEvidence::UNKNOWN_AA)
{
pre += "null";
}
else if (peptide_evidences[i].getAABefore() == PeptideEvidence::N_TERMINAL_AA)
{
pre += "-";
}
else
{
pre += String(peptide_evidences[i].getAABefore());
}
if (peptide_evidences[i].getAAAfter() == PeptideEvidence::UNKNOWN_AA)
{
post += "null";
}
else if (peptide_evidences[i].getAAAfter() == PeptideEvidence::C_TERMINAL_AA)
{
post += "-";
}
else
{
post += String(peptide_evidences[i].getAAAfter());
}
// start/end
if (peptide_evidences[i].getStart() == PeptideEvidence::UNKNOWN_POSITION)
{
start += "null";
}
else
{
start += String(peptide_evidences[i].getStart() + 1); // counting in mzTab starts at 1
}
if (peptide_evidences[i].getEnd() == PeptideEvidence::UNKNOWN_POSITION)
{
end += "null";
}
else
{
end += String(peptide_evidences[i].getEnd() + 1); // counting in mzTab starts at 1
}
accession += peptide_evidences[i].getProteinAccession();
if (i < peptide_evidences.size() - 1) { pre += ','; post += ','; start += ','; end += ','; accession += ',';}
}
this->pre = MzTabString(pre);
this->post = MzTabString(post);
this->start = MzTabString(start);
this->end = MzTabString(end);
this->accession = MzTabString(accession);
}
void MzTab::addMetaInfoToOptionalColumns(
const set<String>& keys,
vector<MzTabOptionalColumnEntry>& opt,
const String& id,
const MetaInfoInterface& meta)
{
for (String const & key : keys)
{
MzTabOptionalColumnEntry opt_entry;
// column names must not contain spaces
opt_entry.first = "opt_" + id + "_" + String(key).substitute(' ','_');
if (meta.metaValueExists(key))
{
opt_entry.second = MzTabString(meta.getMetaValue(key).toString());
} // otherwise it is default ("null")
opt.push_back(opt_entry);
}
}
map<Size, MzTabModificationMetaData> MzTab::generateMzTabStringFromModifications(const vector<String>& mods)
{
map<Size, MzTabModificationMetaData> mods_mztab;
Size index(1);
for (String const & s : mods)
{
MzTabModificationMetaData mod;
MzTabParameter mp;
ModificationsDB* mod_db = ModificationsDB::getInstance();
String unimod_accession;
try
{
const ResidueModification* m = mod_db->getModification(s);
unimod_accession = m->getUniModAccession();
if (!unimod_accession.empty())
{
// MzTab standard is to report Unimod accession.
mp.setCVLabel("UNIMOD");
mp.setAccession(unimod_accession.toUpper());
}
mp.setName(m->getId());
mod.modification = mp;
if (m->getTermSpecificity() == ResidueModification::C_TERM)
{
mod.position = MzTabString("Any C-term");
}
else if (m->getTermSpecificity() == ResidueModification::N_TERM)
{
mod.position = MzTabString("Any N-term");
}
else if (m->getTermSpecificity() == ResidueModification::ANYWHERE)
{
mod.position = MzTabString("Anywhere");
}
else if (m->getTermSpecificity() == ResidueModification::PROTEIN_C_TERM)
{
mod.position = MzTabString("Protein C-term");
}
else if (m->getTermSpecificity() == ResidueModification::PROTEIN_N_TERM)
{
mod.position = MzTabString("Protein N-term");
}
mod.site = MzTabString(String(m->getOrigin()));
mods_mztab[index] = mod;
}
catch(...)
{
OPENMS_LOG_WARN << "Skipping unknown residue modification: '" + s + "'" << endl;
}
++index;
}
return mods_mztab;
}
map<Size, MzTabModificationMetaData> MzTab::generateMzTabStringFromVariableModifications(const vector<String>& mods)
{
if (mods.empty())
{
map<Size, MzTabModificationMetaData> mods_mztab;
MzTabModificationMetaData mod_mtd;
mod_mtd.modification.fromCellString("[MS, MS:1002454, No variable modifications searched, ]");
mods_mztab.insert(make_pair(1, mod_mtd));
return mods_mztab;
}
else
{
return generateMzTabStringFromModifications(mods);
}
}
map<Size, MzTabModificationMetaData> MzTab::generateMzTabStringFromFixedModifications(const vector<String>& mods)
{
if (mods.empty())
{
map<Size, MzTabModificationMetaData> mods_mztab;
MzTabModificationMetaData mod_mtd;
mod_mtd.modification.fromCellString("[MS, MS:1002453, No fixed modifications searched, ]");
mods_mztab.insert(make_pair(1, mod_mtd));
return mods_mztab;
}
else
{
return generateMzTabStringFromModifications(mods);
}
}
MzTab MzTab::exportFeatureMapToMzTab(
const FeatureMap & feature_map,
const String & filename)
{
OPENMS_LOG_INFO << "exporting feature map: \"" << filename << "\" to mzTab: " << std::endl;
MzTab mztab;
MzTabMetaData meta_data;
const vector<ProteinIdentification> &prot_ids = feature_map.getProteinIdentifications();
vector<String> var_mods, fixed_mods;
MzTabString db, db_version;
if (!prot_ids.empty())
{
const ProteinIdentification::SearchParameters &sp = prot_ids[0].getSearchParameters();
var_mods = sp.variable_modifications;
fixed_mods = sp.fixed_modifications;
db = sp.db.empty() ? MzTabString() : MzTabString(sp.db);
db_version = sp.db_version.empty() ? MzTabString() : MzTabString(sp.db_version);
}
meta_data.variable_mod = generateMzTabStringFromVariableModifications(var_mods);
meta_data.fixed_mod = generateMzTabStringFromFixedModifications(fixed_mods);
// mandatory meta values
meta_data.mz_tab_type = MzTabString("Quantification");
meta_data.mz_tab_mode = MzTabString("Summary");
meta_data.description = MzTabString("OpenMS export from featureXML");
MzTabMSRunMetaData ms_run;
StringList spectra_data;
feature_map.getPrimaryMSRunPath(spectra_data);
if (!spectra_data.empty())
{
// prepend file:// if not there yet
String m = spectra_data[0];
if (!m.hasPrefix("file://")) {m = String("file://") + m; }
ms_run.location = MzTabString(m);
}
else
{
ms_run.location = MzTabString();
}
meta_data.ms_run[1] = ms_run;
meta_data.uri[1] = MzTabString(filename);
meta_data.psm_search_engine_score[1] = MzTabParameter(); // TODO: we currently only support psm search engine scores annotated to the identification run
meta_data.peptide_search_engine_score[1] = MzTabParameter();
mztab.setMetaData(meta_data);
// pre-analyze data for occurring meta values at feature and peptide hit level
// these are used to build optional columns containing the meta values in internal data structures
set<String> feature_user_value_keys;
set<String> peptide_identifications_user_value_keys;
set<String> peptide_hit_user_value_keys;
MzTab::getFeatureMapMetaValues_(
feature_map,
feature_user_value_keys,
peptide_identifications_user_value_keys,
peptide_hit_user_value_keys);
for (Size i = 0; i < feature_map.size(); ++i)
{
const Feature& f = feature_map[i];
auto row = peptideSectionRowFromFeature_(
f,
feature_user_value_keys,
peptide_identifications_user_value_keys,
peptide_hit_user_value_keys,
fixed_mods);
mztab.getPeptideSectionRows().emplace_back(std::move(row));
}
return mztab;
}
MzTabPeptideSectionRow MzTab::peptideSectionRowFromFeature_(
const Feature& f,
const set<String>& feature_user_value_keys,
const set<String>& peptide_identifications_user_value_keys,
const set<String>& peptide_hit_user_value_keys,
const vector<String>& fixed_mods)
{
MzTabPeptideSectionRow row;
row.mass_to_charge = MzTabDouble(f.getMZ());
MzTabDoubleList rt_list;
vector<MzTabDouble> rts;
rts.emplace_back(f.getRT());
rt_list.set(rts);
row.retention_time = rt_list;
// set rt window if a bounding box has been set
vector<MzTabDouble> window;
if (f.getConvexHull().getBoundingBox() != DBoundingBox<2>())
{
window.emplace_back(f.getConvexHull().getBoundingBox().minX());
window.emplace_back(f.getConvexHull().getBoundingBox().maxX());
}
MzTabDoubleList rt_window;
rt_window.set(window);
row.retention_time_window = rt_window;
row.charge = MzTabInteger(f.getCharge());
row.peptide_abundance_stdev_study_variable[1];
row.peptide_abundance_std_error_study_variable[1];
row.peptide_abundance_study_variable[1] = MzTabDouble(f.getIntensity());
row.best_search_engine_score[1] = MzTabDouble();
row.search_engine_score_ms_run[1][1] = MzTabDouble();
// create opt_ column for peptide sequence containing modification
MzTabOptionalColumnEntry opt_global_modified_sequence;
opt_global_modified_sequence.first = "opt_global_cv_MS:1000889_peptidoform_sequence";
row.opt_.push_back(opt_global_modified_sequence);
// create and fill opt_ columns for feature (peptide) user values
addMetaInfoToOptionalColumns(feature_user_value_keys, row.opt_, String("global"), f);
const PeptideIdentificationList& pep_ids = f.getPeptideIdentifications();
if (pep_ids.empty())
{
// still add empty opt_ columns before returning
addMetaInfoToOptionalColumns(peptide_identifications_user_value_keys, row.opt_, "global", MetaInfoInterface());
addMetaInfoToOptionalColumns(peptide_hit_user_value_keys, row.opt_, "global", MetaInfoInterface());
return row;
}
const PeptideIdentification& best_pid = f.getPeptideIdentifications()[0];
addMetaInfoToOptionalColumns(peptide_identifications_user_value_keys, row.opt_, "global", best_pid);
// TODO: here we assume that all have the same score type etc.
vector<PeptideHit> all_hits;
for (const PeptideIdentification& it : pep_ids)
{
all_hits.insert(all_hits.end(), it.getHits().begin(), it.getHits().end());
}
if (all_hits.empty())
{
addMetaInfoToOptionalColumns(peptide_identifications_user_value_keys, row.opt_, "global", MetaInfoInterface());
return row;
}
// create new peptide id object to assist in sorting
PeptideIdentification new_pep_id = pep_ids[0];
new_pep_id.setHits(all_hits);
new_pep_id.sort();
const PeptideHit& best_ph = new_pep_id.getHits()[0];
const AASequence& aas = best_ph.getSequence();
row.sequence = MzTabString(aas.toUnmodifiedString());
row.modifications = extractModificationList(best_ph, fixed_mods, vector<String>());
const set<String>& accessions = best_ph.extractProteinAccessionsSet();
const vector<PeptideEvidence>& peptide_evidences = best_ph.getPeptideEvidences();
row.unique = accessions.size() == 1 ? MzTabBoolean(true) : MzTabBoolean(false);
// select accession of first peptide_evidence as representative ("leading") accession
row.accession = peptide_evidences.empty() ? MzTabString() : MzTabString(peptide_evidences[0].getProteinAccession());
row.best_search_engine_score[1] = MzTabDouble(best_ph.getScore());
row.search_engine_score_ms_run[1][1] = MzTabDouble(best_ph.getScore());
// find opt_global_modified_sequence in opt_ and set it to the OpenMS amino acid string (easier human readable than unimod accessions)
for (Size j = 0; j != row.opt_.size(); ++j)
{
MzTabOptionalColumnEntry& opt_entry = row.opt_[j];
if (opt_entry.first == "opt_global_cv_MS:1000889_peptidoform_sequence")
{
opt_entry.second = MzTabString(aas.toString());
}
}
// create and fill opt_ columns for psm (PeptideHit) user values
addMetaInfoToOptionalColumns(peptide_hit_user_value_keys, row.opt_, String("global"), best_ph);
// remap the target/decoy column
remapTargetDecoyPSMAndPeptideSection_(row.opt_);
return row;
}
MzTabPeptideSectionRow MzTab::peptideSectionRowFromConsensusFeature_(
const ConsensusFeature& c,
const ConsensusMap& consensus_map,
const StringList& ms_runs,
const Size n_study_variables,
const set<String>& consensus_feature_user_value_keys,
const set<String>& peptide_identifications_user_value_keys,
const set<String>& peptide_hit_user_value_keys,
const map<String, size_t>& idrun_2_run_index,
const map<pair<size_t,size_t>,size_t>& map_run_fileidx_2_msfileidx,
const std::map< std::pair< String, unsigned >, unsigned>& path_label_to_assay,
const vector<String>& fixed_mods,
bool export_subfeatures)
{
MzTabPeptideSectionRow row;
const ConsensusMap::ColumnHeaders& cm_column_headers = consensus_map.getColumnHeaders();
const String & experiment_type = consensus_map.getExperimentType();
const vector<ProteinIdentification>& prot_id = consensus_map.getProteinIdentifications();
// create opt_ column for peptide sequence containing modification
MzTabOptionalColumnEntry opt_global_modified_sequence;
opt_global_modified_sequence.first = "opt_global_cv_MS:1000889_peptidoform_sequence";
row.opt_.push_back(opt_global_modified_sequence);
// Defines how to consume user value keys for the upcoming keys
const auto addUserValueToRowBy = [&row](const function<void(const String &s, MzTabOptionalColumnEntry &entry)>& f) -> function<void(const String &key)>
{
return [f,&row](const String &user_value_key)
{
MzTabOptionalColumnEntry opt_entry;
opt_entry.first = "opt_global_" + user_value_key;
f(user_value_key, opt_entry);
// Use default column_header for target decoy
row.opt_.push_back(opt_entry);
};
};
// create opt_ columns for consensus map user values
for_each(consensus_feature_user_value_keys.begin(), consensus_feature_user_value_keys.end(),
addUserValueToRowBy([&c](const String &key, MzTabOptionalColumnEntry &opt_entry)
{
if (c.metaValueExists(key))
{
opt_entry.second = MzTabString(c.getMetaValue(key).toString());
}
})
);
// add optional columns for first peptide identification in consensus feature
for_each(peptide_identifications_user_value_keys.begin(), peptide_identifications_user_value_keys.end(),
addUserValueToRowBy([&c](const String &key, MzTabOptionalColumnEntry &opt_entry)
{
opt_entry.second = MzTabString(c.getMetaValue(key).toString());
})
);
// create opt_ columns for psm (PeptideHit) user values
for_each(peptide_hit_user_value_keys.begin(), peptide_hit_user_value_keys.end(),
addUserValueToRowBy([](const String&, MzTabOptionalColumnEntry&){}));
row.mass_to_charge = MzTabDouble(c.getMZ());
MzTabDoubleList rt_list;
vector<MzTabDouble> rts;
rts.emplace_back(c.getRT());
rt_list.set(rts);
row.retention_time = rt_list;
MzTabDoubleList rt_window;
row.retention_time_window = rt_window;
row.charge = MzTabInteger(c.getCharge());
row.best_search_engine_score[1] = MzTabDouble();
// initialize columns
OPENMS_LOG_DEBUG << "Initializing study variables:" << n_study_variables << endl;
for (Size study_variable = 1; study_variable <= n_study_variables; ++study_variable)
{
row.peptide_abundance_stdev_study_variable[study_variable] = MzTabDouble();
row.peptide_abundance_std_error_study_variable[study_variable] = MzTabDouble();
row.peptide_abundance_study_variable[study_variable] = MzTabDouble();
}
for (Size ms_run = 1; ms_run <= ms_runs.size(); ++ms_run)
{
row.search_engine_score_ms_run[1][ms_run] = MzTabDouble();
}
ConsensusFeature::HandleSetType fs = c.getFeatures();
for (auto fit = fs.begin(); fit != fs.end(); ++fit)
{
UInt study_variable{1};
const int index = fit->getMapIndex();
const ConsensusMap::ColumnHeader& ch = cm_column_headers.at(index);
UInt label = ch.getLabelAsUInt(experiment_type);
// convert from column index to study variable index
auto pl = make_pair(ch.filename, label);
study_variable = path_label_to_assay.at(pl) + 1; // for now, a study_variable is one assay (both 1-based). And pathLabelToSample mapping reports 0-based.
//TODO implement aggregation in case we generalize study_variable to include multiple assays.
row.peptide_abundance_stdev_study_variable[study_variable];
row.peptide_abundance_std_error_study_variable[study_variable];
row.peptide_abundance_study_variable[study_variable] = MzTabDouble(fit->getIntensity());
if (export_subfeatures)
{
MzTabOptionalColumnEntry opt_global_mass_to_charge_study_variable;
opt_global_mass_to_charge_study_variable.first = "opt_global_mass_to_charge_study_variable[" + String(study_variable) + "]";
opt_global_mass_to_charge_study_variable.second = MzTabString(String(fit->getMZ()));
row.opt_.push_back(opt_global_mass_to_charge_study_variable);
MzTabOptionalColumnEntry opt_global_retention_time_study_variable;
opt_global_retention_time_study_variable.first = "opt_global_retention_time_study_variable[" + String(study_variable) + "]";
opt_global_retention_time_study_variable.second = MzTabString(String(fit->getRT()));
row.opt_.push_back(opt_global_retention_time_study_variable);
}
}
const PeptideIdentificationList& curr_pep_ids = c.getPeptideIdentifications();
if (!curr_pep_ids.empty())
{
checkSequenceUniqueness_(curr_pep_ids);
// Overall information for this feature in PEP section
// Features need to be resolved for this. First is not necessarily the best since ids were resorted by map_index.
const PeptideIdentification& best_id = curr_pep_ids[0];
const PeptideHit& best_ph = best_id.getHits()[0];
const AASequence& aas = best_ph.getSequence();
row.sequence = MzTabString(aas.toUnmodifiedString());
// annotate variable modifications (no fixed ones)
row.modifications = extractModificationList(best_ph, fixed_mods, vector<String>());
const set<String>& accessions = best_ph.extractProteinAccessionsSet();
const vector<PeptideEvidence> &peptide_evidences = best_ph.getPeptideEvidences();
row.unique = accessions.size() == 1 ? MzTabBoolean(true) : MzTabBoolean(false);
// select accession of first peptide_evidence as representative ("leading") accession
row.accession = peptide_evidences.empty() ? MzTabString() : MzTabString(peptide_evidences[0].getProteinAccession());
// fill opt_ columns based on best ID in the feature
vector<String> id_keys;
best_id.getKeys(id_keys);
for (Size k = 0; k != id_keys.size(); ++k)
{
String mztabstyle_key = id_keys[k];
std::replace(mztabstyle_key.begin(), mztabstyle_key.end(), ' ', '_');
// find matching entry in opt_ (TODO: speed this up)
for (Size i = 0; i != row.opt_.size(); ++i)
{
MzTabOptionalColumnEntry& opt_entry = row.opt_[i];
if (opt_entry.first == String("opt_global_") + mztabstyle_key)
{
opt_entry.second = MzTabString(best_id.getMetaValue(id_keys[k]).toString());
}
}
}
// find opt_global_modified_sequence in opt_ and set it to the OpenMS amino acid string (easier human readable than unimod accessions)
for (Size i = 0; i != row.opt_.size(); ++i)
{
MzTabOptionalColumnEntry& opt_entry = row.opt_[i];
if (opt_entry.first == "opt_global_cv_MS:1000889_peptidoform_sequence")
{
opt_entry.second = MzTabString(aas.toString());
}
}
// fill opt_ column of psm
vector<String> ph_keys;
best_ph.getKeys(ph_keys);
for (Size k = 0; k != ph_keys.size(); ++k)
{
String mztabstyle_key = ph_keys[k];
std::replace(mztabstyle_key.begin(), mztabstyle_key.end(), ' ', '_');
// find matching entry in opt_ (TODO: speed this up)
for (Size i = 0; i != row.opt_.size(); ++i)
{
MzTabOptionalColumnEntry& opt_entry = row.opt_[i];
if (opt_entry.first == String("opt_global_") + mztabstyle_key)
{
opt_entry.second = MzTabString(best_ph.getMetaValue(ph_keys[k]).toString());
}
}
}
// get msrun indices for each ID and insert best search_engine_score for this run
// for the best run we also annotate the spectra_ref (since it is not designed to be a list)
double best_score = best_ph.getScore();
for (const auto& pep : curr_pep_ids)
{
size_t spec_run_index = idrun_2_run_index.at(pep.getIdentifier());
StringList filenames;
prot_id[spec_run_index].getPrimaryMSRunPath(filenames);
size_t msfile_index(0);
size_t id_merge_index(0);
//TODO synchronize information from ID structures and quant structures somehow.
// e.g. this part of the code now parses the ID information.
// This is done because in IsobaricLabelling there is only one ID Run for the different labels
if (filenames.size() <= 1) //either none or only one file for this run
{
msfile_index = map_run_fileidx_2_msfileidx.at({spec_run_index, 0});
}
else
{
if (pep.metaValueExists(Constants::UserParam::ID_MERGE_INDEX))
{
id_merge_index = pep.getMetaValue(Constants::UserParam::ID_MERGE_INDEX);
msfile_index = map_run_fileidx_2_msfileidx.at({spec_run_index, id_merge_index});
}
else
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Multiple files in a run, but no id_merge_index in PeptideIdentification found.");
}
}
double curr_score = pep.getHits()[0].getScore();
auto sit = row.search_engine_score_ms_run[1].find(msfile_index);
if (sit == row.search_engine_score_ms_run[1].end())
{
String ref = "";
if (pep.metaValueExists("spectrum_reference"))
{
ref = pep.getMetaValue("spectrum_reference");
}
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"PSM " + ref + " does not map to an MS file registered in the quantitative metadata. "
"Check your merging and filtering steps and/or report the issue, please.");
}
sit->second = MzTabDouble(curr_score);
//TODO assumes same scores & score types
if ((pep.isHigherScoreBetter() && curr_score >= best_score)
|| (!pep.isHigherScoreBetter() && curr_score <= best_score))
{
best_score = curr_score;
if (pep.metaValueExists("spectrum_reference"))
{
row.spectra_ref.setSpecRef(pep.getSpectrumReference());
row.spectra_ref.setMSFile(msfile_index);
}
}
}
row.best_search_engine_score[1] = MzTabDouble(best_score);
}
remapTargetDecoyPSMAndPeptideSection_(row.opt_);
return row;
}
std::optional<MzTabPSMSectionRow> MzTab::PSMSectionRowFromPeptideID_(
const PeptideIdentification& pid,
const vector<const ProteinIdentification*>& prot_ids,
map<String, size_t>& idrun_2_run_index,
map<pair<size_t,size_t>,size_t>& map_run_fileidx_2_msfileidx,
map<Size, vector<pair<String, String>>>& run_to_search_engines,
const Size current_psm_idx,
const Size psm_id,
const MzTabString& db,
const MzTabString& db_version,
const bool export_empty_pep_ids,
const bool export_all_psms)
{
// skip empty peptide identification objects, if they are not wanted
if (pid.getHits().empty() && !export_empty_pep_ids)
{
return std::nullopt;
}
/////// Information that doesn't require a peptide hit ///////
MzTabPSMSectionRow row;
row.PSM_ID = MzTabInteger(int(psm_id));
row.database = db;
row.database_version = db_version;
vector<MzTabDouble> rts_vector;
rts_vector.emplace_back(pid.getRT());
MzTabDoubleList rts;
rts.set(rts_vector);
row.retention_time = rts;
row.exp_mass_to_charge = MzTabDouble(pid.getMZ());
// meta data on peptide identifications
vector<String> pid_keys;
pid.getKeys(pid_keys);
set<String> pid_key_set(pid_keys.begin(), pid_keys.end());
// remove key that only exists for backwards compatibility (will likely be deprecated in the future)
pid_key_set.erase(Constants::UserParam::SIGNIFICANCE_THRESHOLD);
addMetaInfoToOptionalColumns(pid_key_set, row.opt_, String("global"), pid);
// link to spectrum in MS run
String spectrum_nativeID = pid.getSpectrumReference();
size_t run_index = idrun_2_run_index.at(pid.getIdentifier());
StringList filenames;
prot_ids[run_index]->getPrimaryMSRunPath(filenames);
StringList localization_mods;
if (prot_ids[run_index]->getSearchParameters().metaValueExists(Constants::UserParam::LOCALIZED_MODIFICATIONS_USERPARAM))
{
localization_mods = prot_ids[run_index]->getSearchParameters().getMetaValue(Constants::UserParam::LOCALIZED_MODIFICATIONS_USERPARAM);
}
size_t msfile_index(0);
if (filenames.size() <= 1) //either none or only one file for this run
{
msfile_index = map_run_fileidx_2_msfileidx[{run_index, 0}];
}
else
{
if (pid.metaValueExists(Constants::UserParam::ID_MERGE_INDEX))
{
msfile_index = map_run_fileidx_2_msfileidx[{run_index, pid.getMetaValue(Constants::UserParam::ID_MERGE_INDEX)}];
}
else
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Multiple files in a run, but no id_merge_index in PeptideIdentification found.");
}
}
MzTabSpectraRef spec_ref;
row.spectra_ref.setMSFile(msfile_index);
if (spectrum_nativeID.empty())
{
OPENMS_LOG_WARN << "spectrum_reference not set in ID with precursor (RT, m/z) " << pid.getRT() << ", " << pid.getMZ() << endl;
}
else
{
row.spectra_ref.setSpecRef(spectrum_nativeID);
}
const vector<PeptideHit>& phs = pid.getHits();
// add the row and continue to next PepID, if the current one was an empty one
if (phs.empty())
{
return row;
}
/////// Information that does require a peptide hit ///////
PeptideHit current_ph;
if (!export_all_psms)
{
// only consider best peptide hit for export
PeptideIdentificationList dummy;
dummy.push_back(pid);
IDFilter::getBestHit<PeptideIdentification>(dummy.getData(), false, current_ph); // TODO: add getBestHit for PeptideHits so no copying to dummy is needed
}
else
{
current_ph = phs.at(current_psm_idx);
}
const AASequence& aas = current_ph.getSequence();
row.sequence = MzTabString(aas.toUnmodifiedString());
// extract all modifications in the current sequence for reporting.
// In contrast to peptide and protein section where fixed modifications are not reported we now report all modifications.
// If localization mods are specified we add localization scores
row.modifications = extractModificationList(current_ph, vector<String>(), localization_mods);
MzTabParameterList search_engines;
//TODO support columns for multiple search engines/scores
pair<String, String> name_version = *run_to_search_engines[run_index].begin();
search_engines.fromCellString("[,," + name_version.first + "," + name_version.second + "]");
row.search_engine = search_engines;
row.search_engine_score[1] = MzTabDouble(current_ph.getScore());
row.charge = MzTabInteger(current_ph.getCharge());
row.calc_mass_to_charge = current_ph.getCharge() != 0 ? MzTabDouble(aas.getMZ(current_ph.getCharge())) : MzTabDouble();
// add opt_global_modified_sequence in opt_ and set it to the OpenMS amino acid string (easier human readable than unimod accessions)
MzTabOptionalColumnEntry opt_entry;
opt_entry.first = "opt_global_cv_MS:1000889_peptidoform_sequence";
opt_entry.second = MzTabString(aas.toString());
row.opt_.push_back(opt_entry);
// meta data on PSMs
vector<String> ph_keys;
current_ph.getKeys(ph_keys);
set<String> ph_key_set(ph_keys.begin(), ph_keys.end());
addMetaInfoToOptionalColumns(ph_key_set, row.opt_, String("global"), current_ph);
// TODO Think about if the uniqueness can be determined by # of peptide evidences
// b/c this would only differ when evidences come from different DBs
// TODO This also does not consider protein groups but this might be fine here
const set<String>& accessions = current_ph.extractProteinAccessionsSet();
row.unique = accessions.size() == 1 ? MzTabBoolean(true) : MzTabBoolean(false);
// create row for every PeptideEvidence entry (mapping to a protein)
const vector<PeptideEvidence>& peptide_evidences = current_ph.getPeptideEvidences();
// add peptide evidences to Rows
row.addPepEvidenceToRows(peptide_evidences);
// remap target/decoy column
remapTargetDecoyPSMAndPeptideSection_(row.opt_);
return row;
}
size_t MzTab::getQuantStudyVariables_(const ProteinIdentification& pid)
{
size_t quant_study_variables(0);
for (auto & p : pid.getIndistinguishableProteins())
{
if (p.getFloatDataArrays().empty()
|| p.getFloatDataArrays()[0].getName() != "abundances")
{
quant_study_variables = 0;
break;
}
quant_study_variables = p.getFloatDataArrays()[0].size();
}
return quant_study_variables;
}
MzTabParameter MzTab::getProteinScoreType_(const ProteinIdentification& prot_id)
{
MzTabParameter protein_score_type;
bool has_inference_data = prot_id.hasInferenceData();
if (has_inference_data)
{
protein_score_type.fromCellString("[,," + prot_id.getInferenceEngine() + " " + prot_id.getScoreType()
+ ",]"); // TODO: check if we need one for every run (should not be redundant!)
}
else
{
// if there was no inference all proteins just come from PeptideIndexer which kind of does a one-peptide rule
// TODO actually: where are scores coming from in this case. Better to just not write any proteins IMHO
protein_score_type.fromCellString("[,,one-peptide-rule " + prot_id.getScoreType() + ",]");
}
return protein_score_type;
}
void MzTab::mapIDRunFileIndex2MSFileIndex_(
const vector<const ProteinIdentification*>& prot_ids,
const map<String, size_t>& msfilename_2_msrunindex,
bool skip_first_run,
std::map<std::pair<size_t,size_t>,size_t>& map_run_fileidx_2_msfileidx)
{
//TODO the following assumes that every file occurs max. once in all runs
size_t run_index(0);
for (const auto& run : prot_ids)
{
// First entry might be the inference result without (single) associated ms_run. We skip it.
if (skip_first_run && run_index == 0)
{
++run_index;
continue;
}
StringList files;
run->getPrimaryMSRunPath(files);
if (!files.empty())
{
size_t file_index(0);
for (const String& file : files)
{
map_run_fileidx_2_msfileidx[{run_index,file_index}] = msfilename_2_msrunindex.at(file);
file_index++;
}
}
else
{
OPENMS_LOG_WARN << "No MS file associated (primary MS run path)." << endl;
map_run_fileidx_2_msfileidx[{run_index,0}] = run_index;
}
++run_index;
}
}
void MzTab::mapBetweenRunAndSearchEngines_(
const vector<const ProteinIdentification*>& prot_ids,
const vector<const PeptideIdentification*>& pep_ids,
bool skip_first_run,
map<tuple<String, String, String>, set<Size>>& search_engine_to_runs,
map<Size, vector<pair<String, String>>>& run_to_search_engines,
map<Size, vector<vector<pair<String, String>>>>& run_to_search_engine_settings,
map<String, vector<pair<String, String>>>& search_engine_to_settings)
{
size_t run_index(0);
for (auto it = prot_ids.cbegin(); it != prot_ids.cend(); ++it)
{
// First entry might be the inference result without (single) associated ms_run. We skip it.
if (skip_first_run && it == prot_ids.cbegin())
{
run_index++;
continue;
}
const String &search_engine_name = prot_ids[run_index]->getSearchEngine();
const String &search_engine_version = prot_ids[run_index]->getSearchEngineVersion();
String search_engine_score_type = "unknown_score";
// this is very inefficient.. but almost the only way
for (const auto& pep : pep_ids)
{
if (pep->getIdentifier() == (*it)->getIdentifier())
{
search_engine_score_type = pep->getScoreType();
break;
}
}
search_engine_to_runs[make_tuple(search_engine_name, search_engine_version, search_engine_score_type)].insert(run_index);
// store main search engine as first entry in run_to_search_engines
run_to_search_engines[run_index].push_back(make_pair(search_engine_name, search_engine_version));
vector<String> mvkeys;
const ProteinIdentification::SearchParameters& sp2 = prot_ids[run_index]->getSearchParameters();
sp2.getKeys(mvkeys);
for (const String & mvkey : mvkeys)
{
// this is how search engines get overwritten by PercolatorAdapter or ConsensusID
if (mvkey.hasPrefix("SE:"))
{
String se_name = mvkey.substr(3);
String se_ver = sp2.getMetaValue(mvkey);
run_to_search_engines[run_index].emplace_back(se_name, se_ver);
// TODO conserve score_type of underlying search engines (currently always "")
// TODO for now we only save the MAIN search engine in the SE_to_runs, to only have
// those in the meta_data later. -> No discrepancy with the rows (where we also only use
// the main search engine
//search_engine_to_runs[make_tuple(se_name, se_ver, "")].insert(run_index);
}
}
for (const auto& run_se_ver : run_to_search_engines[run_index])
{
const auto& se_setting_pairs = prot_ids[run_index]->getSearchEngineSettingsAsPairs(run_se_ver.first);
// we currently only record the first occurring settings for each search engine.
search_engine_to_settings.emplace(run_se_ver.first, se_setting_pairs);
auto it_inserted = run_to_search_engine_settings.emplace(run_index, vector<vector<pair<String, String>>>{se_setting_pairs});
if (!it_inserted.second)
{
it_inserted.first->second.emplace_back(se_setting_pairs);
}
}
++run_index;
}
}
// static
MzTabString MzTab::getModificationIdentifier_(const ResidueModification& r)
{
String unimod = r.getUniModAccession();
unimod.toUpper();
if (!unimod.empty())
{
return MzTabString(unimod);
}
else
{
MzTabString non_unimod_accession = MzTabString("CHEMMOD:" + String(r.getDiffMonoMass()));
return non_unimod_accession;
}
}
MzTabProteinSectionRow MzTab::proteinSectionRowFromProteinHit_(
const ProteinHit& hit,
const MzTabString& db,
const MzTabString& db_version,
const set<String>& protein_hit_user_value_keys)
{
MzTabProteinSectionRow protein_row;
protein_row.accession = MzTabString(hit.getAccession());
protein_row.description = MzTabString(hit.getDescription());
// protein_row.taxid = hit.getTaxonomyID(); // TODO maybe add as meta value to protein hit NEWT taxonomy for the species.
// MzTabString species = hit.getSpecies(); // Human readable name of the species
protein_row.database = db; // Name of the protein database.
protein_row.database_version = db_version; // String Version of the protein database.
protein_row.best_search_engine_score[1] = MzTabDouble(hit.getScore());
// MzTabParameterList search_engine; // Search engine(s) identifying the protein.
// std::map<Size, MzTabDouble> best_search_engine_score; // best_search_engine_score[1-n]
// std::map<Size, std::map<Size, MzTabDouble> > search_engine_score_ms_run; // search_engine_score[index1]_ms_run[index2]
// MzTabInteger reliability;
// std::map<Size, MzTabInteger> num_psms_ms_run;
// std::map<Size, MzTabInteger> num_peptides_distinct_ms_run;
// std::map<Size, MzTabInteger> num_peptides_unique_ms_run;
MzTabModificationList modifications; // Modifications identified in the protein.
const std::set<pair<Size, ResidueModification>>& leader_mods = hit.getModifications();
for (auto const & m : leader_mods)
{
MzTabModification mztab_mod;
mztab_mod.setModificationIdentifier(MzTab::getModificationIdentifier_(m.second));
vector<std::pair<Size, MzTabParameter> > pos;
pos.emplace_back(make_pair(m.first, MzTabParameter())); // position, parameter pair (e.g. FLR)
mztab_mod.setPositionsAndParameters(pos);
}
protein_row.modifications = modifications;
// MzTabString uri; // Location of the protein’s source entry.
// MzTabStringList go_terms; // List of GO terms for the protein.
double coverage = hit.getCoverage() / 100.0; // convert percent to fraction
protein_row.coverage = coverage >= 0 ? MzTabDouble(coverage) : MzTabDouble(); // (0-1) Amount of protein sequence identified.
// std::vector<MzTabOptionalColumnEntry> opt_; // Optional Columns must start with “opt_”
// create and fill opt_ columns for protein hit user values
addMetaInfoToOptionalColumns(protein_hit_user_value_keys, protein_row.opt_, String("global"), hit);
// optional column for protein groups
MzTabOptionalColumnEntry opt_column_entry;
opt_column_entry.first = "opt_global_result_type";
opt_column_entry.second = MzTabString("protein_details");
protein_row.opt_.push_back(opt_column_entry);
remapTargetDecoyProteinSection_(protein_row.opt_);
return protein_row;
}
MzTabProteinSectionRow MzTab::nextProteinSectionRowFromProteinGroup_(
const ProteinIdentification::ProteinGroup& group,
const MzTabString& db,
const MzTabString& db_version)
{
MzTabProteinSectionRow protein_row;
protein_row.database = db; // Name of the protein database.
protein_row.database_version = db_version; // String Version of the protein database.
MzTabStringList ambiguity_members;
ambiguity_members.setSeparator(',');
vector<MzTabString> entries;
for (Size j = 0; j != group.accessions.size() ; ++j)
{
// set accession and description to first element of group
if (j == 0)
{
protein_row.accession = MzTabString(group.accessions[j]);
// protein_row.description // TODO: how to set description? information not contained in group
}
entries.emplace_back(group.accessions[j]);
}
ambiguity_members.set(entries);
protein_row.ambiguity_members = ambiguity_members; // Alternative protein identifications.
protein_row.best_search_engine_score[1] = MzTabDouble(group.probability);
protein_row.coverage = MzTabDouble();
MzTabOptionalColumnEntry opt_column_entry;
opt_column_entry.first = "opt_global_result_type";
opt_column_entry.second = MzTabString("general_protein_group");
protein_row.opt_.push_back(opt_column_entry);
remapTargetDecoyProteinSection_(protein_row.opt_);
return protein_row;
}
MzTabProteinSectionRow MzTab::nextProteinSectionRowFromIndistinguishableGroup_(
const std::vector<ProteinHit>& protein_hits,
const ProteinIdentification::ProteinGroup& group,
const size_t g,
const map<Size, set<Size>>& ind2prot,
const MzTabString& db,
const MzTabString& db_version)
{
MzTabProteinSectionRow protein_row;
// get references (indices) into proteins vector
const set<Size> & protein_hits_idx = ind2prot.at(g);
// determine group leader
const ProteinHit& leader_protein = protein_hits[*protein_hits_idx.begin()];
protein_row.database = db; // Name of the protein database.
protein_row.database_version = db_version; // String Version of the protein database.
// column: accession and ambiguity_members
MzTabStringList ambiguity_members;
ambiguity_members.setSeparator(',');
vector<MzTabString> entries;
// set accession and description to first element of group
protein_row.accession = MzTabString(leader_protein.getAccession());
// TODO: check with standard if it is important to also place leader at first position
// (because order in set and vector may differ)
for (Size j = 0; j != group.accessions.size() ; ++j)
{
entries.emplace_back(group.accessions[j]);
}
ambiguity_members.set(entries);
protein_row.ambiguity_members = ambiguity_members; // set of indistinguishable proteins
// annotate if group contains only one or multiple proteins
MzTabOptionalColumnEntry opt_column_entry;
opt_column_entry.first = "opt_global_result_type";
// TODO: we could count the number of targets or set it to target if at least one target is inside the group
const String col_name = entries.size() == 1 ? "single_protein" : "indistinguishable_protein_group";
opt_column_entry.second = MzTabString(col_name);
protein_row.opt_.push_back(opt_column_entry);
// column: coverage
// calculate mean coverage from individual protein coverages
double coverage{0};
for (const Size & prot_idx : protein_hits_idx)
{
coverage += (1.0 / (double)protein_hits_idx.size()) * 0.01 * protein_hits[prot_idx].getCoverage();
}
if (coverage >= 0) { protein_row.coverage = MzTabDouble(coverage); }
// Store quantitative value attached to abundances in study variables
if (!group.getFloatDataArrays().empty()
&& group.getFloatDataArrays()[0].getName() == "abundances")
{
const ProteinIdentification::ProteinGroup::FloatDataArray & fa = group.getFloatDataArrays()[0];
Size s(1);
for (float f : fa)
{
protein_row.protein_abundance_assay[s] = MzTabDouble(f); // assay has same information as SV (without design)
protein_row.protein_abundance_study_variable[s] = MzTabDouble(f);
protein_row.protein_abundance_stdev_study_variable[s] = MzTabDouble();
protein_row.protein_abundance_std_error_study_variable[s] = MzTabDouble();
++s;
}
}
// add protein description of first (leader) protein
protein_row.description = MzTabString(leader_protein.getDescription());
protein_row.taxid = (leader_protein.metaValueExists("TaxID")) ?
MzTabInteger(static_cast<int>(leader_protein.getMetaValue("TaxID"))) :
MzTabInteger();
protein_row.species = (leader_protein.metaValueExists("Species")) ?
MzTabString(leader_protein.getMetaValue("Species")) :
MzTabString();
protein_row.uri = (leader_protein.metaValueExists("URI")) ?
MzTabString(leader_protein.getMetaValue("URI")) :
MzTabString();
if (leader_protein.metaValueExists("GO"))
{
StringList sl = leader_protein.getMetaValue("GO");
String s{};
s.concatenate(sl.begin(), sl.end(), ",");
protein_row.go_terms.fromCellString(s);
}
protein_row.best_search_engine_score[1] = MzTabDouble(group.probability); // TODO: group probability or search engine score?
protein_row.reliability = MzTabInteger();
MzTabParameterList search_engine; // Search engine(s) identifying the protein.
protein_row.search_engine = search_engine;
MzTabModificationList modifications; // Modifications identified in the protein.
const std::set<pair<Size, ResidueModification>>& leader_mods = leader_protein.getModifications();
for (auto const & m : leader_mods)
{
MzTabModification mztab_mod;
mztab_mod.setModificationIdentifier(MzTab::getModificationIdentifier_(m.second));
vector<std::pair<Size, MzTabParameter> > pos;
// mzTab position is one-based, internal is 0-based so we need to +1
pos.emplace_back(make_pair(m.first + 1, MzTabParameter())); // position, parameter pair (e.g. FLR)
mztab_mod.setPositionsAndParameters(pos);
vector<MzTabModification> mztab_mods(1, mztab_mod);
modifications.set(mztab_mods);
}
protein_row.modifications = modifications;
if (leader_protein.metaValueExists("num_psms_ms_run"))
{
const IntList& il = leader_protein.getMetaValue("num_psms_ms_run");
for (Size ili = 0; ili != il.size(); ++ili)
{
protein_row.num_psms_ms_run[ili+1] = MzTabInteger(il[ili]);
}
}
if (leader_protein.metaValueExists("num_peptides_distinct_ms_run"))
{
const IntList& il = leader_protein.getMetaValue("num_peptides_distinct_ms_run");
for (Size ili = 0; ili != il.size(); ++ili)
{
protein_row.num_peptides_distinct_ms_run[ili+1] = MzTabInteger(il[ili]);
}
}
if (leader_protein.metaValueExists("num_peptides_unique_ms_run"))
{
const IntList& il = leader_protein.getMetaValue("num_peptides_unique_ms_run");
for (Size ili = 0; ili != il.size(); ++ili)
{
protein_row.num_peptides_unique_ms_run[ili+1] = MzTabInteger(il[ili]);
}
}
/*
TODO:
Not sure how to handle these:
// std::map<Size, MzTabDouble> best_search_engine_score; // best_search_engine_score[1-n]
// std::map<Size, std::map<Size, MzTabDouble> > search_engine_score_ms_run; // search_engine_score[index1]_ms_run[index2]
*/
remapTargetDecoyProteinSection_(protein_row.opt_);
// Add protein(group) row to MzTab
return protein_row;
}
map<String, Size> MzTab::mapIDRunIdentifier2IDRunIndex_(const vector<const ProteinIdentification*>& prot_ids)
{
map<String, Size> idrunid_2_idrunindex;
size_t current_idrun_index(0);
for (auto const& pid : prot_ids)
{
idrunid_2_idrunindex[pid->getIdentifier()] = current_idrun_index;
++current_idrun_index;
}
return idrunid_2_idrunindex;
}
void MzTab::mapBetweenMSFileNameAndMSRunIndex_(
const vector<const ProteinIdentification*>& prot_ids,
bool skip_first,
map<String, size_t>& msfilename_2_msrunindex,
map<size_t, String>& msrunindex_2_msfilename)
{
size_t current_ms_run_index(1);
bool first = true;
for (auto const& pid : prot_ids)
{
if (skip_first && first)
{
first = false;
continue;
}
StringList ms_run_in_data;
pid->getPrimaryMSRunPath(ms_run_in_data);
if (!ms_run_in_data.empty())
{
// prepend file:// if not there yet
for (const String& s : ms_run_in_data)
{
// use the string without file: prefix for the map
msrunindex_2_msfilename.emplace(current_ms_run_index, s);
const auto& msfileidxpair_success = msfilename_2_msrunindex.emplace(s, current_ms_run_index);
if (msfileidxpair_success.second) // newly inserted
{
current_ms_run_index++;
}
}
}
else
{
// next line is a hack. In case we would ever have some idXML where some runs are annotated
// and others are not. If a run is not annotated use its index as a String key.
msrunindex_2_msfilename.emplace(current_ms_run_index, String(current_ms_run_index));
msfilename_2_msrunindex.emplace(String(current_ms_run_index), current_ms_run_index);
current_ms_run_index++;
}
}
}
void MzTab::addMSRunMetaData_(
const map<size_t, String>& msrunindex_2_msfilename,
MzTabMetaData& meta_data)
{
for (const auto& r2f : msrunindex_2_msfilename)
{
MzTabMSRunMetaData ms_run;
String m = r2f.second;
if (!m.hasPrefix("file://")) m = String("file://") + m;
ms_run.location = MzTabString(m);
meta_data.ms_run[r2f.first] = ms_run;
}
}
map<Size, set<Size>> MzTab::mapGroupsToProteins_(
const vector<ProteinIdentification::ProteinGroup>& groups,
const vector<ProteinHit>& proteins)
{
map<Size, set<Size>> group2prot;
Size idx{0};
for (const ProteinIdentification::ProteinGroup & p : groups)
{
for (const String & a : p.accessions)
{
// find protein corresponding to accession stored in group
auto it = std::find_if(proteins.begin(), proteins.end(), [&a](const ProteinHit & ph)
{
return ph.getAccession() == a;
}
);
if (it == proteins.end())
{
continue;
}
Size protein_index = std::distance(proteins.begin(), it);
group2prot[idx].insert(protein_index);
}
++idx;
}
return group2prot;
}
void MzTab::addSearchMetaData_(
const vector<const ProteinIdentification*>& prot_ids,
const map<tuple<String, String, String>, set<Size>>& search_engine_to_runs,
const map<String, vector<pair<String,String>>>& search_engine_to_settings,
MzTabMetaData& meta_data,
bool first_run_inference_only)
{
set<String> protein_scoretypes;
map<pair<String, String>, vector<pair<String,String>>> protein_settings;
for (const auto& prot_run : prot_ids)
{
//TODO this is a little hack to convert back and from
protein_scoretypes.insert(getProteinScoreType_(*prot_run).toCellString());
if (prot_run->hasInferenceData())
{
String eng = prot_run->getInferenceEngine();
String ver = prot_run->getInferenceEngineVersion();
protein_settings.emplace(make_pair(std::move(eng), std::move(ver)),vector<pair<String,String>>{});
// TODO add settings for inference tools?
}
if (first_run_inference_only) break;
}
Size cnt(1);
for (const auto& mztpar : protein_scoretypes)
{
MzTabParameter p{};
//TODO actually we should make a distinction between protein and protein group-level FDRs
if (mztpar.hasSubstring("q-value"))
{
p.fromCellString("[MS,MS:1003117,OpenMS:Target-decoy protein q-value, ]");
}
else if (mztpar.hasSubstring("Epifany"))
{
p.fromCellString("[MS,MS:1003119,EPIFANY:Protein posterior probability,]");
}
else
{
p.fromCellString(mztpar);
}
meta_data.protein_search_engine_score[cnt] = p;
cnt++;
}
for (const auto& eng_ver_settings : protein_settings)
{
MzTabSoftwareMetaData sesoftwaremd;
MzTabParameter sesoftware;
if (eng_ver_settings.first.first == "Epifany")
{
sesoftware.fromCellString("[MS,MS:1003118,EPIFANY," + eng_ver_settings.first.second + "]");
}
else if (eng_ver_settings.first.first == "TOPPProteinInference")
{
sesoftware.fromCellString("[MS,MS:1002203,TOPP ProteinInference," + eng_ver_settings.first.second + "]");
}
else
{
sesoftware.fromCellString("[,," + eng_ver_settings.first.first + "," + eng_ver_settings.first.second + "]");
}
sesoftwaremd.software = sesoftware;
meta_data.software[meta_data.software.size() + 1] = sesoftwaremd;
}
//TODO make software a list?? super weird to fill it like this.
Size sw_idx(meta_data.software.size() + 1); //+1 since we always start with 1 anyway.
// Print unique search engines as collected in the input map (globally with first setting encountered)
for (auto const & name_ver_score_to_runs : search_engine_to_runs)
{
MzTabSoftwareMetaData sesoftwaremd;
MzTabParameter sesoftware;
//TODO decide if we should use the original search engine ontology entries or the TOPPAdapter entries
if (get<0>(name_ver_score_to_runs.first) == "Comet")
{
sesoftware.fromCellString("[MS,MS:1002251,Comet," + get<1>(name_ver_score_to_runs.first) + "]");
}
else if (get<0>(name_ver_score_to_runs.first) == "Percolator")
{
sesoftware.fromCellString("[MS,MS:1001490,Percolator," + get<1>(name_ver_score_to_runs.first) + "]");
}
else if (get<0>(name_ver_score_to_runs.first) == "MS-GF+" || get<0>(name_ver_score_to_runs.first) == "MSGFPlus")
{
sesoftware.fromCellString("[MS,MS:1002048,MS-GF+," + get<1>(name_ver_score_to_runs.first) + "]");
}
else if (get<0>(name_ver_score_to_runs.first) == "XTandem")
{
sesoftware.fromCellString("[MS,MS:1001476,X!Tandem," + get<1>(name_ver_score_to_runs.first) + "]");
}
else if (get<0>(name_ver_score_to_runs.first).hasSubstring("ConsensusID"))
{
sesoftware.fromCellString("[MS,MS:1002188,TOPP ConsensusID," + get<1>(name_ver_score_to_runs.first) + "]");
}
else
{
sesoftware.fromCellString("[,," + get<0>(name_ver_score_to_runs.first) + "," + get<1>(name_ver_score_to_runs.first) + "]");
}
sesoftwaremd.software = sesoftware;
Size cnt2(1);
for (auto const & sesetting : search_engine_to_settings.at(get<0>(name_ver_score_to_runs.first)))
{
sesoftwaremd.setting[cnt2] = MzTabString(sesetting.first + ":" + (!sesetting.second.empty() ? sesetting.second : "null"));
cnt2++;
}
meta_data.software[sw_idx] = sesoftwaremd;
sw_idx++;
}
//TODO actually when filling search_engine_to_runs we would need to go through all MetaValues
// in the PeptideHits to get all scores and list them.
// But we do not really annotate which meta values are scores, so we would need to do best guesses
// Therefore we currently only list the main score type and potentially report additional scores as
// opt_ columns
Size psm_search_engine_index(1);
for (auto const & se : search_engine_to_runs) // loop over (unique) search engine names
{
//Huge TODO: we need to somehow correctly support peptide-level scores
MzTabParameter psm_score_type;
MzTabParameter pep_score_type;
const tuple<String, String, String>& name_version_score = se.first;
psm_score_type.fromCellString("[,," + get<0>(name_version_score) + " " + get<2>(name_version_score) + ",]");
pep_score_type.fromCellString("[MS,MS:1003114,OpenMS:Best PSM Score,]");
//TODO we also should consider the different q-value calculation methods of Percolator....
if (get<2>(name_version_score) == "peptide-level q-value")
{
if (get<0>(name_version_score) == "Percolator")
{
pep_score_type.fromCellString("[MS,MS:1002360,distinct peptide-level FDRScore,Percolator]");
psm_score_type = pep_score_type; // since we have no way to have two types
}
else
{
pep_score_type.fromCellString("[MS,MS:1003116,OpenMS:Target-decoy peptide q-value,]");
psm_score_type = pep_score_type; // since we have no way to have two types
}
}
else if (get<2>(name_version_score).hasSubstring("q-value"))
{
if (get<0>(name_version_score) == "Percolator")
{
psm_score_type.fromCellString("[MS,MS:1001491,percolator:Q value,]");
}
else
{
psm_score_type.fromCellString("[MS,MS:1003115,OpenMS:Target-decoy PSM q-value,]");
}
}
else if (get<2>(name_version_score) == "Posterior Error Probability" || get<2>(name_version_score) == "pep")
{
if (get<0>(name_version_score).hasSubstring("ConsensusID"))
{
const String& name = get<0>(name_version_score);
String algo = name.suffix('_');
psm_score_type.fromCellString("[MS,MS:1003113,OpenMS:ConsensusID PEP," + algo + "]");
}
else if (get<0>(name_version_score).hasSubstring("Percolator"))
{
psm_score_type.fromCellString("[MS,MS:1001493,percolator:PEP,]");
}
}
else if (get<0>(name_version_score) == "Comet")
{
if (get<2>(name_version_score) == "expect")
{
psm_score_type.fromCellString("[MS,MS:1002257,Comet:expectation value,]");
}
//TODO other Comet scores
}
else if (get<0>(name_version_score) == "MSGFPlus" || get<0>(name_version_score) == "MS-GF+")
{
if (get<2>(name_version_score) == "SpecEValue")
{
psm_score_type.fromCellString("[MS,MS:1002052,MS-GF:SpecEValue,]");
}
//TODO other MSGF scores
}
//TODO all the other dozens of search engines
meta_data.psm_search_engine_score[psm_search_engine_index] = psm_score_type;
meta_data.peptide_search_engine_score[psm_search_engine_index] = pep_score_type; // same score type for peptides
psm_search_engine_index++;
}
}
MzTabParameter MzTab::getMSRunSpectrumIdentifierType_(const vector<const PeptideIdentification*>& peptide_ids)
{
MzTabParameter p;
p.fromCellString("[MS,MS:1001530,mzML unique identifier,]");
for (const auto& pid : peptide_ids)
{
String spec_ref = pid->getMetaValue("spectrum_reference", "");
// note: don't change order as some may contain the other terms as well. Taken from mzTab specification document
if (spec_ref.hasSubstring("controllerNumber=")) { p.fromCellString("[MS,MS:1000768,Thermo nativeID format,]"); return p; }
if (spec_ref.hasSubstring("process=")) { p.fromCellString("[MS,MS:1000769,Waters nativeID format,]"); return p; }
if (spec_ref.hasSubstring("cycle=")) { p.fromCellString("[MS,MS:1000770,WIFF nativeID format,]"); return p; }
if (spec_ref.hasSubstring("scan=")) { p.fromCellString("[MS,MS:1000776,scan number only nativeID format,]"); return p; }
if (spec_ref.hasSubstring("spectrum=")) { p.fromCellString("[MS,MS:1000777,spectrum identifier nativeID format,]"); return p; }
return p;
}
return p;
}
MzTab::IDMzTabStream::IDMzTabStream(
const std::vector<const ProteinIdentification*>& prot_ids,
const std::vector<const PeptideIdentification*>& peptide_ids,
const String& filename,
bool first_run_inference_only,
bool export_empty_pep_ids,
bool export_all_psms,
const String& title):
prot_ids_(prot_ids),
peptide_ids_(peptide_ids),
filename_(filename),
export_empty_pep_ids_(export_empty_pep_ids),
export_all_psms_(export_all_psms)
{
////////////////////////////////////////////////
// create some lookup structures and precalculate some values
idrunid_2_idrunindex_ = MzTab::mapIDRunIdentifier2IDRunIndex_(prot_ids_);
bool has_inference_data = prot_ids_.empty() ? false : prot_ids_[0]->hasInferenceData();
first_run_inference_ = has_inference_data && first_run_inference_only;
if (first_run_inference_)
{
OPENMS_LOG_INFO << "MzTab: Inference data provided. Considering first run only for inference data." << std::endl;
}
map<String, size_t> msfilename_2_msrunindex;
map<size_t, String> msrunindex_2_msfilename;
MzTab::mapBetweenMSFileNameAndMSRunIndex_(prot_ids_, first_run_inference_, msfilename_2_msrunindex, msrunindex_2_msfilename);
// MS runs of a peptide identification object is stored in
// the protein identification object with the same "identifier".
// Thus, we build a map from psm_idx->run_index (aka index of PeptideHit -> run index)
MzTab::mapIDRunFileIndex2MSFileIndex_(prot_ids_, msfilename_2_msrunindex, first_run_inference_, map_id_run_fileidx_2_msfileidx_);
// collect variable and fixed modifications from different runs
StringList var_mods;
MzTab::getSearchModifications_(prot_ids_, var_mods, fixed_mods_);
// Determine search engines used in the different MS runs.
map<tuple<String, String, String>, set<Size>> search_engine_to_runs;
map<String, vector<pair<String,String>>> search_engine_to_settings;
// search engine and version <-> MS runs index
MzTab::mapBetweenRunAndSearchEngines_(
prot_ids_,
peptide_ids_,
first_run_inference_,
search_engine_to_runs,
run_to_search_engines_,
run_to_search_engines_settings_,
search_engine_to_settings);
///////////////////////////////////////
// create column names from meta values
MzTab::getIdentificationMetaValues_(
prot_ids,
peptide_ids_,
protein_hit_user_value_keys_,
peptide_id_user_value_keys_,
peptide_hit_user_value_keys_);
// determine nativeID format
MzTabParameter msrun_spectrum_identifier_type = MzTab::getMSRunSpectrumIdentifierType_(peptide_ids);
// filter out redundant meta values
protein_hit_user_value_keys_.erase("Description"); // already used in Description column
// construct optional column names
for (const auto& k : protein_hit_user_value_keys_) prt_optional_column_names_.emplace_back("opt_global_" + k);
for (const auto& k : peptide_id_user_value_keys_) psm_optional_column_names_.emplace_back("opt_global_" + k);
for (const auto& k : peptide_hit_user_value_keys_) psm_optional_column_names_.emplace_back("opt_global_" + k);
// rename some of them to be compatible with PRIDE
std::replace(prt_optional_column_names_.begin(), prt_optional_column_names_.end(), String("opt_global_target_decoy"), String("opt_global_cv_PRIDE:0000303_decoy_hit")); // for PRIDE
prt_optional_column_names_.emplace_back("opt_global_result_type");
std::replace(psm_optional_column_names_.begin(), psm_optional_column_names_.end(), String("opt_global_target_decoy"), String("opt_global_cv_MS:1002217_decoy_peptide")); // for PRIDE
psm_optional_column_names_.emplace_back("opt_global_cv_MS:1000889_peptidoform_sequence");
///////////////////////////////////////////////////////////////////////
// Export protein/-group quantifications (stored as meta value in protein IDs)
// In this case, the first run is only for inference, get peptide info from the rest of the runs.
// Check if abundances are annotated to the ind. protein groups
// if so, we will output the abundances as in a quantification file
// TODO: we currently assume groups are only in the first run, if at all
// if we add a field to an ProtIDRun to specify to which condition it belongs,
// a vector of ProtIDRuns can potentially hold multiple groupings with quants
quant_study_variables_ = prot_ids_.empty() ? 0 : getQuantStudyVariables_(*prot_ids_[0]);
// export PSMs of peptide identifications
MzTab mztab;
// mandatory meta values
meta_data_.mz_tab_type = MzTabString("Identification");
meta_data_.mz_tab_mode = MzTabString("Summary");
meta_data_.description = MzTabString("OpenMS export from ID data");
meta_data_.title = MzTabString(title);
meta_data_.variable_mod = generateMzTabStringFromModifications(var_mods);
meta_data_.fixed_mod = generateMzTabStringFromModifications(fixed_mods_);
MzTabSoftwareMetaData sw;
sw.software.fromCellString("[MS,MS:1000752,TOPP software," + VersionInfo::getVersion() + "]");
meta_data_.software[std::max<size_t>(1u, meta_data_.software.size()+1)] = sw;
if (!prot_ids_.empty())
{
// add filenames to the MSRuns in the metadata section
MzTab::addMSRunMetaData_(msrunindex_2_msfilename, meta_data_);
// add search settings to software meta data
MzTab::addSearchMetaData_(
prot_ids_,
search_engine_to_runs,
search_engine_to_settings,
meta_data_,
first_run_inference_);
// trim db name for rows (full name already stored in meta data)
const ProteinIdentification::SearchParameters & sp = prot_ids_[0]->getSearchParameters();
String db_basename = File::basename(sp.db);
db_ = MzTabString(FileHandler::stripExtension(db_basename));
db_version_ = sp.db_version.empty() ? MzTabString() : MzTabString(sp.db_version);
}
// condense consecutive unique MS runs to get the different MS files
auto it = std::unique(ms_runs_.begin(), ms_runs_.end());
ms_runs_.resize(std::distance(ms_runs_.begin(), it));
// TODO according to the mzTab standard an MS run can or should be multiple files, when they are coming from
// a pre-fractionated sample -> this sounds more like our fraction groups ?!
// set run meta data
Size run_index{1};
for (String m : ms_runs_)
{
MzTabMSRunMetaData mztab_run_metadata;
mztab_run_metadata.format.fromCellString("[MS,MS:1000584,mzML file,]");
mztab_run_metadata.id_format = msrun_spectrum_identifier_type;
// prepend file:// if not there yet
if (!m.hasPrefix("file://")) {m = String("file://") + m; }
mztab_run_metadata.location = MzTabString(m);
meta_data_.ms_run[run_index] = mztab_run_metadata;
OPENMS_LOG_DEBUG << "Adding MS run for file: " << m << endl;
++run_index;
}
}
const MzTabMetaData& MzTab::IDMzTabStream::getMetaData() const
{
return meta_data_;
}
const vector<String>& MzTab::IDMzTabStream::getProteinOptionalColumnNames() const
{
return prt_optional_column_names_;
}
const vector<String>& MzTab::IDMzTabStream::getPeptideOptionalColumnNames() const
{
return pep_optional_column_names_;
}
const vector<String>& MzTab::IDMzTabStream::getPSMOptionalColumnNames() const
{
return psm_optional_column_names_;
}
bool MzTab::IDMzTabStream::nextPRTRow(MzTabProteinSectionRow& row)
{
if (prot_ids_.empty()) return false;
// simple state machine to write out 1. all proteins, 2. all general groups and 3. all indistinguishable groups
state0:
// done if all protein information is contained in run zero and we enter run 1
if (first_run_inference_ && prt_run_id_ > 0) return false; // done
if (prt_run_id_ >= prot_ids_.size()) return false; // done for the first_run_inference_ == false case
const ProteinIdentification& pid = *prot_ids_[prt_run_id_];
const std::vector<ProteinHit>& protein_hits = pid.getHits();
// We only report quantitative data for indistinguishable groups (which may be composed of single proteins).
// We skip the more extensive reporting of general groups with complex shared peptide relations.
const std::vector<ProteinIdentification::ProteinGroup>& protein_groups2 = quant_study_variables_ == 0 ? pid.getProteinGroups() : std::vector<ProteinIdentification::ProteinGroup>();
const std::vector<ProteinIdentification::ProteinGroup>& indist_groups2 = pid.getIndistinguishableProteins();
if (prt_hit_id_ == 0 && PRT_STATE_ == 0)
{ // Processing new protein identification run?
// Map (indist.)protein groups to their protein hits (by index) in this run.
ind2prot_ = MzTab::mapGroupsToProteins_(pid.getIndistinguishableProteins(), protein_hits);
pg2prot_ = MzTab::mapGroupsToProteins_(pid.getProteinGroups(), protein_hits);
}
if (PRT_STATE_ == 0) // write protein hits
{
if (prt_hit_id_ >= protein_hits.size())
{
prt_hit_id_ = 0;
PRT_STATE_ = 1; // continue with next state (!)
}
else
{
const ProteinHit& protein = protein_hits[prt_hit_id_];
auto prt_row = MzTab::proteinSectionRowFromProteinHit_(
protein,
db_,
db_version_,
protein_hit_user_value_keys_);
++prt_hit_id_;
std::swap(row, prt_row);
return true;
}
}
if (PRT_STATE_ == 1) // write general groups
{
if (prt_group_id_ >= protein_groups2.size())
{
prt_group_id_ = 0;
PRT_STATE_ = 2;
}
else
{
const ProteinIdentification::ProteinGroup& group = protein_groups2[prt_group_id_];
auto prt_row = MzTab::nextProteinSectionRowFromProteinGroup_(
group,
db_,
db_version_);
++prt_group_id_;
std::swap(row, prt_row);
return true;
}
}
// PRT_STATE_ == 2
if (prt_indistgroup_id_ >= indist_groups2.size())
{
prt_indistgroup_id_ = 0;
prt_hit_id_ = 0;
PRT_STATE_ = 0;
++prt_run_id_; // next protein run
goto state0;
}
else
{
const ProteinIdentification::ProteinGroup& group = indist_groups2[prt_indistgroup_id_];
auto prt_row = MzTab::nextProteinSectionRowFromIndistinguishableGroup_(
protein_hits,
group,
prt_indistgroup_id_,
ind2prot_,
db_,
db_version_);
++prt_indistgroup_id_;
std::swap(row, prt_row);
return true;
}
return false; // should not be reached
}
bool MzTab::IDMzTabStream::nextPEPRow(MzTabPeptideSectionRow&)
{
return false; // no linked feature information
}
bool MzTab::IDMzTabStream::nextPSMRow(MzTabPSMSectionRow& row)
{
if (pep_id_ >= peptide_ids_.size())
{
return false;
}
const PeptideIdentification* pid = peptide_ids_[pep_id_];
auto psm_row = MzTab::PSMSectionRowFromPeptideID_(
*pid,
prot_ids_,
idrunid_2_idrunindex_,
map_id_run_fileidx_2_msfileidx_,
run_to_search_engines_,
current_psm_idx_,
psm_id_,
db_,
db_version_,
export_empty_pep_ids_,
export_all_psms_);
if (!export_all_psms_ || current_psm_idx_ == pid->getHits().size()-1)
{
++pep_id_;
current_psm_idx_ = 0;
}
else
{
++current_psm_idx_;
}
++psm_id_; //global psm id "counter"
if (psm_row) // valid row?
{
row = *psm_row;
}
else
{
row = MzTabPSMSectionRow();
}
return true;
}
MzTab MzTab::exportIdentificationsToMzTab(
const vector<ProteinIdentification>& prot_ids,
const PeptideIdentificationList& peptide_ids,
const String& filename,
bool first_run_inference_only,
bool export_empty_pep_ids,
bool export_all_psms,
const String& title)
{
vector<const PeptideIdentification*> pep_ids_ptr;
pep_ids_ptr.reserve(peptide_ids.size());
for (const PeptideIdentification& pi : peptide_ids) { pep_ids_ptr.push_back(&pi); }
vector<const ProteinIdentification*> prot_ids_ptr;
prot_ids_ptr.reserve(prot_ids.size());
for (const ProteinIdentification& pi : prot_ids) { prot_ids_ptr.push_back(&pi); }
IDMzTabStream s(prot_ids_ptr, pep_ids_ptr, filename, first_run_inference_only, export_empty_pep_ids, export_all_psms, title);
MzTab m;
m.setMetaData(s.getMetaData());
MzTabProteinSectionRow prot_row;
while (s.nextPRTRow(prot_row))
{
m.getProteinSectionRows().emplace_back(std::move(prot_row));
}
MzTabPSMSectionRow psm_row;
while (s.nextPSMRow(psm_row))
{
m.getPSMSectionRows().emplace_back(std::move(psm_row));
}
return m;
}
MzTabModificationList MzTab::extractModificationList(const PeptideHit& pep_hit, const vector<String>& fixed_mods, const vector<String>& localization_mods)
{
const AASequence& aas = pep_hit.getSequence();
MzTabModificationList mod_list;
vector<MzTabModification> mods;
bool has_loc_mods = !localization_mods.empty();
MzTabParameter localization_score;
if (has_loc_mods && pep_hit.metaValueExists("Luciphor_global_flr"))
{
localization_score.fromCellString("[MS,MS:1002380,false localization rate," + String(pep_hit.getMetaValue("Luciphor_global_flr"))+"]");
}
if (aas.isModified())
{
if (aas.hasNTerminalModification())
{
MzTabModification mod;
const ResidueModification& res_mod = *(aas.getNTerminalModification());
bool is_fixed = std::find(fixed_mods.begin(), fixed_mods.end(), res_mod.getId()) != fixed_mods.end();
if (!is_fixed)
{
mod.setModificationIdentifier(MzTab::getModificationIdentifier_(res_mod));
vector<std::pair<Size, MzTabParameter> > pos;
pos.emplace_back(0, MzTabParameter());
mod.setPositionsAndParameters(pos);
mods.push_back(mod);
}
}
for (Size ai = 0; ai != aas.size(); ++ai)
{
if (aas[ai].isModified())
{
MzTabModification mod;
const ResidueModification& res_mod = *(aas[ai].getModification());
bool is_fixed = std::find(fixed_mods.begin(), fixed_mods.end(), res_mod.getId()) != fixed_mods.end();
if (!is_fixed)
{
// MzTab standard is to just report Unimod accession.
vector<std::pair<Size, MzTabParameter> > pos;
if (has_loc_mods && std::find(localization_mods.begin(), localization_mods.end(), res_mod.getFullId()) != localization_mods.end())
{ // store localization score for this mod
pos.emplace_back(ai + 1, localization_score);
}
else
{
pos.emplace_back(ai + 1, MzTabParameter());
}
mod.setPositionsAndParameters(pos);
mod.setModificationIdentifier(MzTab::getModificationIdentifier_(res_mod));
mods.push_back(mod);
}
}
}
if (aas.hasCTerminalModification())
{
MzTabModification mod;
const ResidueModification& res_mod = *(aas.getCTerminalModification());
if (std::find(fixed_mods.begin(), fixed_mods.end(), res_mod.getId()) == fixed_mods.end())
{
vector<std::pair<Size, MzTabParameter> > pos;
pos.emplace_back(aas.size() + 1, MzTabParameter());
mod.setPositionsAndParameters(pos);
mod.setModificationIdentifier(MzTab::getModificationIdentifier_(res_mod));
mods.push_back(mod);
}
}
}
mod_list.set(mods);
return mod_list;
}
void MzTab::getFeatureMapMetaValues_(const FeatureMap& feature_map,
set<String>& feature_user_value_keys,
set<String>& peptide_identification_user_value_keys,
set<String>& peptide_hit_user_value_keys)
{
for (Size i = 0; i < feature_map.size(); ++i)
{
const Feature& f = feature_map[i];
vector<String> keys;
f.getKeys(keys); //TODO: why not just return it?
feature_user_value_keys.insert(keys.begin(), keys.end());
const PeptideIdentificationList& pep_ids = f.getPeptideIdentifications();
for (PeptideIdentification const & pep_id : pep_ids)
{
vector<String> pep_keys;
pep_id.getKeys(pep_keys);
peptide_identification_user_value_keys.insert(pep_keys.begin(), pep_keys.end());
for (PeptideHit const & hit : pep_id.getHits())
{
vector<String> ph_keys;
hit.getKeys(ph_keys);
peptide_hit_user_value_keys.insert(ph_keys.begin(), ph_keys.end());
}
}
}
// we don't want spectrum reference to show up as meta value (already in dedicated column)
peptide_hit_user_value_keys.erase("spectrum_reference");
peptide_identification_user_value_keys.erase(Constants::UserParam::SIGNIFICANCE_THRESHOLD);
}
// local helper to extract meta values with space substituted with '_'
void extractMetaValuesFromIDs(const PeptideIdentificationList & curr_pep_ids,
set<String>& peptide_identification_user_value_keys,
set<String>& peptide_hit_user_value_keys)
{
for (auto const & pep_id : curr_pep_ids)
{
vector<String> pep_keys;
pep_id.getKeys(pep_keys);
// replace whitespaces with underscore
std::transform(pep_keys.begin(), pep_keys.end(), pep_keys.begin(), [&](String& s) { return s.substitute(' ', '_'); });
peptide_identification_user_value_keys.insert(pep_keys.begin(), pep_keys.end());
for (auto const & hit : pep_id.getHits())
{
vector<String> ph_keys;
hit.getKeys(ph_keys);
// replace whitespaces with underscore
std::transform(ph_keys.begin(), ph_keys.end(), ph_keys.begin(), [&](String& s) { return s.substitute(' ', '_'); });
peptide_hit_user_value_keys.insert(ph_keys.begin(), ph_keys.end());
}
}
}
// local helper to extract meta values with space substituted with '_'
void extractMetaValuesFromIDPointers(const vector<const PeptideIdentification*> & curr_pep_ids,
set<String>& peptide_identification_user_value_keys,
set<String>& peptide_hit_user_value_keys)
{
for (auto const * pep_id : curr_pep_ids)
{
vector<String> pep_keys;
pep_id->getKeys(pep_keys);
// replace whitespaces with underscore
std::transform(pep_keys.begin(), pep_keys.end(), pep_keys.begin(), [&](String& s) { return s.substitute(' ', '_'); });
peptide_identification_user_value_keys.insert(pep_keys.begin(), pep_keys.end());
for (auto const & hit : pep_id->getHits())
{
vector<String> ph_keys;
hit.getKeys(ph_keys);
// replace whitespaces with underscore
std::transform(ph_keys.begin(), ph_keys.end(), ph_keys.begin(), [&](String& s) { return s.substitute(' ', '_'); });
peptide_hit_user_value_keys.insert(ph_keys.begin(), ph_keys.end());
}
}
}
// extract *all* meta values stored at consensus feature, peptide id and peptide hit level
void MzTab::getConsensusMapMetaValues_(const ConsensusMap& consensus_map,
set<String>& consensus_feature_user_value_keys,
set<String>& peptide_identification_user_value_keys,
set<String>& peptide_hit_user_value_keys)
{
// extract meta values from unassigned peptide identifications
const PeptideIdentificationList & curr_pep_ids = consensus_map.getUnassignedPeptideIdentifications();
extractMetaValuesFromIDs(curr_pep_ids, peptide_identification_user_value_keys, peptide_hit_user_value_keys);
for (ConsensusFeature const & c : consensus_map)
{
vector<String> keys;
c.getKeys(keys);
// replace whitespaces with underscore
std::transform(keys.begin(), keys.end(), keys.begin(), [&](String& s) { return s.substitute(' ', '_'); });
consensus_feature_user_value_keys.insert(keys.begin(), keys.end());
// extract meta values from assigned peptide identifications
const PeptideIdentificationList & curr_pep_ids = c.getPeptideIdentifications();
extractMetaValuesFromIDs(curr_pep_ids, peptide_identification_user_value_keys, peptide_hit_user_value_keys);
}
// we don't want spectrum reference to show up as meta value (already in dedicated column)
peptide_identification_user_value_keys.erase("spectrum_reference");
peptide_identification_user_value_keys.erase(Constants::UserParam::SIGNIFICANCE_THRESHOLD);
}
void MzTab::getIdentificationMetaValues_(
const std::vector<const ProteinIdentification*>& prot_ids,
std::vector<const PeptideIdentification*>& peptide_ids_,
std::set<String>& protein_hit_user_value_keys,
std::set<String>& peptide_id_user_value_keys,
std::set<String>& peptide_hit_user_value_keys)
{
for (auto const & pid : prot_ids)
{
for (auto const & hit : pid->getHits())
{
vector<String> keys;
hit.getKeys(keys);
// replace whitespaces with underscore
std::transform(keys.begin(), keys.end(), keys.begin(), [&](String& s) { return s.substitute(' ', '_'); });
protein_hit_user_value_keys.insert(keys.begin(), keys.end());
}
}
extractMetaValuesFromIDPointers(peptide_ids_, peptide_id_user_value_keys, peptide_hit_user_value_keys);
peptide_id_user_value_keys.erase(Constants::UserParam::SIGNIFICANCE_THRESHOLD);
}
void MzTab::getSearchModifications_(const vector<const ProteinIdentification*>& prot_ids, StringList& var_mods, StringList& fixed_mods)
{
for (auto const & pid : prot_ids)
{
const ProteinIdentification::SearchParameters & sp = pid->getSearchParameters();
var_mods.insert(std::end(var_mods), std::begin(sp.variable_modifications), std::end(sp.variable_modifications));
fixed_mods.insert(std::end(fixed_mods), std::begin(sp.fixed_modifications), std::end(sp.fixed_modifications));
}
// make mods unique
std::sort(var_mods.begin(), var_mods.end());
auto v_it = std::unique(var_mods.begin(), var_mods.end());
var_mods.resize(std::distance(var_mods.begin(), v_it));
std::sort(fixed_mods.begin(), fixed_mods.end());
auto f_it = std::unique(fixed_mods.begin(), fixed_mods.end());
fixed_mods.resize(std::distance(fixed_mods.begin(), f_it));
}
MzTab::CMMzTabStream::CMMzTabStream(
const ConsensusMap& consensus_map,
const String& filename,
const bool first_run_inference_only,
const bool export_unidentified_features,
const bool export_unassigned_ids,
const bool export_subfeatures,
const bool export_empty_pep_ids,
const bool export_all_psms,
const String& title)
:
consensus_map_(consensus_map),
filename_(filename),
export_unidentified_features_(export_unidentified_features),
export_subfeatures_(export_subfeatures),
export_empty_pep_ids_(export_empty_pep_ids),
export_all_psms_(export_all_psms)
{
// fill ID datastructure without copying
const vector<ProteinIdentification>& prot_id = consensus_map.getProteinIdentifications();
prot_ids_.reserve(prot_id.size());
for (const auto & i : prot_id)
{
prot_ids_.push_back(&i);
}
// pre-reserve to prevent reallocations
size_t new_size = peptide_ids_.size();
for (const auto& elem : consensus_map) new_size += elem.getPeptideIdentifications().size();
if (export_unassigned_ids)
{
new_size += consensus_map.getUnassignedPeptideIdentifications().size();
}
peptide_ids_.reserve(new_size);
// extract mapped IDs
for (Size i = 0; i < consensus_map.size(); ++i)
{
const ConsensusFeature& c = consensus_map[i];
const PeptideIdentificationList& p = c.getPeptideIdentifications();
for (const PeptideIdentification& pi : p) { peptide_ids_.push_back(&pi); }
}
// also export PSMs of unassigned peptide identifications
if (export_unassigned_ids)
{
const PeptideIdentificationList& up = consensus_map.getUnassignedPeptideIdentifications();
for (const PeptideIdentification& pi : up) { peptide_ids_.push_back(&pi); }
}
////////////////////////////////////////////////
// create some lookup structures and precalculate some values
idrunid_2_idrunindex_ = MzTab::mapIDRunIdentifier2IDRunIndex_(prot_ids_);
bool has_inference_data = !prot_ids_.empty() && prot_ids_[0]->hasInferenceData();
first_run_inference_ = has_inference_data && first_run_inference_only;
if (first_run_inference_)
{
OPENMS_LOG_INFO << "MzTab: Inference data provided. Considering first run only for inference data." << std::endl;
}
map<String, size_t> msfilename_2_msrunindex;
map<size_t, String> msrunindex_2_msfilename;
MzTab::mapBetweenMSFileNameAndMSRunIndex_(prot_ids_, first_run_inference_, msfilename_2_msrunindex, msrunindex_2_msfilename);
// MS runs of a peptide identification object is stored in
// the protein identification object with the same "identifier".
// Thus, we build a map from psm_idx->run_index (aka index of PeptideHit -> run index)
MzTab::mapIDRunFileIndex2MSFileIndex_(prot_ids_, msfilename_2_msrunindex, first_run_inference_, map_id_run_fileidx_2_msfileidx_);
// collect variable and fixed modifications from different runs
StringList var_mods;
MzTab::getSearchModifications_(prot_ids_, var_mods, fixed_mods_);
// determine nativeID format
MzTabParameter msrun_spectrum_identifier_type = MzTab::getMSRunSpectrumIdentifierType_(peptide_ids_);
// Determine search engines used in the different MS runs.
map<tuple<String, String, String>, set<Size>> search_engine_to_runs;
map<String, vector<pair<String,String>>> search_engine_to_settings;
// search engine and version <-> MS runs index
MzTab::mapBetweenRunAndSearchEngines_(
prot_ids_,
peptide_ids_,
first_run_inference_,
search_engine_to_runs,
run_to_search_engines_,
run_to_search_engines_settings_,
search_engine_to_settings);
// Pre-analyze data for re-occurring meta values at consensus feature and contained peptide id and hit level.
// These are stored in optional columns of the PEP section.
MzTab::getConsensusMapMetaValues_(consensus_map,
consensus_feature_user_value_keys_,
consensus_feature_peptide_identification_user_value_keys_,
consensus_feature_peptide_hit_user_value_keys_);
// create column names from meta values
// feature meta values
for (const auto& k : consensus_feature_user_value_keys_)
{
pep_optional_column_names_.emplace_back("opt_global_" + k);
}
/*
Note: In the PEP section, meta values in peptide identifications are better omitted as they can be easily looked up from the PSM-level are otherwise duplicates.
For debug purposes one can enable this line:
for (const auto& k : consensus_feature_peptide_identification_user_value_keys_) pep_optional_column_names_.emplace_back("opt_global_" + k);
*/
// peptide hit (PSM) meta values
// whitelisted meta values "target_decoy". Expose in the PEP section with special CV term (for PRIDE compatibility):
if (auto it = consensus_feature_peptide_hit_user_value_keys_.find("target_decoy");
it != consensus_feature_peptide_hit_user_value_keys_.end())
{
pep_optional_column_names_.emplace_back("opt_global_cv_MS:1002217_decoy_peptide");
}
// added during export (for PRIDE compatibility):
pep_optional_column_names_.emplace_back("opt_global_cv_MS:1000889_peptidoform_sequence");
// PSM optional columns: also from meta values in consensus features
for (const auto& k : consensus_feature_peptide_hit_user_value_keys_) psm_optional_column_names_.emplace_back("opt_global_" + k);
std::replace(psm_optional_column_names_.begin(), psm_optional_column_names_.end(), String("opt_global_target_decoy"), String("opt_global_cv_MS:1002217_decoy_peptide")); // for PRIDE
psm_optional_column_names_.emplace_back("opt_global_cv_MS:1000889_peptidoform_sequence");
///////////////////////////////////////////////////////////////////////
// Export protein/-group quantifications (stored as meta value in protein IDs)
// In this case, the first run is only for inference, get peptide info from the rest of the runs.
// Check if abundances are annotated to the ind. protein groups
// if so, we will output the abundances as in a quantification file
// TODO: we currently assume groups are only in the first run, if at all
// if we add a field to an ProtIDRun to specify to which condition it belongs,
// a vector of ProtIDRuns can potentially hold multiple groupings with quants
quant_study_variables_ = prot_ids_.empty() ? 0 : getQuantStudyVariables_(*prot_ids_[0]);
// export PSMs of peptide identifications
MzTab mztab;
// mandatory meta values
meta_data_.mz_tab_type = MzTabString("Quantification");
meta_data_.mz_tab_mode = MzTabString("Summary");
meta_data_.description = MzTabString("OpenMS export from consensusXML");
meta_data_.variable_mod = generateMzTabStringFromModifications(var_mods);
meta_data_.fixed_mod = generateMzTabStringFromModifications(fixed_mods_);
MzTabSoftwareMetaData sw;
sw.software.fromCellString("[MS,MS:1000752,TOPP software," + VersionInfo::getVersion() + "]");
meta_data_.software[std::max<size_t>(1u, meta_data_.software.size()+1)] = sw;
if (!prot_ids_.empty())
{
// add filenames to the MSRuns in the metadata section
MzTab::addMSRunMetaData_(msrunindex_2_msfilename, meta_data_);
// add search settings to software meta data
MzTab::addSearchMetaData_(
prot_ids_,
search_engine_to_runs,
search_engine_to_settings,
meta_data_,
first_run_inference_);
// trim db name for rows (full name already stored in meta data)
const ProteinIdentification::SearchParameters & sp = prot_ids_[0]->getSearchParameters();
String db_basename = File::basename(sp.db);
db_ = MzTabString(FileHandler::stripExtension(db_basename));
db_version_ = sp.db_version.empty() ? MzTabString() : MzTabString(sp.db_version);
////////////////////////////////////////////////////////////////
// generate protein section
for (auto it = prot_ids_.cbegin(); it != prot_ids_.cend(); ++it)
{
const std::vector<ProteinHit>& protein_hits = (*it)->getHits();
// TODO: add processing information that this file has been exported from "filename"
// pre-analyze data for occurring meta values at protein hit level
// these are used to build optional columns containing the meta values in internal data structures
set<String> protein_hit_user_value_keys_tmp =
MetaInfoInterfaceUtils::findCommonMetaKeys<vector<ProteinHit>, set<String> >(protein_hits.begin(), protein_hits.end(), 100.0);
// we do not want descriptions twice
protein_hit_user_value_keys_tmp.erase("Description");
protein_hit_user_value_keys_.insert(protein_hit_user_value_keys_tmp.begin(), protein_hit_user_value_keys_tmp.end());
}
}
// column headers may not contain spaces
set<String> protein_hit_user_value_keys_tmp_2;
// replace whitespaces with underscore
std::transform(protein_hit_user_value_keys_.begin(),
protein_hit_user_value_keys_.end(),
std::inserter(protein_hit_user_value_keys_tmp_2, protein_hit_user_value_keys_tmp_2.begin()),
[](String s) { return s.substitute(' ', '_'); });
std::swap(protein_hit_user_value_keys_, protein_hit_user_value_keys_tmp_2);
// PRT optional columns
for (const auto& k : protein_hit_user_value_keys_) prt_optional_column_names_.emplace_back("opt_global_" + k);
std::replace(prt_optional_column_names_.begin(), prt_optional_column_names_.end(), String("opt_global_target_decoy"), String("opt_global_cv_PRIDE:0000303_decoy_hit")); // for PRIDE
prt_optional_column_names_.emplace_back("opt_global_result_type");
// determine number of samples
ExperimentalDesign ed = ExperimentalDesign::fromConsensusMap(consensus_map);
Size n_assays = ed.getNumberOfSamples();
// TODO for now every assay is a study variable since we do not aggregate across e.g. replicates.
n_study_variables_ = n_assays;
///////////////////////////////////////////////////////////////////////
// MetaData section
meta_data_.title = MzTabString(title);
MzTabParameter quantification_method;
const String & experiment_type = consensus_map.getExperimentType();
if (experiment_type == "label-free")
{
quantification_method.fromCellString("[MS,MS:1001834,LC-MS label-free quantitation analysis,]");
}
else if (experiment_type == "labeled_MS1")
{
quantification_method.fromCellString("[PRIDE,PRIDE_0000316,MS1 based isotope labeling,]");
}
else if (experiment_type == "labeled_MS2")
{
quantification_method.fromCellString("[PRIDE,PRIDE_0000317,MS2 based isotope labeling,]");
}
meta_data_.quantification_method = quantification_method;
MzTabParameter protein_quantification_unit;
// TODO: add better term to obo: Would need to be a combination of settings:
// "sum/mean/max/..fancy", "top3,all,..", "shared,unique,razor+unique", potentially make clear that it is usually
// on group level here (even if singleton group).
protein_quantification_unit.fromCellString("[,,Abundance,]");
meta_data_.protein_quantification_unit = protein_quantification_unit;
MzTabParameter peptide_quantification_unit;
// TODO: I think we could use MS1 feature area or feature height or spectral count here.
peptide_quantification_unit.fromCellString("[,,Abundance,]");
meta_data_.peptide_quantification_unit = peptide_quantification_unit;
consensus_map.getPrimaryMSRunPath(ms_runs_);
// condense consecutive unique MS runs to get the different MS files
auto it = std::unique(ms_runs_.begin(), ms_runs_.end());
ms_runs_.resize(std::distance(ms_runs_.begin(), it));
// TODO according to the mzTab standard an MS run can or should be multiple files, when they are coming from
// a pre-fractionated sample -> this sounds more like our fraction groups ?!
// set run meta data
Size run_index{1};
for (String m : ms_runs_)
{
MzTabMSRunMetaData mztab_run_metadata;
mztab_run_metadata.format.fromCellString("[MS,MS:1000584,mzML file,]");
mztab_run_metadata.id_format = msrun_spectrum_identifier_type;
// prepend file:// if not there yet
if (!m.hasPrefix("file://")) {m = String("file://") + m; }
mztab_run_metadata.location = MzTabString(m);
meta_data_.ms_run[run_index] = mztab_run_metadata;
OPENMS_LOG_DEBUG << "Adding MS run for file: " << m << endl;
++run_index;
}
// assay index (and sample index) must be unique numbers 1..n
// fraction_group + label define the quant. values of an assay (which currently corresponds to our Sample ID)
path_label_to_assay_ = ed.getPathLabelToSampleMapping(false);
// assay meta data
for (auto const & c : consensus_map.getColumnHeaders())
{
Size assay_index{1};
MzTabAssayMetaData assay;
MzTabParameter quantification_reagent;
Size label = c.second.getLabelAsUInt(experiment_type);
auto pl = make_pair(c.second.filename, label);
assay_index = path_label_to_assay_[pl] + 1; // sample rows are a vector and therefore their IDs zero-based, mzTab assays 1-based
if (experiment_type == "label-free")
{
quantification_reagent.fromCellString("[MS,MS:1002038,unlabeled sample,]");
}
else if (experiment_type == "labeled_MS1")
{
quantification_reagent.fromCellString("[PRIDE,PRIDE:0000316,MS1 based isotope labeling," + c.second.label + "]");
}
else if (experiment_type == "labeled_MS2")
{
quantification_reagent.fromCellString("[PRIDE,PRIDE:0000317,MS2 based isotope labeling," + c.second.label + "]");
}
// look up run index by filename
//TODO again, check if we rather want fraction groups instead of individual files.
auto md_it = find_if(meta_data_.ms_run.begin(), meta_data_.ms_run.end(),
[&c] (const pair<Size, MzTabMSRunMetaData>& m) {
return m.second.location.toCellString().hasSuffix(c.second.filename);
} );
Size curr_run_index = md_it->first;
meta_data_.assay[assay_index].quantification_reagent = quantification_reagent;
meta_data_.assay[assay_index].ms_run_ref.push_back(curr_run_index);
// study variable meta data
MzTabString sv_description;
// TODO how would we represent study variables? = Collection of sample rows that are equal except for replicate
// columns?
meta_data_.study_variable[assay_index].description.fromCellString("no description given");
IntList al;
al.push_back(assay_index);
meta_data_.study_variable[assay_index].assay_refs = al;
}
}
const MzTabMetaData& MzTab::CMMzTabStream::getMetaData() const
{
return meta_data_;
}
const vector<String>& MzTab::CMMzTabStream::getProteinOptionalColumnNames() const
{
return prt_optional_column_names_;
}
const vector<String>& MzTab::CMMzTabStream::getPeptideOptionalColumnNames() const
{
return pep_optional_column_names_;
}
const vector<String>& MzTab::CMMzTabStream::getPSMOptionalColumnNames() const
{
return psm_optional_column_names_;
}
bool MzTab::CMMzTabStream::nextPRTRow(MzTabProteinSectionRow& row)
{
if (prot_ids_.empty()) return false;
// simple state machine to write out 1. all proteins, 2. all general groups and 3. all indistinguishable groups
state0:
// done if all protein information is contained in run zero and we enter run 1
if (first_run_inference_ && prt_run_id_ > 0) return false; // done
if (prt_run_id_ >= prot_ids_.size()) return false; // done for the first_run_inference_ == false case
const ProteinIdentification& pid = *prot_ids_[prt_run_id_];
const std::vector<ProteinHit>& protein_hits = pid.getHits();
// We only report quantitative data for indistinguishable groups (which may be composed of single proteins).
// We skip the more extensive reporting of general groups with complex shared peptide relations.
const std::vector<ProteinIdentification::ProteinGroup>& protein_groups2 = quant_study_variables_ == 0 ? pid.getProteinGroups() : std::vector<ProteinIdentification::ProteinGroup>();
const std::vector<ProteinIdentification::ProteinGroup>& indist_groups2 = pid.getIndistinguishableProteins();
if (prt_hit_id_ == 0 && PRT_STATE_ == 0)
{ // Processing new protein identification run?
// Map (indist.)protein groups to their protein hits (by index) in this run.
ind2prot_ = MzTab::mapGroupsToProteins_(pid.getIndistinguishableProteins(), protein_hits);
pg2prot_ = MzTab::mapGroupsToProteins_(pid.getProteinGroups(), protein_hits);
}
if (PRT_STATE_ == 0) // write protein hits
{
if (prt_hit_id_ >= protein_hits.size())
{
prt_hit_id_ = 0;
PRT_STATE_ = 1; // continue with next state (!)
}
else
{
const ProteinHit& protein = protein_hits[prt_hit_id_];
auto prt_row = MzTab::proteinSectionRowFromProteinHit_(
protein,
db_,
db_version_,
protein_hit_user_value_keys_);
++prt_hit_id_;
std::swap(row, prt_row);
return true;
}
}
if (PRT_STATE_ == 1) // write general groups
{
if (prt_group_id_ >= protein_groups2.size())
{
prt_group_id_ = 0;
PRT_STATE_ = 2;
}
else
{
const ProteinIdentification::ProteinGroup& group = protein_groups2[prt_group_id_];
auto prt_row = MzTab::nextProteinSectionRowFromProteinGroup_(
group,
db_,
db_version_);
++prt_group_id_;
std::swap(row, prt_row);
return true;
}
}
// PRT_STATE_ == 2
if (prt_indistgroup_id_ >= indist_groups2.size())
{
prt_indistgroup_id_ = 0;
prt_hit_id_ = 0;
PRT_STATE_ = 0;
++prt_run_id_; // next protein run
goto state0;
}
else
{
const ProteinIdentification::ProteinGroup& group = indist_groups2[prt_indistgroup_id_];
auto prt_row = MzTab::nextProteinSectionRowFromIndistinguishableGroup_(
protein_hits,
group,
prt_indistgroup_id_,
ind2prot_,
db_,
db_version_);
++prt_indistgroup_id_;
std::swap(row, prt_row);
return true;
}
return false; // should not be reached
}
bool MzTab::CMMzTabStream::nextPEPRow(MzTabPeptideSectionRow& row)
{
if (pep_id_ >= consensus_map_.size()) return false;
auto c = std::cref(consensus_map_[pep_id_]);
auto has_peptide_hits = [&](const ConsensusFeature& c)
{
for (const auto& pid : c.getPeptideIdentifications())
{
if (!pid.getHits().empty()) return true;
}
return false;
};
// skip unidentified features
while (!export_unidentified_features_ && !has_peptide_hits(c.get()))
{
++pep_id_;
if (pep_id_ >= consensus_map_.size()) return false;
c = consensus_map_[pep_id_];
}
auto pep_row = MzTab::peptideSectionRowFromConsensusFeature_(
c.get(),
consensus_map_,
ms_runs_,
n_study_variables_,
consensus_feature_user_value_keys_,
consensus_feature_peptide_identification_user_value_keys_,
consensus_feature_peptide_hit_user_value_keys_,
idrunid_2_idrunindex_,
map_id_run_fileidx_2_msfileidx_,
path_label_to_assay_,
fixed_mods_,
export_subfeatures_);
++pep_id_;
std::swap(row, pep_row);
return true;
}
bool MzTab::CMMzTabStream::nextPSMRow(MzTabPSMSectionRow& row)
{
if (pep_counter_ >= peptide_ids_.size()) return false;
const PeptideIdentification* pid = peptide_ids_[pep_counter_];
auto psm_row = MzTab::PSMSectionRowFromPeptideID_(
*pid,
prot_ids_,
idrunid_2_idrunindex_,
map_id_run_fileidx_2_msfileidx_,
run_to_search_engines_,
current_psm_idx_,
psm_id_,
db_,
db_version_,
export_empty_pep_ids_,
export_all_psms_);
if (!export_all_psms_ || current_psm_idx_ == pid->getHits().size()-1)
{
++pep_counter_;
current_psm_idx_ = 0;
}
else
{
++current_psm_idx_;
}
++psm_id_; //global psm id "counter"
if (psm_row) // valid row?
{
row = *psm_row;
}
else
{
row = MzTabPSMSectionRow();
}
return true;
}
MzTab MzTab::exportConsensusMapToMzTab(
const ConsensusMap& consensus_map,
const String& filename,
const bool first_run_inference_only,
const bool export_unidentified_features,
const bool export_unassigned_ids,
const bool export_subfeatures,
const bool export_empty_pep_ids,
const bool export_all_psms,
const String& title)
{
OPENMS_LOG_INFO << "exporting consensus map: \"" << filename << "\" to mzTab: " << std::endl;
CMMzTabStream s(consensus_map,
filename,
first_run_inference_only,
export_unidentified_features,
export_unassigned_ids,
export_subfeatures,
export_empty_pep_ids,
export_all_psms,
title);
MzTab m;
m.setMetaData(s.getMetaData());
MzTabProteinSectionRow prot_row;
while (s.nextPRTRow(prot_row))
{
m.getProteinSectionRows().emplace_back(std::move(prot_row));
}
MzTabPeptideSectionRow pep_row;
while (s.nextPEPRow(pep_row))
{
m.getPeptideSectionRows().emplace_back(std::move(pep_row));
}
MzTabPSMSectionRow psm_row;
while (s.nextPSMRow(psm_row))
{
// TODO better return a State enum instead of relying on some uninitialized
// parts of a row..
if (!psm_row.sequence.isNull())
{
m.getPSMSectionRows().push_back(psm_row);
}
}
return m;
}
void MzTab::checkSequenceUniqueness_(const PeptideIdentificationList& curr_pep_ids)
{
const auto& refseq = curr_pep_ids[0].getHits()[0].getSequence();
for (const auto& pep : curr_pep_ids)
{
if (pep.getHits()[0].getSequence() != refseq)
{
throw OpenMS::Exception::IllegalArgument(
__FILE__
, __LINE__
, __FUNCTION__
, "Consensus features may contain at most one identification. Run IDConflictResolver first to remove ambiguities!");
}
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ParamCWLFile.cpp | .cpp | 11,362 | 330 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Authors: Simon Gene Gottlieb $
// --------------------------------------------------------------------------
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/ParamCWLFile.h>
#include <fstream>
#include <iostream>
#include <limits>
#include <nlohmann/json.hpp>
#if defined(ENABLE_TDL)
#include <tdl/tdl.h>
#else
#include <stdexcept>
#endif
using json = nlohmann::json;
// replaces the substrings inside a string
// This method is 'static' so no external linkage occurs
static std::string replaceAll(std::string str, const std::string& pattern, const std::string& replacement)
{
size_t pos {0};
while ((pos = str.find(pattern, pos)) != std::string::npos)
{
str.replace(pos, pattern.size(), replacement);
pos += replacement.size();
}
return str;
}
namespace OpenMS
{
void ParamCWLFile::store(const std::string& filename, const Param& param, const ToolInfo& tool_info) const
{
std::ofstream os;
std::ostream* os_ptr;
if (filename != "-")
{
os.open(filename.c_str(), std::ofstream::out);
if (!os)
{
// Replace the OpenMS specific exception with a std exception
// Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
throw std::ios::failure("Unable to create file: " + filename);
}
os_ptr = &os;
}
else
{
os_ptr = &std::cout;
}
writeCWLToStream(os_ptr, param, tool_info);
}
void ParamCWLFile::writeCWLToStream(std::ostream* os_ptr, const Param& param, const ToolInfo& tool_info) const
{
#if defined(ENABLE_TDL)
std::ostream& os = *os_ptr;
os.precision(std::numeric_limits<double>::digits10);
tdl::ToolInfo tdl_tool_info;
tdl_tool_info.metaInfo.version = tool_info.version_;
tdl_tool_info.metaInfo.name = tool_info.name_;
tdl_tool_info.metaInfo.docurl = tool_info.docurl_;
tdl_tool_info.metaInfo.category = tool_info.category_;
tdl_tool_info.metaInfo.description = tool_info.description_;
for (auto cite : tool_info.citations_)
{
tdl::Citation tdl_citation;
tdl_citation.doi = cite;
tdl_citation.url = "";
tdl_tool_info.metaInfo.citations.push_back(tdl_citation);
}
// discover the name of the first nesting Level
// this is expected to result in something like "ToolName:1:"
auto traces = param.begin().getTrace();
std::string toolNamespace = traces.front().name + ":1:";
std::vector<tdl::Node> stack;
stack.push_back(tdl::Node {});
auto param_it = param.begin();
for (auto last = param.end(); param_it != last; ++param_it)
{
for (auto& trace : param_it.getTrace())
{
if (trace.opened)
{
// First nested param should be the executable name of the tool
if (tdl_tool_info.metaInfo.executableName.empty())
{
tdl_tool_info.metaInfo.executableName = trace.name;
}
stack.push_back(tdl::Node {trace.name, trace.description, {}, tdl::Node::Children {}});
}
else // these nodes must be closed
{
auto top = stack.back();
stack.pop_back();
auto& children = std::get<tdl::Node::Children>(stack.back().value);
children.push_back(top);
}
}
// converting OpenMS tags to tdl compatible tags
std::set<std::string> tags;
for (auto const& t : param_it->tags)
{
if (t == TOPPBase::TAG_INPUT_FILE)
{
tags.insert("file");
}
else if (t == TOPPBase::TAG_OUTPUT_FILE)
{
tags.insert("file");
tags.insert("output");
}
else if (t == TOPPBase::TAG_OUTPUT_PREFIX)
{
tags.insert("output");
tags.insert("prefixed");
}
else if (t == TOPPBase::TAG_OUTPUT_DIR)
{
tags.insert("directory");
tags.insert("output");
}
else
{
tags.insert(t);
}
}
// Sets a single value into the tdl library
auto setValue = [&](auto value) { std::get<tdl::Node::Children>(stack.back().value).push_back(tdl::Node {param_it->name, param_it->description, tags, value}); };
// Sets a value including their limits into the tdl library
auto setValueLimits = [&](auto value) {
using T = typename decltype(value.minLimit)::value_type;
if (value.minLimit == -std::numeric_limits<T>::max())
value.minLimit.reset();
if (value.maxLimit == std::numeric_limits<T>::max())
value.maxLimit.reset();
setValue(value);
};
switch (param_it->value.valueType())
{
case ParamValue::INT_VALUE:
setValueLimits(tdl::IntValue {static_cast<int>(param_it->value), param_it->min_int, param_it->max_int});
break;
case ParamValue::DOUBLE_VALUE:
setValueLimits(tdl::DoubleValue {static_cast<double>(param_it->value), param_it->min_float, param_it->max_float});
break;
case ParamValue::STRING_VALUE:
if (param_it->valid_strings.size() == 2 && param_it->valid_strings[0] == "true" && param_it->valid_strings[1] == "false" && param_it->value == "false")
{
std::get<tdl::Node::Children>(stack.back().value).push_back(tdl::Node {param_it->name, param_it->description, tags, false});
}
else
{
std::get<tdl::Node::Children>(stack.back().value)
.push_back(tdl::Node {param_it->name, param_it->description, tags, tdl::StringValue {static_cast<std::string>(param_it->value), param_it->valid_strings}});
}
break;
case ParamValue::INT_LIST: {
auto value = tdl::IntValueList {};
value.value = param_it->value.toIntVector();
value.minLimit = param_it->min_int;
value.maxLimit = param_it->max_int;
setValueLimits(value);
break;
}
case ParamValue::DOUBLE_LIST: {
auto value = tdl::DoubleValueList {};
value.value = param_it->value.toDoubleVector();
value.minLimit = param_it->min_float;
value.maxLimit = param_it->max_float;
setValueLimits(value);
break;
}
case ParamValue::STRING_LIST: {
auto value = tdl::StringValueList {};
value.value = param_it->value.toStringVector();
value.validValues = param_it->valid_strings;
auto param = tdl::Node {param_it->name, param_it->description, tags, value};
std::get<tdl::Node::Children>(stack.back().value).push_back(param);
break;
}
default:
break;
}
}
while (stack.size() > 1)
{
auto top = stack.back();
stack.pop_back();
auto& children = std::get<tdl::Node::Children>(stack.back().value);
children.push_back(top);
}
assert(stack.size() == 1);
auto allChildren = tdl::Node::Children{};
// fix naming of all children, by appending their parents name
// skipping the first two levels, since they are always the "ToolName:1:" keys
auto renameNodes = std::function<void(tdl::Node&, tdl::Node const*, int)> {};
renameNodes = [&](tdl::Node& element, tdl::Node const* parent, int level) {
if (parent != nullptr && !parent->name.empty())
{
element.name = parent->name + ":" + element.name;
}
if (auto children = std::get_if<tdl::Node::Children>(&element.value))
{
for (auto& child : *children)
{
renameNodes(child, &element, level + 1);
}
} else if (!element.name.empty()) {
allChildren.push_back(element);
}
};
renameNodes(stack.back(), nullptr, 0);
if (flatHierarchy) {
stack = allChildren;
}
// This does different things
// 1. uses a safer sign than ':' for output
// 2. strips of the toolNamespace
// 3. ignore certain options
//
// returns true if object can be removed
auto recursiveCleanup = std::function<void(tdl::Node&)> {};
recursiveCleanup = [&](tdl::Node& element) {
auto& name = element.name;
// strip of the tool namespace part and ignore entries that aren't part of the name space (like ToolName:version)
if (name.size() >= toolNamespace.size() && name.substr(0, toolNamespace.size()) == toolNamespace)
{
name = name.substr(toolNamespace.size());
}
else
{
name = "";
}
if (flatHierarchy) {
// replace all ':' with '__'
name = replaceAll(name, ":", "__");
} else {
if (auto pos = name.rfind(':'); pos != std::string::npos) {
name = name.substr(pos+1);
}
}
// cleanup recursivly
if (auto children = std::get_if<tdl::Node::Children>(&element.value))
{
for (auto& child : *children) {
recursiveCleanup(child);
}
}
};
for (auto& s : stack) {
recursiveCleanup(s);
}
// recursiveMarkingRemove
auto recursiveMarkRemove = std::function<bool(tdl::Node&)> {};
recursiveMarkRemove = [&](tdl::Node& element) -> bool {
// remove children that are marked for cleanup
if (auto children = std::get_if<tdl::Node::Children>(&element.value))
{
children->erase(std::remove_if(children->begin(), children->end(), [&](auto& child) {
return recursiveMarkRemove(child);
}),
children->end());
return children->empty() && element.name.empty();
}
return element.name.empty();
};
// Erase invalid entries
stack.erase(std::remove_if(stack.begin(), stack.end(), [&](auto& child) {
return recursiveMarkRemove(child);
}),
stack.end());
// unroll nested options, until you have some with names
while (stack.size() == 1 && stack.back().name.empty() && std::holds_alternative<tdl::Node::Children>(stack.back().value)) {
auto v = std::get<tdl::Node::Children>(stack.back().value);
stack = v;
}
tdl_tool_info.params = stack;
// Removing the fake cli methods
tdl::post_process_cwl = [&](YAML::Node node) {
node["requirements"] = YAML::Load(R"-(
InlineJavascriptRequirement: {}
InitialWorkDirRequirement:
listing:
- entryname: cwl_inputs.json
entry: $(JSON.stringify(inputs))
)-");
node["arguments"] = YAML::Load(R"-(
- -ini
- cwl_inputs.json
)-");
};
os << "# Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin\n"
"# SPDX-License-Identifier: Apache-2.0\n";
os << convertToCWL(tdl_tool_info) << "\n";
#else
throw std::runtime_error{"TDL support is not available. Rebuild with -DENABLE_TDL=ON to enable this feature."};
#endif
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/OMSSACSVFile.cpp | .cpp | 3,020 | 102 | // 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/FORMAT/OMSSACSVFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <fstream>
using namespace std;
namespace OpenMS
{
OMSSACSVFile::OMSSACSVFile() = default;
OMSSACSVFile::~OMSSACSVFile() = default;
void OMSSACSVFile::load(const String & filename, ProteinIdentification & /* protein_identification */, PeptideIdentificationList & id_data) const
{
ifstream is(filename.c_str());
if (!is)
{
if (!File::exists(filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
else if (!File::readable(filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
}
String line;
getline(is, line, '\n');
if (!line.hasPrefix("Spectrum"))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "first line does not contain a description", "");
}
// line number counter
Size line_number = 0;
// ignore first line
Int actual_spectrum_number(-1);
while (getline(is, line, '\n'))
{
++line_number;
// Spectrum number, Filename/id, Peptide, E-value, Mass, gi, Accession, Start, Stop, Defline, Mods, Charge, Theo Mass, P-value
// 1,,MSHHWGYGK,0.00336754,1101.49,0,6599,1,9,CRHU2 carbonate dehydratase (EC 4.2.1.1) II [validated] - human,,1,1101.48,1.30819e-08
line.trim();
// replace ',' in protein name
String::ConstIterator it = find(line.begin(), line.end(), '"');
UInt offset(0);
if (it != line.end())
{
while (*(++it) != '"')
{
if (*it == ',')
{
offset++;
}
}
}
vector<String> split;
line.split(',', split);
if (split.size() != 14 && split.size() != 14 + offset)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, line, "number of columns should be 14 in line " + String(line_number));
}
PeptideHit p;
p.setSequence(AASequence::fromString(split[2].trim()));
p.setScore(split[13 + offset].trim().toDouble());
p.setCharge(split[11 + offset].trim().toInt());
if (actual_spectrum_number != split[0].trim().toInt())
{
// new id
//id_data.push_back(IdentificationData());
id_data.emplace_back();
id_data.back().setScoreType("OMSSA");
actual_spectrum_number = (UInt)split[0].trim().toInt();
}
id_data.back().insertHit(p);
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ExperimentalDesignFile.cpp | .cpp | 16,827 | 466 | // 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, Lukas Zimmermann $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/FORMAT/ExperimentalDesignFile.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/ExperimentalDesign.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtCore/QFileInfo>
#include <QtCore/QString>
#include <iostream>
using namespace std;
namespace OpenMS
{
String findSpectraFile(const String &spec_file, const String &tsv_file, const bool require_spectra_files)
{
String result;
QFileInfo spectra_file_info(spec_file.toQString());
if (spectra_file_info.isRelative())
{
// file name is relative, so we need to figure out the correct folder
// first check folder relative to folder of design file
// to allow, for example, a design in ./design.tsv and spectra in ./spectra/a.mzML
// where ./ is the same folder
QFileInfo design_file_info(tsv_file.toQString());
QString design_file_relative(design_file_info.absolutePath());
design_file_relative = design_file_relative + "/" + spec_file.toQString();
if (File::exists(design_file_relative))
{
result = design_file_relative.toStdString();
}
else
{
// check current folder
String f = File::absolutePath(spec_file);
if (File::exists(f))
{
result = f;
}
}
// if result still empty, just use the provided value
if (result.empty())
{
result = spec_file;
}
}
else
{
// set to absolute path
result = spec_file;
}
// Fail if the existence of the spectra files is required but they do not exist
if (require_spectra_files && !File::exists(result))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, tsv_file,
"Error: Spectra file does not exist: '" + result + "'");
}
return result;
}
// Parse Error of filename if test holds
void ExperimentalDesignFile::parseErrorIf_(const bool test, const String &filename, const String &message)
{
if (test)
{
throw Exception::ParseError(
__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
filename,
"Error: " + message);
}
}
void ExperimentalDesignFile::parseHeader_(
const StringList &header,
const String &filename,
std::map <String, Size> &column_map,
const std::set <String> &required,
const std::set <String> &optional,
const bool allow_other_header)
{
// Headers as set
std::set <String> header_set(header.begin(), header.end());
parseErrorIf_(header_set.size() != header.size(), filename, "Some column headers of the table appear multiple times!");
// Check that all required headers are there
for (const String &req_header : required)
{
parseErrorIf_(!ListUtils::contains(header, req_header), filename, "Missing column header: " + req_header);
}
// Assign index in column map and check for weird headers
for (Size i = 0; i < header.size(); ++i)
{
const String &h = header[i];
// A header is unexpected if it is neither required nor optional and we do not allow other headers
const bool header_unexpected = (required.find(h) == required.end()) && (optional.find(h) == optional.end());
parseErrorIf_(!allow_other_header && header_unexpected, filename, "Header not allowed in this section of the Experimental Design: " + h);
column_map[h] = i;
}
}
bool ExperimentalDesignFile::isOneTableFile_(const TextFile& text_file)
{
// To determine if we have a *separate* sample table, we check if a row is present
// that contains "Sample" but no "Fraction_Group".
for (String s : text_file)
{
const String line(s.trim());
if (line.empty()) { continue; }
StringList cells;
line.split("\t", cells);
// check if we are outside of run section (no Fraction_Group column)
// but in sample section (Sample column present)
if (std::count(cells.begin(), cells.end(), "Fraction_Group") == 0
&& std::count(cells.begin(), cells.end(), "Sample") == 1)
{
return false;
}
}
return true;
}
ExperimentalDesign ExperimentalDesignFile::parseOneTableFile_(const TextFile& text_file, const String& tsv_file, bool require_spectra_file)
{
ExperimentalDesign::MSFileSection msfile_section;
bool has_sample(false);
bool has_label(false);
/// Content of the sample section (vector of rows with column contents as strings)
std::vector< std::vector < String > > sample_content_;
/// Sample name to sample (row) index
std::map< unsigned, Size > sample_sample_to_rowindex_;
/// Inside each row, the value for a column can be accessed by name with this map
std::map< String, Size > sample_columnname_to_columnindex_;
/// Maps the column header string to the column index for
/// the file section
std::map <String, Size> fs_column_header_to_index;
/// Maps the sample name to all values of sample-related columns
std::map <String, std::vector<String>> sample_content_map;
/// Maps the sample name to its index (i.e., the order how it gets added to the sample section)
std::map<String, Size> samplename_to_index;
enum ParseState { RUN_HEADER, RUN_CONTENT };
ParseState state(RUN_HEADER);
Size n_col = 0;
for (String s : text_file)
{
const String line(s.trim());
if (line.hasPrefix("#") || line.empty()) { continue; }
// Now split the line into individual cells
StringList cells;
line.split("\t", cells);
// Trim whitespace from all cells (so , foo , and ,foo, is the same)
std::transform(cells.begin(), cells.end(), cells.begin(),
[](String cell) -> String { return cell.trim(); });
if (state == RUN_HEADER)
{
state = RUN_CONTENT;
parseHeader_(
cells,
tsv_file,
fs_column_header_to_index,
{"Fraction_Group", "Fraction", "Spectra_Filepath"},
{"Label", "Sample"}, true
);
has_label = fs_column_header_to_index.find("Label") != fs_column_header_to_index.end();
has_sample = fs_column_header_to_index.find("Sample") != fs_column_header_to_index.end();
if (!has_label) // add label column to end of header
{
size_t hs = fs_column_header_to_index.size();
fs_column_header_to_index["Label"] = hs;
cells.push_back("Label");
}
if (!has_sample) // add sample column to end of header
{
size_t hs = fs_column_header_to_index.size();
fs_column_header_to_index["Sample"] = hs;
cells.push_back("Sample");
}
n_col = fs_column_header_to_index.size();
// determine columns with sample metainfo like condition or replication
for (size_t i = 0; i != cells.size(); ++i)
{
const String& c = cells[i];
if (c != "Fraction_Group" && c != "Fraction"
&& c != "Spectra_Filepath" && c != "Label")
{
sample_columnname_to_columnindex_[c] = i;
}
}
}
else if (state == RUN_CONTENT)
{
// if no label column exists -> label free
// -> add label column with label 1 at the end of every row
if (!has_label) { cells.push_back("1"); }
// Assign label
int label = cells[fs_column_header_to_index["Label"]].toInt();
int fraction = cells[fs_column_header_to_index["Fraction"]].toInt();
int fraction_group = cells[fs_column_header_to_index["Fraction_Group"]].toInt();
// read sample column
Size sample = 1;
String samplename = "";
if (!has_sample)
{
samplename = fraction_group; // deducing the sample in the case of multiplexed could be done if label > 1 information is there (e.g., max(label) * (fraction_group - 1) + label
cells.push_back(samplename);
}
samplename = cells[fs_column_header_to_index["Sample"]];
parseErrorIf_(n_col != cells.size(), tsv_file, "Wrong number of records in line");
const auto& [it, inserted] = samplename_to_index.emplace(samplename, samplename_to_index.size());
sample = it->second;
// get indices of sample metadata and store content in sample cells
StringList sample_cells;
for (const auto & c2i : sample_columnname_to_columnindex_)
{
sample_cells.push_back(cells[c2i.second]);
}
if (inserted)
{
sample_content_.push_back(sample_cells);
}
else
{
if (sample_content_[it->second] != sample_cells)
{
OPENMS_LOG_WARN << "Warning: Factors for the same sample do not match." << std::endl;
}
}
ExperimentalDesign::MSFileSectionEntry e;
// Assign fraction group and fraction
e.fraction_group = fraction_group;
e.fraction = fraction;
e.label = label;
e.sample = sample;
// Spectra files
e.path = findSpectraFile(
cells[fs_column_header_to_index["Spectra_Filepath"]],
tsv_file,
require_spectra_file);
msfile_section.push_back(e);
}
}
// Assign correct position for columns in sample section subset
// (i.e., without "Fraction_Group", "Fraction", "Spectra_Filepath", "Label")
int sample_index = 0;
for (auto & c : sample_columnname_to_columnindex_)
{
c.second = sample_index++;
}
// Create Sample Section and set in design
ExperimentalDesign::SampleSection sample_section(
sample_content_,
samplename_to_index,
sample_columnname_to_columnindex_);
// Create experimentalDesign
ExperimentalDesign design(msfile_section, sample_section);
return design;
}
ExperimentalDesign ExperimentalDesignFile::parseTwoTableFile_(const TextFile& text_file, const String& tsv_file, bool require_spectra_file)
{
ExperimentalDesign::MSFileSection msfile_section;
bool has_sample(false);
bool has_label(false);
// Attributes of the sample section
std::vector< std::vector < String > > sample_content_;
std::map< String, Size > sample_sample_to_rowindex_;
std::map< String, Size > sample_columnname_to_columnindex_;
// Maps the column header string to the column index for
// the file section
std::map <String, Size> fs_column_header_to_index;
unsigned line_number(0);
enum ParseState { RUN_HEADER, RUN_CONTENT, SAMPLE_HEADER, SAMPLE_CONTENT };
ParseState state(RUN_HEADER);
Size n_col = 0;
for (String s : text_file)
{
// skip empty lines (except in state RUN_CONTENT, where the sample table is read)
const String line(s.trim());
// also skip comment lines
if (line.hasPrefix("#") || (line.empty() && state != RUN_CONTENT))
{
continue;
}
// Now split the line into individual cells
StringList cells;
line.split("\t", cells);
// Trim whitespace from all cells (so , foo , and ,foo, is the same)
std::transform(cells.begin(), cells.end(), cells.begin(),
[](String cell) -> String { return cell.trim(); });
if (state == RUN_HEADER)
{
state = RUN_CONTENT;
parseHeader_(
cells,
tsv_file,
fs_column_header_to_index,
{"Fraction_Group", "Fraction", "Spectra_Filepath"},
{"Label", "Sample"}, false
);
has_label = fs_column_header_to_index.find("Label") != fs_column_header_to_index.end();
has_sample = fs_column_header_to_index.find("Sample") != fs_column_header_to_index.end();
n_col = fs_column_header_to_index.size();
}
// End of file section lines, empty line separates file and sample section
else if (state == RUN_CONTENT && line.empty())
{
// Next line is header of Sample table
state = SAMPLE_HEADER;
}
// Line is file section line
else if (state == RUN_CONTENT)
{
parseErrorIf_(n_col != cells.size(), tsv_file, "Wrong number of records in line");
ExperimentalDesign::MSFileSectionEntry e;
// Assign fraction group and fraction
e.fraction_group = cells[fs_column_header_to_index["Fraction_Group"]].toInt();
e.fraction = cells[fs_column_header_to_index["Fraction"]].toInt();
// Assign label
e.label = has_label ? cells[fs_column_header_to_index["Label"]].toInt() : 1;
// Assign sample number
if (has_sample)
{
//e.sample has to be filled after the sample section was read
e.sample_name = cells[fs_column_header_to_index["Sample"]];
}
else
{
e.sample = e.fraction_group; // TODO: deducing the sample in the case of multiplexed
// could be done if label > 1 information is there
// (e.g., max(label) * (fraction_group - 1) + label
e.sample_name = "Fraction group " + String(e.fraction_group);
}
// Spectra files
e.path = findSpectraFile(
cells[fs_column_header_to_index["Spectra_Filepath"]],
tsv_file,
require_spectra_file);
msfile_section.push_back(e);
}
// Parse header of the Condition Table
else if (state == SAMPLE_HEADER)
{
state = SAMPLE_CONTENT;
line_number = 0;
parseHeader_(
cells,
tsv_file,
sample_columnname_to_columnindex_,
{"Sample"}, {}, true
);
n_col = sample_columnname_to_columnindex_.size();
}
// Parse Sample Row
else if (state == SAMPLE_CONTENT)
{
// Parse Error if sample appears multiple times
const String& sample = cells[sample_columnname_to_columnindex_["Sample"]];
parseErrorIf_(sample_sample_to_rowindex_.find(sample) != sample_sample_to_rowindex_.end(),
tsv_file,
"Sample: " + String(sample) + " appears multiple times in the sample table");
sample_sample_to_rowindex_[sample] = line_number++;
sample_content_.push_back(cells);
}
}
for (auto& e : msfile_section)
{
e.sample = sample_sample_to_rowindex_.at(e.sample_name);
}
// Create Sample Section and set in design
ExperimentalDesign::SampleSection sample_section(
sample_content_,
sample_sample_to_rowindex_,
sample_columnname_to_columnindex_);
// Create experimentalDesign
ExperimentalDesign design(msfile_section, sample_section);
return design;
}
// static
ExperimentalDesign ExperimentalDesignFile::load(const TextFile &text_file, const bool require_spectra_file, String filename = "--no design file provided--")
{
// check if we have information stored in one or two files
bool has_one_table = isOneTableFile_(text_file);
if (has_one_table)
{
return parseOneTableFile_(text_file, filename, require_spectra_file);
}
else // two tables
{
return parseTwoTableFile_(text_file, filename, require_spectra_file);
}
}
ExperimentalDesign ExperimentalDesignFile::load(const String &tsv_file, const bool require_spectra_file)
{
const TextFile text_file(tsv_file, true);
return load(text_file, require_spectra_file, tsv_file);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/UnimodXMLFile.cpp | .cpp | 921 | 36 | // 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/FORMAT/UnimodXMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/UnimodXMLHandler.h>
#include <OpenMS/SYSTEM/File.h>
using namespace xercesc;
using namespace std;
namespace OpenMS
{
UnimodXMLFile::UnimodXMLFile() :
Internal::XMLFile()
{
}
UnimodXMLFile::~UnimodXMLFile() = default;
void UnimodXMLFile::load(const String& filename, vector<ResidueModification*> & modifications)
{
String file = File::find(filename);
Internal::UnimodXMLHandler handler(modifications, file);
parse_(file, &handler);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/FLASHDeconvSpectrumFile.cpp | .cpp | 22,729 | 614 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Kyowon Jeong$
// $Authors: Kyowon Jeong $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/FLASHDeconvSpectrumFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <random>
namespace OpenMS
{
/**
* @brief FLASHDeconv Spectrum level output *.tsv, *.msalign (for TopPIC) file formats
@ingroup FileIO
*/
inline std::default_random_engine generator_;
inline std::uniform_real_distribution<double> distribution_(0.0,1.0);
void FLASHDeconvSpectrumFile::writeDeconvolvedMasses(const DeconvolvedSpectrum& dspec, std::ostream& os, const String& file_name, const FLASHHelperClasses::PrecalculatedAveragine& avg, const FLASHHelperClasses::PrecalculatedAveragine& decoy_avg, double tol,
const bool write_detail, const bool report_decoy, const double noise_decoy_weight)
{
if (!report_decoy && dspec.isDecoy()) return;
static std::vector<uint> indices {};
std::stringstream ss;
if (dspec.empty())
{
return;
}
while (indices.size() <= dspec.getOriginalSpectrum().getMSLevel())
{
indices.push_back(1);
}
uint& index = indices[dspec.getOriginalSpectrum().getMSLevel() - 1];
std::stringstream precursor_ss;
if (dspec.getOriginalSpectrum().getMSLevel() > 1)
{
precursor_ss << dspec.getPrecursorScanNumber() << "\t"
<< (dspec.getPrecursorPeakGroup().getFeatureIndex() == 0 ? "nan" : std::to_string(dspec.getPrecursorPeakGroup().getFeatureIndex()))
<< "\t" << std::to_string(dspec.getPrecursor().getMZ()) << "\t" << dspec.getPrecursor().getIntensity() << "\t"
<< dspec.getPrecursor().getCharge() << "\t";
if (dspec.getPrecursorPeakGroup().empty())
{
precursor_ss << "nan\tnan\tnan\tnan\t";
if (report_decoy) precursor_ss << "nan\t";
}
else
{
precursor_ss << dspec.getPrecursorPeakGroup().getChargeSNR(dspec.getPrecursor().getCharge()) << "\t"
<< std::to_string(dspec.getPrecursorPeakGroup().getMonoMass()) << "\t"
<< std::to_string(dspec.getPrecursorPeakGroup().getQscore()) << "\t" << dspec.getPrecursorPeakGroup().getQscore2D() << "\t";
if (report_decoy) { precursor_ss << dspec.getPrecursorPeakGroup().getQvalue() << "\t"; }
}
}
for (Size i = 0; i < dspec.size(); i++)
{
const auto& pg = dspec[i];
if (!report_decoy && pg.getTargetDecoyType() != PeakGroup::TargetDecoyType::target) continue;
if (pg.getTargetDecoyType() == PeakGroup::TargetDecoyType::noise_decoy)
{
double number = distribution_(generator_);
if (number > noise_decoy_weight)
{
continue;
}
// Note: removed i-- logic as it doesn't work well with const iteration
// The random sampling behavior is preserved by the continue above
}
const auto& avg_ = pg.getTargetDecoyType() == PeakGroup::TargetDecoyType::noise_decoy? decoy_avg : avg;
const double mono_mass = pg.getMonoMass();
const double avg_mass = pg.getMonoMass() + avg_.getAverageMassDelta(mono_mass);
const double intensity = pg.getIntensity();
const auto& charge_range = pg.getAbsChargeRange();
int min_charge = pg.isPositive() ? std::get<0>(charge_range) : -std::get<1>(charge_range);
int max_charge = pg.isPositive() ? std::get<1>(charge_range) : -std::get<0>(charge_range);
// Output the current index (no need to store it in the PeakGroup)
ss << index++ << "\t" << file_name << "\t" << pg.getScanNumber() << "\t" << (pg.getFeatureIndex() == 0 ? "nan" : std::to_string(pg.getFeatureIndex())) << "\t";
if (report_decoy)
{
ss << pg.getTargetDecoyType() << "\t";
}
ss << std::to_string(dspec.getOriginalSpectrum().getRT()/60.0) << "\t" << dspec.size() << "\t" << std::to_string(avg_mass) << "\t" << std::to_string(mono_mass) << "\t" << intensity << "\t"
<< min_charge << "\t" << max_charge << "\t" << pg.size() << "\t";
if (write_detail)
{
// Use const getNoisyPeaks instead of non-const recruitAllPeaksInSpectrum
auto noisy_peaks = pg.getNoisyPeaks(dspec.getOriginalSpectrum(), tol * 1e-6, avg_);
std::sort(noisy_peaks.begin(), noisy_peaks.end());
ss << std::fixed << std::setprecision(2);
for (const auto& p : pg)
{
ss << std::to_string(p.mz) << " ";
}
ss << "\t";
ss << std::fixed << std::setprecision(1);
for (const auto& p : pg)
{
ss << p.intensity << " ";
}
ss << "\t";
ss << std::setprecision(-1);
for (const auto& p : pg)
{
ss << (p.is_positive ? p.abs_charge : -p.abs_charge) << " ";
}
ss << "\t";
for (const auto& p : pg)
{
ss << p.getUnchargedMass() << " ";
}
ss << "\t";
for (const auto& p : pg)
{
ss << p.isotopeIndex << " ";
}
ss << "\t";
ss << std::setprecision(2);
for (const auto& p : pg)
{
double average_mass = pg.getMonoMass() + p.isotopeIndex * pg.getIsotopeDaDistance();
double mass_error = (average_mass / p.abs_charge + FLASHHelperClasses::getChargeMass(p.is_positive) - p.mz) / p.mz;
ss << 1e6 * mass_error << " ";
}
ss << std::setprecision(-1);
ss << "\t";
ss << std::fixed << std::setprecision(2);
for (const auto& np : noisy_peaks)
{
ss << std::to_string(np.mz) << " ";
}
ss << "\t";
ss << std::fixed << std::setprecision(1);
for (const auto& np : noisy_peaks)
{
ss << np.intensity << " ";
}
ss << "\t";
ss << std::setprecision(-1);
for (const auto& np : noisy_peaks)
{
ss << (np.is_positive ? np.abs_charge : -np.abs_charge) << " ";
}
ss << "\t";
for (const auto& np : noisy_peaks)
{
ss << np.getUnchargedMass() << " ";
}
ss << "\t";
for (const auto& np : noisy_peaks)
{
ss << np.isotopeIndex << " ";
}
ss << "\t";
ss << std::setprecision(2);
for (const auto& np : noisy_peaks)
{
double average_mass = pg.getMonoMass() + np.isotopeIndex * pg.getIsotopeDaDistance();
double mass_error = (average_mass / np.abs_charge + FLASHHelperClasses::getChargeMass(np.is_positive) - np.mz) / np.mz;
ss << 1e6 * mass_error << " ";
}
ss << std::setprecision(-1);
ss << "\t";
}
if (dspec.getOriginalSpectrum().getMSLevel() > 1)
{
ss << precursor_ss.str();
}
ss << pg.getIsotopeCosine() << "\t" << pg.getChargeIsotopeCosine(pg.getRepAbsCharge()) << "\t" << pg.getChargeScore() << "\t";
const auto& max_qscore_mz_range = pg.getRepMzRange();
ss << pg.getSNR() << "\t" << pg.getChargeSNR(pg.getRepAbsCharge()) << "\t" << pg.getAvgPPMError() << "\t" << (pg.isPositive() ? pg.getRepAbsCharge() : -pg.getRepAbsCharge()) << "\t"
<< std::to_string(std::get<0>(max_qscore_mz_range)) << "\t" << std::to_string(std::get<1>(max_qscore_mz_range)) << "\t" << std::to_string(pg.getQscore()) << "\t"
<< std::to_string(pg.getQscore2D());
if (report_decoy)
{
ss << "\t" << pg.getQvalue();
}
if (write_detail)
{
ss << "\t" << std::setprecision(-1);
for (int j = min_charge; j <= max_charge; j++)
{
ss << pg.getChargeIntensity(j);
if (j < max_charge)
{
ss << ";";
}
}
ss << "\t";
const auto& iso_intensities = pg.getIsotopeIntensities();
for (size_t j = 0; j < iso_intensities.size(); j++)
{
ss << iso_intensities[j];
if (j < iso_intensities.size() - 1)
{
ss << ";";
}
}
}
ss << "\n";
}
os << ss.str();
}
void FLASHDeconvSpectrumFile::writeDeconvolvedMassesHeader(std::ostream& os, const uint ms_level, const bool detail, const bool report_decoy)
{
if (detail)
{
if (ms_level == 1)
{
os << "Index\tFileName\tScanNum\tFeatureIndex\t";
if (report_decoy)
{
os << "TargetDecoyType\t";
}
os << "RetentionTime\tMassCountInSpec\tAverageMass\tMonoisotopicMass\t"
"SumIntensity\tMinCharge\tMaxCharge\t"
"PeakCount\tPeakMZs\tPeakIntensities\tPeakCharges\tPeakMasses\tPeakIsotopeIndices\tPeakPPMErrors\t"
"NoisePeakMZs\tNoisePeakIntensities\tNoisePeakCharges\tNoisePeakMasses\tNoisePeakIsotopeIndices\tNoisePeakPPMErrors\t"
"IsotopeCosine\tChargeCosine\tChargeScore\tMassSNR\tChargeSNR\tAveragePPMError\tRepresentativeCharge\tRepresentativeMzStart\tRepresentativeMzEnd\tQscore\tQscore2D\t";
if (report_decoy)
{
os << "Qvalue\t";
}
os << "PerChargeIntensity\tPerIsotopeIntensity\n";
}
else
{
os << "Index\tFileName\tScanNum\tFeatureIndex\t";
if (report_decoy)
{
os << "TargetDecoyType\t";
}
os << "RetentionTime\tMassCountInSpec\tAverageMass\tMonoisotopicMass\t"
"SumIntensity\tMinCharge\tMaxCharge\t"
"PeakCount\tPeakMZs\tPeakIntensities\tPeakCharges\tPeakMasses\tPeakIsotopeIndices\tPeakPPMErrors\t"
"NoisePeakMZs\tNoisePeakIntensities\tNoisePeakCharges\tNoisePeakMasses\tNoisePeakIsotopeIndices\tNoisePeakPPMErrors\t"
"PrecursorScanNum\tPrecursorFeatureIndex\tPrecursorMz\tPrecursorIntensity\tPrecursorCharge\tPrecursorSNR\tPrecursorMonoisotopicMass\tPrecursorQscore\tPrecursorQscore2D\t";
if (report_decoy)
{
os << "PrecursorQvalue\t";
}
os << "IsotopeCosine\tChargeCosine\tChargeScore\tMassSNR\tChargeSNR\tAveragePPMError\tRepresentativeCharge\tRepresentativeMzStart\tRepresentativeMzEnd\tQscore\tQscore2D\t";
if (report_decoy)
{
os << "Qvalue\t";
}
os << "PerChargeIntensity\tPerIsotopeIntensity\n";
}
}
else
{
if (ms_level == 1)
{
os << "Index\tFileName\tScanNum\tFeatureIndex\t";
if (report_decoy)
{
os << "TargetDecoyType\t";
}
os << "RetentionTime\tMassCountInSpec\tAverageMass\tMonoisotopicMass\t"
"SumIntensity\tMinCharge\tMaxCharge\t"
"PeakCount\t"
"IsotopeCosine\tChargeCosine\tChargeScore\tMassSNR\tChargeSNR\tAveragePPMError\tRepresentativeCharge\tRepresentativeMzStart\tRepresentativeMzEnd\tQscore\tQscore2D\t";
if (report_decoy)
{
os << "Qvalue";
}
os << "\n";
}
else
{
os << "Index\tFileName\tScanNum\tFeatureIndex\t";
if (report_decoy)
{
os << "TargetDecoyType\t";
}
os << "RetentionTime\tMassCountInSpec\tAverageMass\tMonoisotopicMass\t"
"SumIntensity\tMinCharge\tMaxCharge\t"
"PeakCount\t"
"PrecursorScanNum\tPrecursorFeatureIndex\tPrecursorMz\tPrecursorIntensity\tPrecursorCharge\tPrecursorSNR\tPrecursorMonoisotopicMass\tPrecursorQscore\tPrecursorQscore2D\t";
if (report_decoy)
{
os << "PrecursorQvalue\t";
}
os << "IsotopeCosine\tChargeCosine\tChargeScore\tMassSNR\tChargeSNR\tAveragePPMError\tRepresentativeCharge\tRepresentativeMzStart\tRepresentativeMzEnd\tQscore\tQscore2D\t";
if (report_decoy)
{
os << "Qvalue\t";
}
os << "\n";
}
}
}
void FLASHDeconvSpectrumFile::writeIsobaricQuantification(std::ostream& os, std::vector<DeconvolvedSpectrum>& deconvolved_spectra)
{
std::stringstream ss;
ss << "Scan\tPrecursorScan\tPrecursorMZ\tRetentionTime\tMassCountInSpec\tQuantifiedChannelCount\tPrecursorQscore\tActivation\tActivationEnergy"
"\tPrecursorCharge\tIsolationLeft\tIsolationRight\tPrecursorMass\tPrecursorSNR";
Size channel_count = 0;
for (auto& dspec : deconvolved_spectra)
{
if (dspec.isDecoy() || dspec.getOriginalSpectrum().getMSLevel() == 1)
continue;
auto quant = dspec.getQuantities();
if (!quant.empty())
{
channel_count = quant.quantities.size();
for (Size i = 0; i < quant.quantities.size(); i++)
{
ss << "\tQuantForCh" << (i + 1);
}
for (Size i = 0; i < quant.quantities.size(); i++)
{
ss << "\tNormalizedQuantForCh" << (i + 1);
}
for (Size i = 0; i < quant.quantities.size(); i++)
{
ss << "\tMergedQuantForCh" << (i + 1);
}
for (Size i = 0; i < quant.quantities.size(); i++)
{
ss << "\tNormalizedMergedQuantForCh" << (i + 1);
}
ss << "\n";
break;
}
}
if (channel_count == 0)
{
os << ss.str();
return;
}
for (auto& dspec : deconvolved_spectra)
{
bool precursor_found = ! dspec.getPrecursorPeakGroup().empty();
if (dspec.isDecoy() || dspec.getOriginalSpectrum().getMSLevel() == 1) continue;
int scan = dspec.getScanNumber();
auto quant = dspec.getQuantities();
// if (quant.empty())
// continue;
int ch_count = 0;
for (auto q : quant.quantities) if (q != 0) ch_count++;
ss << scan << "\t" << dspec.getPrecursorScanNumber() << "\t" << dspec.getPrecursor().getMZ() << "\t" << dspec.getOriginalSpectrum().getRT()
<< "\t" << dspec.size() << "\t" << ch_count << "\t" << (precursor_found ? std::to_string(dspec.getPrecursorPeakGroup().getQscore2D()) : "NaN") << "\t"
<< (dspec.getActivationMethod() < Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD
? Precursor::NamesOfActivationMethodShort[static_cast<Size>(dspec.getActivationMethod())]
: "N/A")
<< "\t" << dspec.getPrecursor().getActivationEnergy() << "\t" << dspec.getPrecursor().getCharge() << "\t"
<< dspec.getPrecursor().getMZ() - dspec.getPrecursor().getIsolationWindowLowerOffset() << "\t"
<< dspec.getPrecursor().getMZ() + dspec.getPrecursor().getIsolationWindowUpperOffset() << "\t"
<< (precursor_found ? std::to_string(dspec.getPrecursorPeakGroup().getMonoMass()) : "NaN") << "\t"
<< (precursor_found ? std::to_string(dspec.getPrecursorPeakGroup().getChargeSNR(dspec.getPrecursorCharge())) : "NaN");
double sum = 0;
if (quant.empty())
{
for (Size i = 0; i < channel_count * 4; i++)
{
ss << "\t" << 0;
}
ss << "\n";
}
else
{
for (auto q : quant.quantities)
{
ss << "\t" << std::to_string(q);
sum += q;
}
for (auto q : quant.quantities)
{
ss << "\t" << std::to_string(q / sum);
}
sum = 0;
for (auto q : quant.merged_quantities)
{
ss << "\t" << std::to_string(q);
sum += q;
}
for (auto q : quant.merged_quantities)
{
ss << "\t" << std::to_string(q / sum);
}
ss << "\n";
}
}
os << ss.str();
}
void FLASHDeconvSpectrumFile::writeMzML(const MSExperiment& map, std::vector<DeconvolvedSpectrum>& deconvolved_spectra, const String& deconvolved_mzML_file, const String& annotated_mzML_file,
int mzml_charge, DoubleList tols)
{
if (deconvolved_mzML_file.empty() && annotated_mzML_file.empty())
return;
MSExperiment deconvolved_map;
MSExperiment annotated_map;
if (!deconvolved_mzML_file.empty())
{
deconvolved_map = MSExperiment(map);
deconvolved_map.clear(false);
}
if (!annotated_mzML_file.empty())
{
annotated_map = MSExperiment(map);
annotated_map.clear(false);
}
for (auto & deconvolved_spectrum : deconvolved_spectra)
{
if (deconvolved_spectrum.empty()) continue;
if (deconvolved_spectrum.isDecoy()) continue;
auto deconvolved_mzML = deconvolved_spectrum.toSpectrum(mzml_charge, tols[deconvolved_spectrum.getOriginalSpectrum().getMSLevel() - 1], false);
if (!deconvolved_mzML_file.empty())
{
if (deconvolved_mzML.empty())
continue;
deconvolved_map.addSpectrum(deconvolved_mzML);
}
if (!annotated_mzML_file.empty())
{
auto anno_spec = MSSpectrum(deconvolved_spectrum.getOriginalSpectrum());
anno_spec.sortByPosition();
if (anno_spec.empty()) continue;
std::stringstream val {};
for (auto& pg : deconvolved_spectrum)
{
if (pg.empty() || pg.getTargetDecoyType() != PeakGroup::TargetDecoyType::target)
{
continue;
}
val << std::to_string(pg.getMonoMass()) << ":";
size_t pindex = 0;
for (size_t k = 0; k < pg.size(); k++)
{
auto& p = pg[k];
// Increment the pindex while it points to values less than p.mz
while (pindex < anno_spec.size() - 1 && anno_spec[pindex].getMZ() < p.mz)
{
pindex++;
}
size_t nearest_index = pindex;
if (anno_spec[pindex].getMZ() != p.mz)
{
if (pindex > 0 && std::abs(anno_spec[pindex - 1].getMZ() - p.mz) < std::abs(anno_spec[pindex].getMZ() - p.mz))
{
nearest_index = pindex - 1;
}
}
val << nearest_index;
if (k < pg.size() - 1)
{
val << ",";
}
}
val << ";";
}
anno_spec.setMetaValue("DeconvMassPeakIndices", val.str());
annotated_map.addSpectrum(anno_spec);
}
}
if (!deconvolved_mzML_file.empty())
{
MzMLFile mzml_file;
mzml_file.store(deconvolved_mzML_file, deconvolved_map);
}
if (!annotated_mzML_file.empty())
{
MzMLFile mzml_file;
mzml_file.store(annotated_mzML_file, annotated_map);
}
}
void FLASHDeconvSpectrumFile::writeTopFDHeader(std::ostream& os, const Param& param)
{
os << "#FLASHDeconv generated msalign file\n";
os << "####################### Parameters ######################\n";
for (const auto& p : param)
{
os << "#" << p.name << ": " << p.value << "\n";
}
os << "####################### Parameters ######################\n";
}
void FLASHDeconvSpectrumFile::writeTopFD(const DeconvolvedSpectrum& dspec, std::ostream& os, const String& filename, double qval_threshold, uint min_ms_level,
bool randomize_precursor_mass, bool randomize_fragment_mass)
{
std::stringstream ss;
UInt ms_level = dspec.getOriginalSpectrum().getMSLevel();
if (ms_level > min_ms_level)
{
if (dspec.getPrecursorPeakGroup().empty() ||
dspec.getPrecursorPeakGroup().getQvalue() > qval_threshold)
{
return;
}
}
if (dspec.size() < topFD_min_peak_count_)
{
return;
}
ss << std::fixed << std::setprecision(2);
ss << "BEGIN IONS\n"
<< "FILE_NAME=" << filename << "\n"
<< "SPECTRUM_ID=" << dspec.getScanNumber() - 1 << "\n"
<< "TITLE=" << (dspec.isDecoy()? "DScan_" : "Scan_") << dspec.getScanNumber() << "\n"
<< "SCANS=" << dspec.getScanNumber() << "\n"
<< "RETENTION_TIME=" << dspec.getOriginalSpectrum().getRT() << "\n"
<< "LEVEL=" << dspec.getOriginalSpectrum().getMSLevel() << "\n";
if (ms_level > 1)
{
double precursor_mass = dspec.getPrecursorPeakGroup().getMonoMass();
ss << "MS_ONE_ID=" << dspec.getPrecursorScanNumber() - 1 << "\n"
<< "MS_ONE_SCAN=" << dspec.getPrecursorScanNumber() << "\n"
<< "PRECURSOR_WINDOW_BEGIN=" << -dspec.getPrecursor().getIsolationWindowLowerOffset() + dspec.getPrecursor().getMZ() << "\n"
<< "PRECURSOR_WINDOW_END=" << dspec.getPrecursor().getIsolationWindowUpperOffset() + dspec.getPrecursor().getMZ() << "\n";
if (static_cast<size_t>(dspec.getActivationMethod()) < static_cast<size_t>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD))
{
ss << "ACTIVATION=" << Precursor::NamesOfActivationMethodShort[static_cast<size_t>(dspec.getActivationMethod())] << "\n";
}
ss << "PRECURSOR_MZ=" << std::to_string(dspec.getPrecursor().getMZ()) << "\n"
<< "PRECURSOR_CHARGE=" << (int)(dspec.getPrecursorCharge()) << "\n"
<< "PRECURSOR_MASS=" << std::to_string(precursor_mass + (randomize_precursor_mass ? (((double)rand() / (RAND_MAX)) * 200.0 - 100.0) : .0)) << "\n" // random number between 0 and 100.
<< "PRECURSOR_INTENSITY=" << dspec.getPrecursor().getIntensity() << "\n"
<< "PRECURSOR_FEATURE_ID=" << dspec.getPrecursorPeakGroup().getFeatureIndex() << "\n"
<< "PRECURSOR_QSCORE=" << dspec.getPrecursorPeakGroup().getQscore2D() << "\n";
}
ss << std::setprecision(-1);
double qscore_threshold = 0;
std::vector<double> qscores;
if (dspec.size() > topFD_max_peak_count_) // max peak count for TopPic = 500
{
qscores.reserve(dspec.size());
for (const auto& pg : dspec)
{
qscores.push_back(pg.getQscore2D());
}
std::sort(qscores.begin(), qscores.end());
qscore_threshold = qscores[qscores.size() - topFD_max_peak_count_];
std::vector<double>().swap(qscores);
}
int size = 0;
for (const auto& pg : dspec)
{
if (pg.getQscore2D() < qscore_threshold || pg.getTargetDecoyType() != PeakGroup::TargetDecoyType::target)
{
continue;
}
ss << std::fixed << std::setprecision(2);
ss << std::to_string(pg.getMonoMass() + (randomize_fragment_mass ? (((double)rand() / (RAND_MAX)) * 200.0 - 100.0) : .0)) << "\t" << pg.getIntensity() << "\t"
<< (pg.isPositive() ? std::get<1>(pg.getAbsChargeRange()) : -std::get<1>(pg.getAbsChargeRange())) << "\n";
ss << std::setprecision(-1);
if (++size >= topFD_max_peak_count_)
{
break;
}
}
ss << "END IONS\n\n";
os << ss.str();
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ToolDescriptionFile.cpp | .cpp | 1,235 | 38 | // 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/FORMAT/ToolDescriptionFile.h>
#include <OpenMS/FORMAT/CVMappingFile.h>
#include <OpenMS/FORMAT/HANDLERS/ToolDescriptionHandler.h>
namespace OpenMS
{
ToolDescriptionFile::ToolDescriptionFile() :
XMLFile("/SCHEMAS/ToolDescriptor_1_0.xsd", "1.0.0")
{
}
ToolDescriptionFile::~ToolDescriptionFile() = default;
void ToolDescriptionFile::load(const String & filename, std::vector<Internal::ToolDescription> & tds)
{
Internal::ToolDescriptionHandler handler(filename, schema_version_);
parse_(filename, &handler);
tds = handler.getToolDescriptions();
}
void ToolDescriptionFile::store(const String & filename, const std::vector<Internal::ToolDescription> & tds) const
{
Internal::ToolDescriptionHandler handler(filename, schema_version_);
handler.setToolDescriptions(tds);
save_(filename, &handler);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/EDTAFile.cpp | .cpp | 10,442 | 334 | // 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/FORMAT/EDTAFile.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/KERNEL/FeatureMap.h>
using namespace std;
namespace OpenMS
{
EDTAFile::EDTAFile() = default;
EDTAFile::~EDTAFile() = default;
double EDTAFile::checkedToDouble_(const std::vector<String>& parts, Size index, double def)
{
if (index < parts.size() && parts[index] != "NA")
{
return parts[index].toDouble();
}
return def;
}
Int EDTAFile::checkedToInt_(const std::vector<String>& parts, Size index, Int def)
{
if (index < parts.size() && parts[index] != "NA")
{
return parts[index].toInt();
}
return def;
}
void EDTAFile::load(const String& filename, ConsensusMap& consensus_map)
{
// load input
TextFile input(filename);
TextFile::ConstIterator input_it = input.begin();
// reset map
consensus_map = ConsensusMap();
consensus_map.setUniqueId();
char separator = ' ';
if (input_it->hasSubstring("\t"))
{
separator = '\t';
}
else if (input_it->hasSubstring(" "))
{
separator = ' ';
}
else if (input_it->hasSubstring(","))
{
separator = ',';
}
// parsing header line
std::vector<String> headers;
input_it->split(separator, headers);
int offset = 0;
for (Size i = 0; i < headers.size(); ++i)
{
headers[i].trim();
}
String header_trimmed = *input.begin();
header_trimmed.trim();
enum
{
TYPE_UNDEFINED,
TYPE_OLD_NOCHARGE,
TYPE_OLD_CHARGE,
TYPE_CONSENSUS
}
input_type = TYPE_UNDEFINED;
Size input_features = 1;
double rt = 0.0;
double mz = 0.0;
double it = 0.0;
Int ch = 0;
if (headers.size() <= 2)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", String("Failed parsing in line 1: not enough columns! Expected at least 3 columns!\nOffending line: '") + header_trimmed + "' (line 1)\n");
}
else if (headers.size() == 3)
{
input_type = TYPE_OLD_NOCHARGE;
}
else if (headers.size() == 4)
{
input_type = TYPE_OLD_CHARGE;
}
// see if we have a header
try
{
// try to convert... if not: that's a header
rt = headers[0].toDouble();
mz = headers[1].toDouble();
it = headers[2].toDouble();
}
catch (Exception::BaseException&)
{
offset = 1;
++input_it;
OPENMS_LOG_INFO << "Detected a header line.\n";
}
if (headers.size() >= 5)
{
if (String(headers[4].trim()).toUpper() == "RT1")
{
input_type = TYPE_CONSENSUS;
}
else
{
input_type = TYPE_OLD_CHARGE;
}
}
if (input_type == TYPE_CONSENSUS)
{
// Every consensus style line includes features with four columns.
// The remainder is meta data
input_features = headers.size() / 4;
}
if (offset == 0 && (input_type == TYPE_OLD_CHARGE || input_type == TYPE_CONSENSUS))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", String("Failed parsing in line 1: No HEADER provided. This is only allowed for three columns. You have more!\nOffending line: '") + header_trimmed + "' (line 1)\n");
}
SignedSize input_size = input.end() - input.begin();
ConsensusMap::ColumnHeader desc;
desc.filename = filename;
desc.size = (input_size) - offset;
consensus_map.getColumnHeaders()[0] = desc;
// parsing features
consensus_map.reserve(input_size);
for (; input_it != input.end(); ++input_it)
{
//do nothing for empty lines
String line_trimmed = *input_it;
line_trimmed.trim();
if (line_trimmed.empty())
{
if ((input_it - input.begin()) < input_size - 1) OPENMS_LOG_WARN << "Notice: Empty line ignored (line " << ((input_it - input.begin()) + 1) << ").";
continue;
}
//split line to tokens
std::vector<String> parts;
input_it->split(separator, parts);
//abort if line does not contain enough fields
if (parts.size() < 3)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "",
String("Failed parsing in line ")
+ String((input_it - input.begin()) + 1)
+ ": At least three columns are needed! (got "
+ String(parts.size())
+ ")\nOffending line: '"
+ line_trimmed
+ "' (line "
+ String((input_it - input.begin()) + 1)
+ ")\n");
}
ConsensusFeature cf;
cf.setUniqueId();
try
{
// Convert values. Will return -1 if not available.
rt = checkedToDouble_(parts, 0);
mz = checkedToDouble_(parts, 1);
it = checkedToDouble_(parts, 2);
ch = checkedToInt_(parts, 3);
cf.setRT(rt);
cf.setMZ(mz);
cf.setIntensity(it);
if (input_type != TYPE_OLD_NOCHARGE)
cf.setCharge(ch);
}
catch (Exception::BaseException&)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", String("Failed parsing in line ") + String((input_it - input.begin()) + 1) + ": Could not convert the first three columns to a number!\nOffending line: '" + line_trimmed + "' (line " + String((input_it - input.begin()) + 1) + ")\n");
}
// Check all features in one line
for (Size j = 1; j < input_features; ++j)
{
try
{
Feature f;
f.setUniqueId();
// Convert values. Will return -1 if not available.
rt = checkedToDouble_(parts, j * 4 + 0);
mz = checkedToDouble_(parts, j * 4 + 1);
it = checkedToDouble_(parts, j * 4 + 2);
ch = checkedToInt_(parts, j * 4 + 3);
// Only accept features with at least RT and MZ set
if (rt != -1 && mz != -1)
{
f.setRT(rt);
f.setMZ(mz);
f.setIntensity(it);
f.setCharge(ch);
cf.insert(j - 1, f);
}
}
catch (Exception::BaseException&)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", String("Failed parsing in line ") + String((input_it - input.begin()) + 1) + ": Could not convert one of the four sub-feature columns (starting at column " + (j * 4 + 1) + ") to a number! Is the correct separator specified?\nOffending line: '" + line_trimmed + "' (line " + String((input_it - input.begin()) + 1) + ")\n");
}
}
//parse meta data
for (Size j = input_features * 4; j < parts.size(); ++j)
{
String part_trimmed = parts[j];
part_trimmed.trim();
if (!part_trimmed.empty())
{
//check if column name is ok
if (headers.size() <= j || headers[j].empty())
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "",
String("Error: Missing meta data header for column ") + (j + 1) + "!"
+ String("Offending header line: '") + header_trimmed + "' (line 1)");
}
//add meta value
cf.setMetaValue(headers[j], part_trimmed);
}
}
//insert feature to map
consensus_map.push_back(cf);
}
// register ColumnHeaders
ConsensusMap::ColumnHeader fd;
fd.filename = filename;
fd.size = consensus_map.size();
Size maps = std::max(input_features - 1, Size(1)); // its either a simple feature or a consensus map
// (in this case the 'input_features' includes the centroid, which we do not count)
for (Size i = 0; i < maps; ++i)
{
fd.label = String("EDTA_Map ") + String(i);
consensus_map.getColumnHeaders()[i] = fd;
}
}
void EDTAFile::store(const String& filename, const ConsensusMap& map) const
{
if (!FileHandler::hasValidExtension(filename, FileTypes::EDTA))
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "invalid file extension, expected '" + FileTypes::typeToName(FileTypes::EDTA) + "'");
}
TextFile tf;
// search for maximum number of sub-features (since this determines the number of columns)
Size max_sub(0);
for (Size i = 0; i < map.size(); ++i)
{
max_sub = std::max(max_sub, map[i].getFeatures().size());
}
// write header
String header("RT\tm/z\tintensity\tcharge");
for (Size i = 1; i <= max_sub; ++i)
{
header += "\tRT" + String(i) + "\tm/z" + String(i) + "\tintensity" + String(i) + "\tcharge" + String(i);
}
tf.addLine(header);
for (Size i = 0; i < map.size(); ++i)
{
ConsensusFeature f = map[i];
// consensus
String entry = String(f.getRT()) + "\t" + f.getMZ() + "\t" + f.getIntensity() + "\t" + f.getCharge();
// sub-features
const ConsensusFeature::HandleSetType& handle = f.getFeatures();
for (ConsensusFeature::HandleSetType::const_iterator it = handle.begin(); it != handle.end(); ++it)
{
entry += String("\t") + it->getRT() + "\t" + it->getMZ() + "\t" + it->getIntensity() + "\t" + it->getCharge();
}
// missing sub-features
for (Size j = handle.size(); j < max_sub; ++j)
{
entry += "\tNA\tNA\tNA\tNA";
}
tf.addLine(entry);
}
tf.store(filename);
}
void EDTAFile::store(const String& filename, const FeatureMap& map) const
{
TextFile tf;
tf.addLine("RT\tm/z\tintensity\tcharge");
for (Size i = 0; i < map.size(); ++i)
{
const Feature& f = map[i];
tf.addLine(String(f.getRT()) + "\t" + f.getMZ() + "\t" + f.getIntensity() + "\t" + f.getCharge());
}
tf.store(filename);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MzQCFile.cpp | .cpp | 9,982 | 279 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Axel Walter $
// $Authors: Axel Walter $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/MzQCFile.h>
#include <OpenMS/FORMAT/ControlledVocabulary.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/DATASTRUCTURES/DateTime.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/QC/TIC.h>
#include <OpenMS/QC/SpectrumCount.h>
#include <OpenMS/QC/FeatureSummary.h>
#include <OpenMS/QC/IdentificationSummary.h>
#include <nlohmann/json.hpp>
#include <map>
#include <fstream>
using namespace std;
namespace OpenMS
{
void MzQCFile::store(const String& input_file,
const String& output_file,
const MSExperiment& exp,
const String& contact_name,
const String& contact_address,
const String& description,
const String& label,
const FeatureMap& feature_map,
vector<ProteinIdentification>& prot_ids,
PeptideIdentificationList& pep_ids) const
{
// --------------------------------------------------------------------
// preparing output stream, quality metrics json object, CV, status
// and initialize QC metric classes
// --------------------------------------------------------------------
ofstream os(output_file.c_str());
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, output_file);
}
using json = nlohmann::ordered_json;
json quality_metrics = {};
ControlledVocabulary cv;
cv.loadFromOBO("PSI-MS", File::find("/CV/psi-ms.obo"));
cv.loadFromOBO("QC", File::find("/CV/qc-cv.obo"));
QCBase::Status status;
if (!input_file.empty())
{
status |= QCBase::Requires::RAWMZML;
}
if (!feature_map.empty())
{
status |= QCBase::Requires::PREFDRFEAT;
}
if (!prot_ids.empty() && !pep_ids.empty())
{
status |= QCBase::Requires::ID;
}
TIC tic;
SpectrumCount spectrum_count;
FeatureSummary feature_summary;
IdentificationSummary identification_summary;
// ---------------------------------------------------------------
// function to add quality metrics to quality_metrics
// ---------------------------------------------------------------
auto addMetric = [&cv, &quality_metrics](const String& accession, const auto& value) -> void
{
json qm;
qm["accession"] = accession.c_str();
if (cv.exists(accession))
{
qm["name"] = cv.getTerm(accession).name.c_str();
}
else
{
cout << accession << " not found in CV." << endl;
return;
}
qm["value"] = value;
quality_metrics.push_back(qm);
};
// ---------------------------------------------------------------
// collecting quality metrics
// ---------------------------------------------------------------
if (spectrum_count.isRunnable(status))
{
auto counts = spectrum_count.compute(exp);
// Number of MS1 spectra
addMetric("QC:4000059", counts[1]);
// Number of MS2 spectra
addMetric("QC:4000060", counts[2]);
}
// Number of chromatograms"
addMetric("QC:4000135", exp.getChromatograms().size());
// Run time (RT duration)
addMetric("QC:4000053", UInt(exp.spectrumRanges().getMaxRT() - exp.spectrumRanges().getMinRT()));
// MZ acquisition range
addMetric("QC:4000138", tuple<UInt,UInt>{exp.spectrumRanges().getMinMZ(), exp.spectrumRanges().getMaxMZ()});
// TICs
if (tic.isRunnable(status))
{
// complete TIC (all ms levels) with area
auto result = tic.compute(exp, 0, 0);
if (!result.intensities.empty())
{
json chrom;
chrom["Relative intensity"] = result.relative_intensities;
chrom["Retention time"] = result.retention_times;
// Total ion current chromatogram
addMetric("QC:4000067", chrom);
// Area under TIC
addMetric("QC:4000077", result.area);
}
// MS1
result = tic.compute(exp,0,1);
if (!result.intensities.empty())
{
json chrom;
chrom["Relative intensity"] = result.relative_intensities;
chrom["Retention time"] = result.retention_times;
// MS1 Total ion current chromatogram
addMetric("QC:4000069", chrom);
// MS1 signal jump (10x) count
addMetric("QC:4000172", result.jump);
// MS1 signal fall (10x) count
addMetric("QC:4000173", result.fall);
}
// MS2
result = tic.compute(exp, 0, 2);
if (!result.intensities.empty())
{
json chrom;
chrom["Relative intensity"] = result.relative_intensities;
chrom["Retention time"] = result.retention_times;
// MS2 Total ion current chromatogram
addMetric("QC:4000070", chrom);
}
}
// Metabolomics: Detected compounds from featureXML file
if (feature_summary.isRunnable(status))
{
auto result = feature_summary.compute(feature_map);
// Detected compounds
addMetric("QC:4000257", result.feature_count);
// Retention time mean shift (sec)
if (result.rt_shift_mean != 0)
{
addMetric("QC:4000262", result.rt_shift_mean);
}
}
// peptides and proteins from idXML file
if (identification_summary.isRunnable(status))
{
auto result = identification_summary.compute(prot_ids, pep_ids);
// Total number of PSM
addMetric("QC:4000186", result.peptide_spectrum_matches);
// Number of identified peptides at given FDR threshold
addMetric("QC:4000187", make_tuple(result.unique_peptides.count, result.unique_peptides.fdr_threshold));
// Identified peptide lengths - mean
addMetric("QC:4000214", result.peptide_length_mean);
// Missed cleavages - mean
addMetric("QC:4000209", result.missed_cleavages_mean);
// Number of identified proteins at given FDR threshold
addMetric("QC:4000185", make_tuple(result.unique_proteins.count, result.unique_proteins.fdr_threshold));
// Identification score mean (of protein hits)
addMetric("QC:4000204", result.protein_hit_scores_mean);
}
// ---------------------------------------------------------------
// writing mzQC file
// ---------------------------------------------------------------
json out;
// required: creationDate, version
DateTime currentTime = DateTime::now();
out["mzQC"]["creationDate"] = currentTime.toString().c_str();
out["mzQC"]["version"] = "1.0.0";
// optional: contact_name, contact_address, description
if (!contact_name.empty())
{
out["mzQC"]["contactName"] = contact_name.c_str();
}
if (!contact_address.empty())
{
out["mzQC"]["contactAddress"] = contact_address.c_str();
}
if (!description.empty())
{
out["mzQC"]["description"] = description.c_str();
}
// get OpenMS version for runQualities
VersionInfo::VersionDetails version = VersionInfo::getVersionStruct();
out["mzQC"]["runQualities"] =
{
{
{"metadata",
{
{"label", label.c_str()},
{"inputFiles",
{
{
{"location", File::absolutePath(input_file).c_str()},
{"name", File::basename(input_file).c_str()},
{"fileFormat",
{
{"accession", "MS:10000584"},
{"name", "mzML format"}
}
},
{"fileProperties",
{
{
{"accession", "MS:1000747"},
{"name", "completion time"},
{"value", String(exp.getDateTime().getDate() + "T" + exp.getDateTime().getTime()).c_str()}
},
{
{"accession", "MS:1000569"},
{"name", "SHA-1"},
{"value", String(FileHandler::computeFileHash(input_file)).c_str()}
},
{
{"accession", "MS:1000031"},
{"name", "instrument model"},
{"value", String(exp.getInstrument().getName()).c_str()}
}
}
}
}
}
},
{"analysisSoftware",
{
{
{"accession", "MS:1009001" }, // create new qc-cv for QCCalculator: MS:1009001 quality control metrics generating software
{"name", "QCCalculator"},
{"version", (String(version.version_major)+"."+String(version.version_minor)+"."+String(version.version_patch)).c_str()},
{"uri", "https://www.openms.de"}
}
}
}
}
},
{"qualityMetrics", quality_metrics}
}
};
out["mzQC"]["controlledVocabularies"] =
{
{
{"name", "Proteomics Standards Initiative Quality Control Ontology"},
{"uri", "https://raw.githubusercontent.com/HUPO-PSI/mzQC/master/cv/qc-cv.obo"},
{"version", "0.1.2"},
},
{
{"name", "Proteomics Standards Initiative Mass Spectrometry Ontology"},
{"uri", "http://purl.obolibrary.org/obo/ms/psi-ms.obo"},
{"version", "4.1.155"}
}
};
os << out.dump(2);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/OMSSAXMLFile.cpp | .cpp | 11,732 | 401 | // 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/FORMAT/OMSSAXMLFile.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
using namespace std;
namespace OpenMS
{
OMSSAXMLFile::OMSSAXMLFile() :
XMLHandler("", 1.1),
XMLFile(),
peptide_identifications_(nullptr)
{
readMappingFile_();
}
OMSSAXMLFile::~OMSSAXMLFile() = default;
void OMSSAXMLFile::load(const String& filename, ProteinIdentification& protein_identification, PeptideIdentificationList& peptide_identifications, bool load_proteins, bool load_empty_hits)
{
// clear input (in case load() is called more than once)
protein_identification = ProteinIdentification();
peptide_identifications.clear();
// filename for error messages in XMLHandler
file_ = filename;
load_proteins_ = load_proteins;
load_empty_hits_ = load_empty_hits;
peptide_identifications_ = &peptide_identifications;
// fill the internal datastructures
parse_(filename, this);
DateTime now = DateTime::now();
String identifier("OMSSA_" + now.get());
// post-processing
set<String> accessions;
for (PeptideIdentification& pep : peptide_identifications)
{
pep.setScoreType("OMSSA");
pep.setHigherScoreBetter(false);
pep.setIdentifier(identifier);
pep.sort();
if (load_proteins)
{
for (const PeptideHit& pit : pep.getHits())
{
set<String> hit_accessions = pit.extractProteinAccessionsSet();
accessions.insert(hit_accessions.begin(), hit_accessions.end());
}
}
}
if (load_proteins)
{
for (set<String>::const_iterator it = accessions.begin(); it != accessions.end(); ++it)
{
ProteinHit hit;
hit.setAccession(*it);
protein_identification.insertHit(hit);
}
// E-values
protein_identification.setHigherScoreBetter(false);
protein_identification.setScoreType("OMSSA");
protein_identification.setIdentifier(identifier);
}
// version of OMSSA is not available
// Date of the search is not available -> set it to now()
protein_identification.setDateTime(now);
protein_identification.setIdentifier(identifier);
// search parameters are also not available
}
void OMSSAXMLFile::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& /*attributes*/)
{
tag_ = String(sm_.convert(qname)).trim();
}
void OMSSAXMLFile::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
tag_ = String(sm_.convert(qname)).trim();
// protein hits (MSPepHits) are handled in ::characters(...)
// end of peptide hit
if (tag_ == "MSHits")
{
actual_peptide_hit_.setPeptideEvidences(actual_peptide_evidences_);
actual_peptide_evidence_ = PeptideEvidence();
actual_peptide_evidences_.clear();
actual_peptide_id_.insertHit(actual_peptide_hit_);
actual_peptide_hit_ = PeptideHit();
}
// end of peptide id
else if (tag_ == "MSHitSet")
{
if (!actual_peptide_id_.getHits().empty() || load_empty_hits_)
{
peptide_identifications_->push_back(actual_peptide_id_);
}
actual_peptide_id_ = PeptideIdentification();
}
else if (tag_ == "MSModHit")
{
/*
Modifications:
<MSModHit>
<MSModHit_site>1</MSModHit_site>
<MSModHit_modtype>
<MSMod>3</MSMod>
</MSModHit_modtype>
</MSModHit>
*/
if (mods_map_.find(actual_mod_type_.toInt()) != mods_map_.end() && !mods_map_[actual_mod_type_.toInt()].empty())
{
if (mods_map_[actual_mod_type_.toInt()].size() > 1)
{
warning(LOAD, String("Cannot determine exact type of modification of position ") + actual_mod_site_ + " in sequence " + actual_peptide_hit_.getSequence().toString() + " using modification " + actual_mod_type_ + " - using first possibility!");
}
AASequence pep = actual_peptide_hit_.getSequence();
auto mod = *(mods_map_[actual_mod_type_.toInt()].begin());
if (mod->getTermSpecificity() == ResidueModification::N_TERM)
{
pep.setNTerminalModification(mod->getFullId());
}
else if (mod->getTermSpecificity() == ResidueModification::C_TERM)
{
pep.setCTerminalModification(mod->getFullId());
}
else
{
pep.setModification(actual_mod_site_, mod->getFullId());
}
actual_peptide_hit_.setSequence(pep);
}
else
{
warning(LOAD, String("Cannot find PSI-MOD mapping for mod - ignoring '") + actual_mod_type_ + "'");
}
}
tag_ = "";
}
void OMSSAXMLFile::characters(const XMLCh* const chars, const XMLSize_t /*length*/)
{
if (tag_.empty()) return;
String value = ((String)sm_.convert(chars)).trim();
// MSPepHit section
// <MSPepHit_start>0</MSPepHit_start>
// <MSPepHit_stop>8</MSPepHit_stop>
// <MSPepHit_accession>6599</MSPepHit_accession>
// <MSPepHit_defline>CRHU2 carbonate dehydratase (EC 4.2.1.1) II [validated] - human</MSPepHit_defline>
// <MSPepHit_protlength>260</MSPepHit_protlength>
// <MSPepHit_oid>6599</MSPepHit_oid>
if (tag_ == "MSPepHit_start")
{
tag_ = "";
return;
}
else if (tag_ == "MSPepHit_stop")
{
tag_ = "";
return;
}
else if (tag_ == "MSPepHit_accession")
{
if (load_proteins_)
{
actual_peptide_evidence_.setProteinAccession(value);
}
tag_ = "";
return;
}
else if (tag_ == "MSPepHit_defline")
{
// TODO add defline to ProteinHit?
tag_ = "";
return;
}
else if (tag_ == "MSPepHit_protlength")
{
tag_ = "";
return;
}
else if (tag_ == "MSPepHit_oid")
{
tag_ = "";
// end of MSPepHit so we add the evidence
actual_peptide_evidences_.push_back(actual_peptide_evidence_);
return;
}
// MSHits section
// <MSHits_evalue>0.00336753988893542</MSHits_evalue>
// <MSHits_pvalue>1.30819399070598e-08</MSHits_pvalue>
// <MSHits_charge>1</MSHits_charge>
// <MSHits_pepstring>MSHHWGYGK</MSHits_pepstring>
// <MSHits_mass>1101492</MSHits_mass>
// <MSHits_pepstart></MSHits_pepstart>
// <MSHits_pepstop>H</MSHits_pepstop>
// <MSHits_theomass>1101484</MSHits_theomass>
else if (tag_ == "MSHits_evalue")
{
actual_peptide_hit_.setScore(value.toDouble());
tag_ = "";
return;
}
else if (tag_ == "MSHits_charge")
{
actual_peptide_hit_.setCharge(value.toInt());
tag_ = "";
return;
}
else if (tag_ == "MSHits_pvalue")
{
// TODO extra field?
//actual_peptide_hit_.setScore(value.toDouble());
tag_ = "";
return;
}
else if (tag_ == "MSHits_pepstring")
{
AASequence seq;
try
{
seq = AASequence::fromString(value.trim());
}
catch (Exception::ParseError& /* e */)
{
actual_peptide_hit_.setSequence(AASequence());
tag_ = "";
return;
}
if (mod_def_set_.getNumberOfFixedModifications() != 0)
{
set<String> fixed_mod_names = mod_def_set_.getFixedModificationNames();
for (set<String>::const_iterator it = fixed_mod_names.begin(); it != fixed_mod_names.end(); ++it)
{
String origin = ModificationsDB::getInstance()->getModification(*it)->getOrigin();
UInt position(0);
for (const Residue& ait : seq)
{
if (ait.getOneLetterCode() == origin)
{
seq.setModification(position, *it);
}
++position;
}
}
}
actual_peptide_hit_.setSequence(seq);
tag_ = "";
return;
}
else if (tag_ == "MSHits_mass")
{
tag_ = "";
return;
}
else if (tag_ == "MSHits_pepstart")
{
if (!value.empty() && !actual_peptide_evidences_.empty())
{
actual_peptide_evidences_[0].setAABefore(value[0]);
}
tag_ = "";
return;
}
else if (tag_ == "MSHits_pepstop")
{
if (!value.empty() && !actual_peptide_evidences_.empty())
{
actual_peptide_evidences_[0].setAAAfter(value[0]);
}
tag_ = "";
return;
}
else if (tag_ == "MSHits_theomass")
{
tag_ = "";
return;
}
// modifications
///<MSHits_mods>
// <MSModHit>
// <MSModHit_site>4</MSModHit_site>
// <MSModHit_modtype>
// <MSMod>2</MSMod>
// </MSModHit_modtype>
// </MSModHit>
///</MSHits_mods>
if (tag_ == "MSHits_mods")
{
actual_mod_site_ = 0;
actual_mod_type_ = "";
}
else if (tag_ == "MSModHit_site")
{
actual_mod_site_ = value.trim().toInt();
}
else if (tag_ == "MSMod")
{
actual_mod_type_ = value.trim();
}
// m/z value and rt
else if (tag_ == "MSHitSet_ids_E")
{
// value might be ( OMSSA 2.1.8): 359.213256835938_3000.13720000002_controllerType=0 controllerNumber=1 scan=4655
// (<OMSSA 2.1.8): 359.213256835938_3000.13720000002
if (!value.trim().empty())
{
if (value.has('_'))
{
StringList sp = ListUtils::create<String>(value, '_');
try
{
actual_peptide_id_.setMZ(sp[0].toDouble());
actual_peptide_id_.setRT(sp[1].toDouble());
}
catch (...)
{
// if exception happens to occur here, s.th. went wrong, e.g. the value does not contain numbers
}
}
}
}
}
void OMSSAXMLFile::readMappingFile_()
{
String file = File::find("CHEMISTRY/OMSSA_modification_mapping");
TextFile infile(file);
for (TextFile::ConstIterator it = infile.begin(); it != infile.end(); ++it)
{
vector<String> split;
it->split(',', split);
if (!it->empty() && (*it)[0] != '#')
{
Int omssa_mod_num = split[0].trim().toInt();
if (split.size() < 2)
{
fatalError(LOAD, String("Invalid mapping file line: '") + *it + "'");
}
vector<const ResidueModification*> mods;
for (Size i = 2; i != split.size(); ++i)
{
String tmp(split[i].trim());
if (!tmp.empty())
{
const ResidueModification* mod = ModificationsDB::getInstance()->getModification(tmp);
mods.push_back(mod);
mods_to_num_[mod->getFullId()] = omssa_mod_num;
}
}
mods_map_[omssa_mod_num] = mods;
}
}
}
void OMSSAXMLFile::setModificationDefinitionsSet(const ModificationDefinitionsSet& mod_set)
{
mod_def_set_ = mod_set;
UInt omssa_mod_num(119);
set<String> mod_names = mod_set.getVariableModificationNames();
for (set<String>::const_iterator it = mod_names.begin(); it != mod_names.end(); ++it)
{
if (!(mods_to_num_.find(*it) != mods_to_num_.end()))
{
mods_map_[omssa_mod_num].push_back(ModificationsDB::getInstance()->getModification(*it));
mods_to_num_[*it] = omssa_mod_num;
++omssa_mod_num;
}
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MRMFeaturePickerFile.cpp | .cpp | 5,112 | 137 | // 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/FORMAT/MRMFeaturePickerFile.h>
#include <boost/regex.hpp>
#include <iostream>
namespace OpenMS
{
void MRMFeaturePickerFile::load(
const String& filename,
std::vector<MRMFeaturePicker::ComponentParams>& cp_list,
std::vector<MRMFeaturePicker::ComponentGroupParams>& cgp_list
)
{
cp_list.clear();
cgp_list.clear();
CsvFile::load(filename, ',', false);
StringList sl;
std::map<String, Size> headers;
if (rowCount() >= 2) // no need to read headers if that's the only line inside the file
{
getRow(0, sl);
for (Size i = 0; i < sl.size(); ++i)
{
headers[sl[i]] = i; // for each header found, assign an index value to it
}
if (!(headers.count("component_name") && headers.count("component_group_name")))
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Columns component_name and/or component_group_name not found.");
}
}
for (Size i = 1; i < rowCount(); ++i)
{
getRow(i, sl);
MRMFeaturePicker::ComponentParams cp;
MRMFeaturePicker::ComponentGroupParams cgp;
if (extractParamsFromLine_(sl, headers, cp, cgp))
{
cp_list.push_back(cp);
// The following lines check if cgp is already present in cgp_list
// If that is not the case, the extracted cgp is pushed
bool cgp_found = std::any_of(
cgp_list.begin(),
cgp_list.end(),
[&cgp](const MRMFeaturePicker::ComponentGroupParams& current_cgp)
{
return cgp.component_group_name == current_cgp.component_group_name;
}
);
if (!cgp_found)
{
cgp_list.push_back(cgp);
}
}
}
}
bool MRMFeaturePickerFile::extractParamsFromLine_(
const StringList& line,
const std::map<String, Size>& headers,
MRMFeaturePicker::ComponentParams& cp,
MRMFeaturePicker::ComponentGroupParams& cgp
) const
{
cp.component_name = line[headers.find("component_name")->second]; // save the component_name value
cp.component_group_name = line[headers.find("component_group_name")->second]; // save the component_group_name value
if (cp.component_name.empty() || cp.component_group_name.empty()) // component_name and component_group_name must not be empty
{
return false;
}
cgp.component_group_name = cp.component_group_name; // save the component_group_name also into cgp
for (const std::pair<const String, Size>& h : headers) // parse the parameters
{
const String& header = h.first;
const Size& i = h.second;
boost::smatch m;
if (boost::regex_search(header, m, boost::regex("TransitionGroupPicker:(?!PeakPickerChromatogram:)(.+)")))
{
setCastValue_(String(m[1]), line[i], cgp.params);
}
else if (boost::regex_search(header, m, boost::regex("TransitionGroupPicker:PeakPickerChromatogram:(.+)")))
{
setCastValue_(String(m[1]), line[i], cp.params);
}
}
return true;
}
void MRMFeaturePickerFile::setCastValue_(const String& key, const String& value, Param& params) const
{
if (value.empty()) // if the value is empty, don't set it
{
return;
}
const std::vector<String> double_headers = {
"gauss_width", "peak_width", "signal_to_noise", "sn_win_len", "stop_after_intensity_ratio",
"min_peak_width", "recalculate_peaks_max_z", "minimal_quality", "resample_boundary"
};
const std::vector<String> bool_headers = {
"use_gauss", "write_sn_log_messages", "remove_overlapping_peaks", "recalculate_peaks",
"use_precursors", "compute_peak_quality", "compute_peak_shape_metrics"
};
const std::vector<String> uint_headers = {
"sgolay_frame_length", "sgolay_polynomial_order", "sn_bin_count"
};
const std::vector<String> int_headers = {
"stop_after_feature"
};
if (std::find(double_headers.begin(), double_headers.end(), key) != double_headers.end())
{
params.setValue(key, value.toDouble());
}
else if (std::find(bool_headers.begin(), bool_headers.end(), key) != bool_headers.end())
{
params.setValue(key, value == "true" || value == "TRUE" ? "true" : "false");
}
else if (std::find(uint_headers.begin(), uint_headers.end(), key) != uint_headers.end())
{
params.setValue(key, static_cast<UInt>(value.toDouble()));
}
else if (std::find(int_headers.begin(), int_headers.end(), key) != int_headers.end())
{
params.setValue(key, value.toInt());
}
else // no conversion for class' parameters of type String
{
params.setValue(key, value);
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/IndentedStream.cpp | .cpp | 2,523 | 74 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/IndentedStream.h>
#include <OpenMS/CONCEPT/Colorizer.h>
#include <algorithm>
#include <sstream>
using namespace std;
namespace OpenMS
{
IndentedStream::IndentedStream(std::ostream& stream, const UInt indentation, const UInt max_lines) :
stream_(&stream), indentation_(indentation), max_lines_(max_lines), max_line_width_(ConsoleUtils::getInstance().getConsoleWidth())
{
}
/// D'tor flushes the stream
IndentedStream::~IndentedStream()
{
stream_->flush();
}
IndentedStream& IndentedStream::operator<<(Colorizer& colorizer)
{
// manipulate the internal data of colorizer (if any)
stringstream reformatted;
// use a clone of ourselves, but dump data to a stringstream
IndentedStream formatter(reformatted, indentation_, max_lines_);
formatter.current_column_pos_ = current_column_pos_; // advance the formatter to the same column position that we have
formatter << colorizer.getInternalChars_().str(); // push the data (invoking line breaks if required)
// update colorizer with new data (with indentation)
colorizer.setInternalChars_(reformatted.str()); // skip the initialization 'x' chars
// apply Color to our internal stream
// Do NOT push the data into the IndentedStream since this prevents detection
// of stdout/stderr (and its redirection status) by Colorizer. If the underlying stream_
// is indeed cout but redirected to a file, you would get ANSI symbols in there (not desiable)
*stream_ << colorizer;
// update our column position based on the new data
current_column_pos_ = formatter.current_column_pos_; // this does not take into account ANSI codes which are added by Colorizer -- nothing we can do about it.
return *this;
}
IndentedStream& IndentedStream::operator<<(IndentedStream & self)
{
return self;
}
IndentedStream& IndentedStream::operator<<(StreamManipulator manip)
{
// call the function on the internal stream
manip(*stream_);
return *this;
}
IndentedStream& IndentedStream::indent(const UInt new_indent)
{
indentation_ = new_indent;
return *this;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/GNPSQuantificationFile.cpp | .cpp | 3,668 | 83 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Axel Walter $
// $Authors: Axel Walter $
// --------------------------------------------------------------------------
//-------------------------------------------------------------------------
#include <OpenMS/FORMAT/GNPSQuantificationFile.h>
#include <OpenMS/FORMAT/SVOutStream.h>
#include <fstream>
#include <iostream>
#include <unordered_map>
namespace OpenMS
{
/**
@brief Generates a feature quantification file required for GNPS FBMN, as defined here: https://ccms-ucsd.github.io/GNPSDocumentation/featurebasedmolecularnetworking/#feature-quantification-table
*/
void GNPSQuantificationFile::store(const ConsensusMap& consensus_map, const String& output_file)
{
// IIMN meta values will be exported, if first feature contains mv Constants::UserParam::IIMN_ROW_ID
bool iimn = false;
if (consensus_map[0].metaValueExists(Constants::UserParam::IIMN_ROW_ID)) iimn = true;
// meta values for ion identity molecular networking
std::vector<String> iimn_mvs{Constants::UserParam::IIMN_ROW_ID,
Constants::UserParam::IIMN_BEST_ION,
Constants::UserParam::IIMN_ADDUCT_PARTNERS,
Constants::UserParam::IIMN_ANNOTATION_NETWORK_NUMBER};
// initialize SVOutStream with tab separation
std::ofstream outstr(output_file.c_str());
SVOutStream out(outstr, "\t", "_", String::NONE);
// write headers for MAP and CONSENSUS
out << "#MAP" << "id" << "filename" << "label" << "size" << std::endl;
out << "#CONSENSUS" << "rt_cf" << "mz_cf" << "intensity_cf" << "charge_cf" << "width_cf" << "quality_cf";
if (iimn)
{
for (const auto& mv : iimn_mvs) out << mv;
}
for (size_t i = 0; i < consensus_map.getColumnHeaders().size(); i++)
{
out << "rt_" + String(i) << "mz_" + String(i) << "intensity_" + String(i) << "charge_" + String(i) << "width_" + String(i);
}
out << std::endl;
// write MAP information
for (const auto& h: consensus_map.getColumnHeaders())
{
out << "MAP" << h.first << h.second.filename << h.second.label << h.second.size << std::endl;
}
// write ConsensusFeature information
for (const auto& cf: consensus_map)
{
out << "CONSENSUS" << cf.getRT() << cf.getMZ() << cf.getIntensity() << cf.getCharge() << cf.getWidth() << cf.getQuality();
if (iimn)
{
for (const auto& mv : iimn_mvs) out << cf.getMetaValue(mv, "");
}
// map index to feature handle and write feature information on correct position, if feature is missing write empty strings
std::unordered_map<size_t, FeatureHandle> index_to_feature;
for (const auto& fh: cf.getFeatures()) index_to_feature[fh.getMapIndex()] = fh;
for (size_t i = 0; i < consensus_map.getColumnHeaders().size(); i++)
{
if (index_to_feature.count(i))
{
out << index_to_feature[i].getRT() << index_to_feature[i].getMZ() << index_to_feature[i].getIntensity() << index_to_feature[i].getCharge() << index_to_feature[i].getWidth();
}
else
{
out << "" << "" << "" << "" << "";
}
}
out << std::endl;
}
outstr.close();
}
} // namespace | C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/InspectInfile.cpp | .cpp | 15,494 | 501 | // 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/FORMAT/InspectInfile.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/FORMAT/PTMXMLFile.h>
#include <fstream>
#include <sstream>
using namespace std;
namespace OpenMS
{
// default constructor
InspectInfile::InspectInfile() :
modifications_per_peptide_(-1),
blind_(2),
maxptmsize_(-1.0),
precursor_mass_tolerance_(-1.0),
peak_mass_tolerance_(-1.0),
multicharge_(2),
tag_count_(-1)
{
}
// copy constructor
InspectInfile::InspectInfile(const InspectInfile& inspect_infile) :
spectra_(inspect_infile.getSpectra()),
enzyme_(inspect_infile.getEnzyme()),
modifications_per_peptide_(inspect_infile.getModificationsPerPeptide()),
blind_(inspect_infile.getBlind()),
maxptmsize_(inspect_infile.getMaxPTMsize()),
precursor_mass_tolerance_(inspect_infile.getPrecursorMassTolerance()),
peak_mass_tolerance_(inspect_infile.getPeakMassTolerance()),
multicharge_(inspect_infile.getMulticharge()),
instrument_(inspect_infile.getInstrument()),
tag_count_(inspect_infile.getTagCount()),
PTMname_residues_mass_type_(inspect_infile.getModifications())
{
}
// destructor
InspectInfile::~InspectInfile()
{
PTMname_residues_mass_type_.clear();
}
// assignment operator
InspectInfile& InspectInfile::operator=(const InspectInfile& inspect_infile)
{
if (this != &inspect_infile)
{
spectra_ = inspect_infile.getSpectra();
enzyme_ = inspect_infile.getEnzyme();
modifications_per_peptide_ = inspect_infile.getModificationsPerPeptide();
blind_ = inspect_infile.getBlind();
maxptmsize_ = inspect_infile.getMaxPTMsize();
precursor_mass_tolerance_ = inspect_infile.getPrecursorMassTolerance();
peak_mass_tolerance_ = inspect_infile.getPeakMassTolerance();
multicharge_ = inspect_infile.getMulticharge();
instrument_ = inspect_infile.getInstrument();
tag_count_ = inspect_infile.getTagCount();
PTMname_residues_mass_type_ = inspect_infile.getModifications();
}
return *this;
}
// equality operator
bool InspectInfile::operator==(const InspectInfile& inspect_infile) const
{
if (this != &inspect_infile)
{
bool equal = true;
equal &= (spectra_ == inspect_infile.getSpectra());
equal &= (enzyme_ == inspect_infile.getEnzyme());
equal &= (modifications_per_peptide_ == inspect_infile.getModificationsPerPeptide());
equal &= (blind_ == inspect_infile.getBlind());
equal &= (maxptmsize_ == inspect_infile.getMaxPTMsize());
equal &= (precursor_mass_tolerance_ == inspect_infile.getPrecursorMassTolerance());
equal &= (peak_mass_tolerance_ == inspect_infile.getPeakMassTolerance());
equal &= (multicharge_ == inspect_infile.getMulticharge());
equal &= (instrument_ == inspect_infile.getInstrument());
equal &= (tag_count_ == inspect_infile.getTagCount());
equal &= (PTMname_residues_mass_type_ == inspect_infile.getModifications());
return equal;
}
return true;
}
void InspectInfile::store(const String& filename)
{
if (!FileHandler::hasValidExtension(filename, FileTypes::TSV))
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "invalid file extension, expected '" + FileTypes::typeToName(FileTypes::TSV) + "'");
}
ofstream ofs(filename.c_str());
if (!ofs)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
stringstream file_content;
file_content << "spectra," << spectra_ << "\n";
if (!db_.empty())
{
file_content << "db," << db_ << "\n";
}
if (!enzyme_.empty())
{
file_content << "protease," << enzyme_ << "\n";
}
if (blind_ != 2)
{
file_content << "blind," << blind_ << "\n";
}
//mod,+57,C,fix,carbamidomethylation
for (std::map<String, vector<String> >::iterator mods_i = PTMname_residues_mass_type_.begin(); mods_i != PTMname_residues_mass_type_.end(); ++mods_i)
{
// fix", "cterminal", "nterminal", and "opt
mods_i->second[2].toLower();
if (mods_i->second[2].hasSuffix("term"))
{
mods_i->second[2].append("inal");
}
file_content << "mod," << mods_i->second[1] << "," << mods_i->second[0] << "," << mods_i->second[2] << "," << mods_i->first << "\n";
}
if (modifications_per_peptide_ > -1)
{
file_content << "mods," << modifications_per_peptide_ << "\n";
}
if (maxptmsize_ >= 0)
{
file_content << "maxptmsize," << maxptmsize_ << "\n";
}
if (precursor_mass_tolerance_ >= 0)
{
file_content << "PM_tolerance," << precursor_mass_tolerance_ << "\n";
}
if (peak_mass_tolerance_ >= 0)
{
file_content << "IonTolerance," << peak_mass_tolerance_ << "\n";
}
if (multicharge_ != 2)
{
file_content << "multicharge," << multicharge_ << "\n";
}
if (!instrument_.empty())
{
file_content << "instrument," << instrument_ << "\n";
}
if (tag_count_ >= 0)
{
file_content << "TagCount," << tag_count_ << "\n";
}
ofs << file_content.str();
ofs.close();
ofs.clear();
}
void InspectInfile::handlePTMs(const String& modification_line, const String& modifications_filename, const bool monoisotopic)
{
PTMname_residues_mass_type_.clear();
// to store the information about modifications from the ptm xml file
std::map<String, pair<String, String> > ptm_informations;
if (!modification_line.empty()) // if modifications are used look whether whether composition and residues (and type and name) is given, the name (type) is used (then the modifications file is needed) or only the mass and residues (and type and name) is given
{
vector<String> modifications, mod_parts;
modification_line.split(':', modifications); // get the single modifications
if (modifications.empty())
{
modifications.push_back(modification_line);
}
// to get masses from a formula
EmpiricalFormula add_formula, substract_formula;
String types = "OPT#FIX#";
String name, residues, mass, type;
// 0 - mass; 1 - composition; 2 - ptm name
Int mass_or_composition_or_name(-1);
for (vector<String>::const_iterator mod_i = modifications.begin(); mod_i != modifications.end(); ++mod_i)
{
if (mod_i->empty())
{
continue;
}
// clear the formulae
add_formula = substract_formula = EmpiricalFormula();
name = residues = mass = type = "";
// get the single parts of the modification string
mod_i->split(',', mod_parts);
if (mod_parts.empty())
mod_parts.push_back(*mod_i);
mass_or_composition_or_name = -1;
// check whether the first part is a mass, composition or name
// check whether it is a mass
try
{
mass = mod_parts.front();
// to check whether the first part is a mass, it is converted into a float and then back into a string and compared to the given string
// remove + signs because they don't appear in a float
if (mass.hasPrefix("+"))
{
mass.erase(0, 1);
}
if (mass.hasSuffix("+"))
{
mass.erase(mass.length() - 1, 1);
}
if (mass.hasSuffix("-")) // a - sign at the end will not be converted
{
mass.erase(mass.length() - 1, 1);
mass.insert(0, "-");
}
// if it is a mass
if (!String(mass.toFloat()).empty()) // just check if conversion does not throw, i.e. consumes the whole string
{
mass_or_composition_or_name = 0;
}
}
catch (Exception::ConversionError& /*c_e*/)
{
mass_or_composition_or_name = -1;
}
// check whether it is a name (look it up in the corresponding file)
if (mass_or_composition_or_name == -1)
{
if (ptm_informations.empty()) // if the ptm xml file has not been read yet, read it
{
if (!File::exists(modifications_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, modifications_filename);
}
if (!File::readable(modifications_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, modifications_filename);
}
// getting all available modifications from a file
PTMXMLFile().load(modifications_filename, ptm_informations);
}
// if the modification cannot be found
if (ptm_informations.find(mod_parts.front()) != ptm_informations.end())
{
mass = ptm_informations[mod_parts.front()].first; // composition
residues = ptm_informations[mod_parts.front()].second; // residues
name = mod_parts.front(); // name
mass_or_composition_or_name = 2;
}
}
// check whether it's an empirical formula / if a composition was given, get the mass
if (mass_or_composition_or_name == -1)
{
mass = mod_parts.front();
}
if (mass_or_composition_or_name == -1 || mass_or_composition_or_name == 2)
{
// check whether there is a positive and a negative formula
String::size_type pos = mass.find("-");
try
{
if (pos != String::npos)
{
add_formula = EmpiricalFormula(mass.substr(0, pos));
substract_formula = EmpiricalFormula(mass.substr(++pos));
}
else
{
add_formula = EmpiricalFormula(mass);
}
// sum up the masses
if (monoisotopic)
{
mass = String(add_formula.getMonoWeight() - substract_formula.getMonoWeight());
}
else
{
mass = String(add_formula.getAverageWeight() - substract_formula.getAverageWeight());
}
if (mass_or_composition_or_name == -1)
{
mass_or_composition_or_name = 1;
}
}
catch (Exception::ParseError& /*pe*/)
{
PTMname_residues_mass_type_.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, *mod_i, "There's something wrong with this modification. Aborting!");
}
}
// now get the residues
mod_parts.erase(mod_parts.begin());
if (mass_or_composition_or_name < 2)
{
if (mod_parts.empty())
{
PTMname_residues_mass_type_.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, *mod_i, "No residues for modification given. Aborting!");
}
// get the residues
residues = mod_parts.front();
residues.substitute('*', 'X');
residues.toUpper();
mod_parts.erase(mod_parts.begin());
}
// get the type
if (mod_parts.empty())
{
type = "OPT";
}
else
{
type = mod_parts.front();
type.toUpper();
if (types.find(type) != String::npos)
{
mod_parts.erase(mod_parts.begin());
}
else
{
type = "OPT";
}
}
if (mod_parts.size() > 1)
{
PTMname_residues_mass_type_.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, *mod_i, "There's something wrong with the type of this modification. Aborting!");
}
// get the name
if (mass_or_composition_or_name < 2)
{
if (mod_parts.empty())
{
name = "PTM_" + String(PTMname_residues_mass_type_.size());
}
else
{
name = mod_parts.front();
}
}
// insert the modification
if (PTMname_residues_mass_type_.find(name) == PTMname_residues_mass_type_.end())
{
PTMname_residues_mass_type_[name] = vector<String>(3);
PTMname_residues_mass_type_[name][0] = residues;
// mass must not have more than 5 digits after the . (otherwise the test may fail)
PTMname_residues_mass_type_[name][1] = mass.substr(0, mass.find(".") + 6);
PTMname_residues_mass_type_[name][2] = type;
}
else
{
PTMname_residues_mass_type_.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, *mod_i, "There's already a modification with this name. Aborting!");
}
}
}
}
const std::map<String, vector<String> >& InspectInfile::getModifications() const
{
return PTMname_residues_mass_type_;
}
const String& InspectInfile::getSpectra() const
{
return spectra_;
}
void InspectInfile::setSpectra(const String& spectra)
{
spectra_ = spectra;
}
const String& InspectInfile::getDb() const
{
return db_;
}
void InspectInfile::setDb(const String& db)
{
db_ = db;
}
const String& InspectInfile::getEnzyme() const
{
return enzyme_;
}
void InspectInfile::setEnzyme(const String& enzyme)
{
enzyme_ = enzyme;
}
Int InspectInfile::getModificationsPerPeptide() const
{
return modifications_per_peptide_;
}
void InspectInfile::setModificationsPerPeptide(Int modifications_per_peptide)
{
modifications_per_peptide_ = modifications_per_peptide;
}
UInt InspectInfile::getBlind() const
{
return blind_;
}
void InspectInfile::setBlind(UInt blind)
{
blind_ = blind;
}
float InspectInfile::getMaxPTMsize() const
{
return maxptmsize_;
}
void InspectInfile::setMaxPTMsize(float maxptmsize)
{
maxptmsize_ = maxptmsize;
}
float InspectInfile::getPrecursorMassTolerance() const
{
return precursor_mass_tolerance_;
}
void InspectInfile::setPrecursorMassTolerance(float precursor_mass_tolerance)
{
precursor_mass_tolerance_ = precursor_mass_tolerance;
}
float InspectInfile::getPeakMassTolerance() const
{
return peak_mass_tolerance_;
}
void InspectInfile::setPeakMassTolerance(float ion_tolerance)
{
peak_mass_tolerance_ = ion_tolerance;
}
UInt InspectInfile::getMulticharge() const
{
return multicharge_;
}
void InspectInfile::setMulticharge(UInt multicharge)
{
multicharge_ = multicharge;
}
const String& InspectInfile::getInstrument() const
{
return instrument_;
}
void InspectInfile::setInstrument(const String& instrument)
{
instrument_ = instrument;
}
Int InspectInfile::getTagCount() const
{
return tag_count_;
}
void InspectInfile::setTagCount(Int tag_count)
{
tag_count_ = tag_count;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/OMSFile.cpp | .cpp | 2,008 | 72 | // 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/FORMAT/OMSFile.h>
#include <OpenMS/FORMAT/OMSFileLoad.h>
#include <OpenMS/FORMAT/OMSFileStore.h>
#include <fstream>
using namespace std;
using ID = OpenMS::IdentificationData;
namespace OpenMS
{
void OMSFile::store(const String& filename, const IdentificationData& id_data)
{
OpenMS::Internal::OMSFileStore helper(filename, log_type_);
helper.store(id_data);
}
void OMSFile::store(const String& filename, const FeatureMap& features)
{
OpenMS::Internal::OMSFileStore helper(filename, log_type_);
helper.store(features);
}
void OMSFile::store(const String& filename, const ConsensusMap& consensus)
{
OpenMS::Internal::OMSFileStore helper(filename, log_type_);
helper.store(consensus);
}
void OMSFile::load(const String& filename, IdentificationData& id_data)
{
OpenMS::Internal::OMSFileLoad helper(filename, log_type_);
helper.load(id_data);
}
void OMSFile::load(const String& filename, FeatureMap& features)
{
OpenMS::Internal::OMSFileLoad helper(filename, log_type_);
helper.load(features);
}
void OMSFile::load(const String& filename, ConsensusMap& consensus)
{
OpenMS::Internal::OMSFileLoad helper(filename, log_type_);
helper.load(consensus);
}
void OMSFile::exportToJSON(const String& filename_in, const String& filename_out)
{
OpenMS::Internal::OMSFileLoad helper(filename_in, log_type_);
ofstream output(filename_out.c_str());
if (output.is_open())
{
helper.exportToJSON(output);
}
else
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename_out);
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/CachedMzML.cpp | .cpp | 3,875 | 118 | // 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/FORMAT/CachedMzML.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/Macros.h>
#include <OpenMS/FORMAT/HANDLERS/CachedMzMLHandler.h>
namespace OpenMS
{
CachedmzML::CachedmzML() = default;
CachedmzML::CachedmzML(const String& filename)
{
load_(filename);
}
CachedmzML::~CachedmzML()
{
ifs_.close();
}
CachedmzML::CachedmzML(const CachedmzML & rhs) :
meta_ms_experiment_(rhs.meta_ms_experiment_),
ifs_(rhs.filename_cached_.c_str(), std::ios::binary),
filename_(rhs.filename_),
spectra_index_(rhs.spectra_index_),
chrom_index_(rhs.chrom_index_)
{
}
void CachedmzML::load_(const String& filename)
{
filename_cached_ = filename + ".cached";
filename_ = filename;
// Create the index from the given file
Internal::CachedMzMLHandler cache;
cache.createMemdumpIndex(filename_cached_);
spectra_index_ = cache.getSpectraIndex();
chrom_index_ = cache.getChromatogramIndex();;
// open the filestream
ifs_.open(filename_cached_.c_str(), std::ios::binary);
// load the meta data from disk
FileHandler().loadExperiment(filename, meta_ms_experiment_, {OpenMS::FileTypes::MZML});
}
MSSpectrum CachedmzML::getSpectrum(Size id)
{
OPENMS_PRECONDITION(id < getNrSpectra(), "Id cannot be larger than number of spectra");
if ( !ifs_.seekg(spectra_index_[id]) )
{
std::cerr << "Error while reading spectrum " << id << " - seekg created an error when trying to change position to " << spectra_index_[id] << "." << std::endl;
std::cerr << "Maybe an invalid position was supplied to seekg, this can happen for example when reading large files (>2GB) on 32bit systems." << std::endl;
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Error while changing position of input stream pointer.", filename_cached_);
}
MSSpectrum s = meta_ms_experiment_.getSpectrum(id);
Internal::CachedMzMLHandler::readSpectrum(s, ifs_);
return s;
}
MSChromatogram CachedmzML::getChromatogram(Size id)
{
OPENMS_PRECONDITION(id < getNrChromatograms(), "Id cannot be larger than number of chromatograms");
if ( !ifs_.seekg(chrom_index_[id]) )
{
std::cerr << "Error while reading chromatogram " << id << " - seekg created an error when trying to change position to " << chrom_index_[id] << "." << std::endl;
std::cerr << "Maybe an invalid position was supplied to seekg, this can happen for example when reading large files (>2GB) on 32bit systems." << std::endl;
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Error while changing position of input stream pointer.", filename_cached_);
}
MSChromatogram c = meta_ms_experiment_.getChromatogram(id);
Internal::CachedMzMLHandler::readChromatogram(c, ifs_);
return c;
}
size_t CachedmzML::getNrSpectra() const
{
return meta_ms_experiment_.size();
}
size_t CachedmzML::getNrChromatograms() const
{
return meta_ms_experiment_.getChromatograms().size();
}
void CachedmzML::store(const String& filename, const PeakMap& map)
{
Internal::CachedMzMLHandler().writeMemdump(map, filename + ".cached");
Internal::CachedMzMLHandler().writeMetadata_x(map, filename, true);
}
void CachedmzML::load(const String& filename, CachedmzML& map)
{
map.load_(filename);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/OMSFileLoad.cpp | .cpp | 44,940 | 1,175 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/OMSFileLoad.h>
#include <OpenMS/FORMAT/OMSFileStore.h> // for "raiseDBError_"
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <OpenMS/CHEMISTRY/RNaseDB.h>
#include <OpenMS/CONCEPT/UniqueIdGenerator.h>
#include <QtCore/QString>
// JSON export:
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <SQLiteCpp/Database.h>
#include <sqlite3.h>
using namespace std;
using ID = OpenMS::IdentificationData;
namespace OpenMS::Internal
{
// initialize lookup table:
map<QString, QString> OMSFileLoad::export_order_by_ = {
{"version", ""},
{"ID_IdentifiedCompound", "molecule_id"},
{"ID_ParentMatch", "molecule_id, parent_id, start_pos, end_pos"},
{"ID_ParentGroup_ParentSequence", "group_id, parent_id"},
{"ID_ProcessingStep_InputFile", "processing_step_id, input_file_id"},
{"ID_ProcessingSoftware_AssignedScore", "software_id, score_type_order"},
{"ID_ObservationMatch_PeakAnnotation", "parent_id, processing_step_id, peak_mz, peak_annotation"},
{"FEAT_ConvexHull", "feature_id, hull_index, point_index"},
{"FEAT_ObservationMatch", "feature_id, observation_match_id"},
{"FEAT_MapMetaData", "unique_id"}
};
OMSFileLoad::OMSFileLoad(const String& filename, LogType log_type):
db_(make_unique<SQLite::Database>(filename))
{
setLogType(log_type);
// read version number:
try
{
auto version = db_->execAndGet("SELECT OMSFile FROM version");
version_number_ = version.getInt();
}
catch (...)
{
raiseDBError_(db_->getErrorMsg(), __LINE__, OPENMS_PRETTY_FUNCTION,
"error reading file format version number");
}
}
OMSFileLoad::~OMSFileLoad()
{
}
bool OMSFileLoad::isEmpty_(const SQLite::Statement& query)
{
return query.getQuery().empty();
}
// currently not needed:
// CVTerm OMSFileLoad::loadCVTerm_(int id)
// {
// // this assumes that the "CVTerm" table exists!
// SQLite::Statement query(db_);
//
// QString sql_select = "SELECT * FROM CVTerm WHERE id = " + QString(id);
// if (!query.exec(sql_select) || !query.executeStep())
// {
// raiseDBError_(model.getErrorMsg(), __LINE__, OPENMS_PRETTY_FUNCTION,
// "error reading from database");
// }
// return CVTerm(query.getColumn("accession").getString(),
// query.getColumn("name").getString(),
// query.getColumn("cv_identifier_ref").getString());
// }
void OMSFileLoad::loadScoreTypes_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_ScoreType")) return;
if (!db_->tableExists("CVTerm")) // every score type is a CV term
{
String msg = "required database table 'CVTerm' not found";
throw Exception::MissingInformation(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
// careful - both joined tables have an "id" field, need to exclude one:
SQLite::Statement query(*db_, "SELECT S.*, C.accession, C.name, C.cv_identifier_ref " \
"FROM ID_ScoreType AS S JOIN CVTerm AS C " \
"ON S.cv_term_id = C.id");
while (query.executeStep())
{
CVTerm cv_term(query.getColumn("accession").getString(),
query.getColumn("name").getString(),
query.getColumn("cv_identifier_ref").getString());
bool higher_better = query.getColumn("higher_better").getInt();
ID::ScoreType score_type(cv_term, higher_better);
ID::ScoreTypeRef ref = id_data.registerScoreType(score_type);
score_type_refs_[query.getColumn("id").getInt64()] = ref;
}
}
void OMSFileLoad::loadInputFiles_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_InputFile")) return;
SQLite::Statement query(*db_, "SELECT * FROM ID_InputFile");
while (query.executeStep())
{
ID::InputFile input(query.getColumn("name").getString(),
query.getColumn("experimental_design_id").getString());
String primary_files = query.getColumn("primary_files").getString();
vector<String> pf_list = ListUtils::create<String>(primary_files);
input.primary_files.insert(pf_list.begin(), pf_list.end());
ID::InputFileRef ref = id_data.registerInputFile(input);
input_file_refs_[query.getColumn("id").getInt64()] = ref;
}
}
void OMSFileLoad::loadProcessingSoftwares_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_ProcessingSoftware")) return;
SQLite::Statement query(*db_, "SELECT * FROM ID_ProcessingSoftware");
bool have_scores = db_->tableExists("ID_ProcessingSoftware_AssignedScore");
SQLite::Statement subquery(*db_, "");
if (have_scores)
{
subquery = SQLite::Statement(*db_, "SELECT score_type_id " \
"FROM ID_ProcessingSoftware_AssignedScore " \
"WHERE software_id = :id ORDER BY score_type_order ASC");
}
while (query.executeStep())
{
Key id = query.getColumn("id").getInt64();
ID::ProcessingSoftware software(query.getColumn("name").getString(),
query.getColumn("version").getString());
if (have_scores)
{
subquery.bind(":id", id);
while (subquery.executeStep())
{
Key score_type_id = subquery.getColumn(0).getInt64();
software.assigned_scores.push_back(score_type_refs_[score_type_id]);
}
subquery.reset(); // get ready for new executeStep()
}
ID::ProcessingSoftwareRef ref = id_data.registerProcessingSoftware(software);
processing_software_refs_[id] = ref;
}
}
DataValue OMSFileLoad::makeDataValue_(const SQLite::Statement& query)
{
DataValue::DataType type = DataValue::EMPTY_VALUE;
int type_index = query.getColumn("data_type_id").getInt();
if (type_index > 0) type = DataValue::DataType(type_index - 1);
String value = query.getColumn("value").getString();
switch (type)
{
case DataValue::STRING_VALUE:
return DataValue(value);
case DataValue::INT_VALUE:
return DataValue(value.toInt());
case DataValue::DOUBLE_VALUE:
return DataValue(value.toDouble());
// converting lists to String adds square brackets - remove them:
case DataValue::STRING_LIST:
value = value.substr(1, value.size() - 2);
return DataValue(ListUtils::create<String>(value));
case DataValue::INT_LIST:
value = value.substr(1, value.size() - 2);
return DataValue(ListUtils::create<int>(value));
case DataValue::DOUBLE_LIST:
value = value.substr(1, value.size() - 2);
return DataValue(ListUtils::create<double>(value));
default: // DataValue::EMPTY_VALUE (avoid warning about missing return)
return DataValue();
}
}
bool OMSFileLoad::prepareQueryMetaInfo_(SQLite::Statement& query,
const String& parent_table)
{
String table_name = parent_table + "_MetaInfo";
if (!db_->tableExists(table_name)) return false;
String sql_select =
"SELECT * FROM " + table_name.toQString() + " AS MI " \
"WHERE MI.parent_id = :id";
if (version_number_ < 4)
{
sql_select =
"SELECT * FROM " + table_name.toQString() + " AS MI " \
"JOIN DataValue AS DV ON MI.data_value_id = DV.id " \
"WHERE MI.parent_id = :id";
}
query = SQLite::Statement(*db_, sql_select);
return true;
}
bool OMSFileLoad::prepareQueryAppliedProcessingStep_(SQLite::Statement& query,
const String& parent_table)
{
String table_name = parent_table + "_AppliedProcessingStep";
if (!db_->tableExists(table_name)) return false;
//
String sql_select = "SELECT * FROM " + table_name.toQString() +
" WHERE parent_id = :id ORDER BY processing_step_order ASC";
query = SQLite::Statement(*db_, sql_select);
return true;
}
void OMSFileLoad::handleQueryMetaInfo_(SQLite::Statement& query,
MetaInfoInterface& info,
Key parent_id)
{
query.bind(":id", parent_id);
while (query.executeStep())
{
DataValue value = makeDataValue_(query);
info.setMetaValue(query.getColumn("name").getString(), value);
}
query.reset(); // get ready for new executeStep()
}
void OMSFileLoad::handleQueryAppliedProcessingStep_(
SQLite::Statement& query,
IdentificationDataInternal::ScoredProcessingResult& result,
Key parent_id)
{
query.bind(":id", parent_id);
while (query.executeStep())
{
ID::AppliedProcessingStep step;
auto step_id_opt = query.getColumn("processing_step_id");
if (!step_id_opt.isNull())
{
step.processing_step_opt =
processing_step_refs_[step_id_opt.getInt64()];
}
auto score_type_opt = query.getColumn("score_type_id");
if (!score_type_opt.isNull())
{
step.scores[score_type_refs_[score_type_opt.getInt64()]] =
query.getColumn("score").getDouble();
}
result.addProcessingStep(step); // this takes care of merging the steps
}
query.reset(); // get ready for new executeStep()
}
void OMSFileLoad::loadDBSearchParams_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_DBSearchParam")) return;
SQLite::Statement query(*db_, "SELECT * FROM ID_DBSearchParam");
while (query.executeStep())
{
Key id = query.getColumn("id").getInt64();
ID::DBSearchParam param;
int molecule_type_index = query.getColumn("molecule_type_id").getInt() - 1;
param.molecule_type = ID::MoleculeType(molecule_type_index);
int mass_type_index = query.getColumn("mass_type_average").getInt();
param.mass_type = ID::MassType(mass_type_index);
param.database = query.getColumn("database").getString();
param.database_version = query.getColumn("database_version").getString();
param.taxonomy = query.getColumn("taxonomy").getString();
vector<Int> charges =
ListUtils::create<Int>(query.getColumn("charges").getString());
param.charges.insert(charges.begin(), charges.end());
vector<String> fixed_mods =
ListUtils::create<String>(query.getColumn("fixed_mods").getString());
param.fixed_mods.insert(fixed_mods.begin(), fixed_mods.end());
vector<String> variable_mods =
ListUtils::create<String>(query.getColumn("variable_mods").getString());
param.variable_mods.insert(variable_mods.begin(), variable_mods.end());
param.precursor_mass_tolerance =
query.getColumn("precursor_mass_tolerance").getDouble();
param.fragment_mass_tolerance =
query.getColumn("fragment_mass_tolerance").getDouble();
param.precursor_tolerance_ppm =
query.getColumn("precursor_tolerance_ppm").getInt();
param.fragment_tolerance_ppm =
query.getColumn("fragment_tolerance_ppm").getInt();
String enzyme = query.getColumn("digestion_enzyme").getString();
if (!enzyme.empty())
{
if (param.molecule_type == ID::MoleculeType::PROTEIN)
{
param.digestion_enzyme = ProteaseDB::getInstance()->getEnzyme(enzyme);
}
else if (param.molecule_type == ID::MoleculeType::RNA)
{
param.digestion_enzyme = RNaseDB::getInstance()->getEnzyme(enzyme);
}
}
if (version_number_ > 1)
{
String spec = query.getColumn("enzyme_term_specificity").getString();
param.enzyme_term_specificity = EnzymaticDigestion::getSpecificityByName(spec);
}
param.missed_cleavages = query.getColumn("missed_cleavages").getUInt();
param.min_length = query.getColumn("min_length").getUInt();
param.max_length = query.getColumn("max_length").getUInt();
ID::SearchParamRef ref = id_data.registerDBSearchParam(param);
search_param_refs_[id] = ref;
}
}
void OMSFileLoad::loadProcessingSteps_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_ProcessingStep")) return;
SQLite::Statement query(*db_, "SELECT * FROM ID_ProcessingStep");
SQLite::Statement subquery_file(*db_, "");
bool have_input_files = db_->tableExists(
"ID_ProcessingStep_InputFile");
if (have_input_files)
{
subquery_file = SQLite::Statement(*db_, "SELECT input_file_id " \
"FROM ID_ProcessingStep_InputFile " \
"WHERE processing_step_id = :id");
}
SQLite::Statement subquery_info(*db_, "");
bool have_meta_info = prepareQueryMetaInfo_(subquery_info, "ID_ProcessingStep");
while (query.executeStep())
{
Key id = query.getColumn("id").getInt64();
Key software_id = query.getColumn("software_id").getInt64();
ID::ProcessingStep step(processing_software_refs_[software_id]);
String date_time = query.getColumn("date_time").getString();
if (!date_time.empty()) step.date_time.set(date_time);
if (have_input_files)
{
subquery_file.bind(":id", id);
while (subquery_file.executeStep())
{
Key input_file_id = subquery_file.getColumn(0).getInt64();
// the foreign key constraint should ensure that look-up succeeds:
step.input_file_refs.push_back(input_file_refs_[input_file_id]);
}
subquery_file.reset(); // get ready for new executeStep()
}
if (have_meta_info)
{
handleQueryMetaInfo_(subquery_info, step, id);
}
ID::ProcessingStepRef ref;
auto opt_search_param_id = query.getColumn("search_param_id");
if (opt_search_param_id.isNull()) // no DB search params available
{
ref = id_data.registerProcessingStep(step);
}
else
{
ID::SearchParamRef search_param_ref =
search_param_refs_[opt_search_param_id.getInt64()];
ref = id_data.registerProcessingStep(step, search_param_ref);
}
processing_step_refs_[id] = ref;
}
}
void OMSFileLoad::loadObservations_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_Observation")) return;
SQLite::Statement query(*db_, "SELECT * FROM ID_Observation");
SQLite::Statement subquery_info(*db_, "");
bool have_meta_info = prepareQueryMetaInfo_(subquery_info,
"ID_Observation");
while (query.executeStep())
{
auto input_file_id = query.getColumn("input_file_id");
ID::Observation obs(query.getColumn("data_id").getString(),
input_file_refs_[input_file_id.getInt64()]);
auto rt = query.getColumn("rt");
if (!rt.isNull()) obs.rt = rt.getDouble();
auto mz = query.getColumn("mz");
if (!mz.isNull()) obs.mz = mz.getDouble();
Key id = query.getColumn("id").getInt64();
if (have_meta_info) handleQueryMetaInfo_(subquery_info, obs, id);
ID::ObservationRef ref = id_data.registerObservation(obs);
observation_refs_[id] = ref;
}
}
void OMSFileLoad::loadParentSequences_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_ParentSequence")) return;
SQLite::Statement query(*db_, "SELECT * FROM ID_ParentSequence");
// @TODO: can we combine handling of meta info and applied processing steps?
SQLite::Statement subquery_info(*db_, "");
bool have_meta_info = prepareQueryMetaInfo_(subquery_info,
"ID_ParentSequence");
SQLite::Statement subquery_step(*db_, "");
bool have_applied_steps =
prepareQueryAppliedProcessingStep_(subquery_step, "ID_ParentSequence");
while (query.executeStep())
{
String accession = query.getColumn("accession").getString();
ID::ParentSequence parent(accession);
int molecule_type_index = query.getColumn("molecule_type_id").getInt() - 1;
parent.molecule_type = ID::MoleculeType(molecule_type_index);
parent.sequence = query.getColumn("sequence").getString();
parent.description = query.getColumn("description").getString();
parent.coverage = query.getColumn("coverage").getDouble();
parent.is_decoy = query.getColumn("is_decoy").getInt();
Key id = query.getColumn("id").getInt64();
if (have_meta_info)
{
handleQueryMetaInfo_(subquery_info, parent, id);
}
if (have_applied_steps)
{
handleQueryAppliedProcessingStep_(subquery_step, parent, id);
}
ID::ParentSequenceRef ref = id_data.registerParentSequence(parent);
parent_sequence_refs_[id] = ref;
}
}
void OMSFileLoad::loadParentGroupSets_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_ParentGroupSet")) return;
// "grouping_order" column was removed in schema version 3:
String order_by = version_number_ > 2 ? "id" : "grouping_order";
SQLite::Statement query(*db_, "SELECT * FROM ID_ParentGroupSet ORDER BY " + order_by + " ASC");
// @TODO: can we combine handling of meta info and applied processing steps?
SQLite::Statement subquery_info(*db_, "");
bool have_meta_info = prepareQueryMetaInfo_(subquery_info,
"ID_ParentGroupSet");
SQLite::Statement subquery_step(*db_, "");
bool have_applied_steps =
prepareQueryAppliedProcessingStep_(subquery_step,
"ID_ParentGroupSet");
SQLite::Statement subquery_group(*db_, "SELECT * FROM ID_ParentGroup WHERE grouping_id = :id");
SQLite::Statement subquery_parent(*db_, "SELECT parent_id FROM ID_ParentGroup_ParentSequence WHERE group_id = :id");
while (query.executeStep())
{
ID::ParentGroupSet grouping(query.getColumn("label").getString());
Key grouping_id = query.getColumn("id").getInt64();
if (have_meta_info)
{
handleQueryMetaInfo_(subquery_info, grouping, grouping_id);
}
if (have_applied_steps)
{
handleQueryAppliedProcessingStep_(subquery_step, grouping, grouping_id);
}
subquery_group.bind(":id", grouping_id);
// get all groups in this grouping:
map<Key, ID::ParentGroup> groups_map;
while (subquery_group.executeStep())
{
Key group_id = subquery_group.getColumn("id").getInt64();
auto score_type_id = subquery_group.getColumn("score_type_id");
if (score_type_id.isNull()) // no scores
{
groups_map[group_id]; // insert empty group
}
else
{
ID::ScoreTypeRef ref = score_type_refs_[score_type_id.getInt64()];
groups_map[group_id].scores[ref] =
subquery_group.getColumn("score").getDouble();
}
}
subquery_group.reset(); // get ready for new executeStep()
// get parent sequences in each group:
for (auto& pair : groups_map)
{
subquery_parent.bind(":id", pair.first);
while (subquery_parent.executeStep())
{
Key parent_id = subquery_parent.getColumn(0).getInt64();
pair.second.parent_refs.insert(
parent_sequence_refs_[parent_id]);
}
subquery_parent.reset(); // get ready for new executeStep()
grouping.groups.insert(pair.second);
}
id_data.registerParentGroupSet(grouping);
}
}
void OMSFileLoad::loadIdentifiedCompounds_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_IdentifiedCompound")) return;
SQLite::Statement query(*db_, "SELECT * FROM ID_IdentifiedMolecule JOIN ID_IdentifiedCompound " \
"ON ID_IdentifiedMolecule.id = ID_IdentifiedCompound.molecule_id");
// @TODO: can we combine handling of meta info and applied processing steps?
SQLite::Statement subquery_info(*db_, "");
bool have_meta_info = prepareQueryMetaInfo_(subquery_info, "ID_IdentifiedMolecule");
SQLite::Statement subquery_step(*db_, "");
bool have_applied_steps =
prepareQueryAppliedProcessingStep_(subquery_step, "ID_IdentifiedMolecule");
while (query.executeStep())
{
ID::IdentifiedCompound compound(
query.getColumn("identifier").getString(),
EmpiricalFormula(query.getColumn("formula").getString()),
query.getColumn("name").getString(),
query.getColumn("smile").getString(),
query.getColumn("inchi").getString());
Key id = query.getColumn("id").getInt64();
if (have_meta_info)
{
handleQueryMetaInfo_(subquery_info, compound, id);
}
if (have_applied_steps)
{
handleQueryAppliedProcessingStep_(subquery_step, compound, id);
}
ID::IdentifiedCompoundRef ref = id_data.registerIdentifiedCompound(compound);
identified_molecule_vars_[id] = ref;
}
}
void OMSFileLoad::handleQueryParentMatch_(SQLite::Statement& query,
IdentificationData::ParentMatches& parent_matches,
Key molecule_id)
{
query.bind(":id", molecule_id);
while (query.executeStep())
{
ID::ParentSequenceRef ref = parent_sequence_refs_[query.getColumn("parent_id").getInt64()];
ID::ParentMatch match;
auto start_pos = query.getColumn("start_pos");
auto end_pos = query.getColumn("end_pos");
if (!start_pos.isNull()) match.start_pos = start_pos.getInt();
if (!end_pos.isNull()) match.end_pos = end_pos.getInt();
match.left_neighbor = query.getColumn("left_neighbor").getString();
match.right_neighbor = query.getColumn("right_neighbor").getString();
parent_matches[ref].insert(match);
}
query.reset(); // get ready for new executeStep()
}
void OMSFileLoad::loadIdentifiedSequences_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_IdentifiedMolecule")) return;
SQLite::Statement query(*db_, "SELECT * FROM ID_IdentifiedMolecule " \
"WHERE molecule_type_id = :molecule_type_id");
// @TODO: can we combine handling of meta info and applied processing steps?
SQLite::Statement subquery_info(*db_, "");
bool have_meta_info = prepareQueryMetaInfo_(subquery_info,
"ID_IdentifiedMolecule");
SQLite::Statement subquery_step(*db_, "");
bool have_applied_steps =
prepareQueryAppliedProcessingStep_(subquery_step,
"ID_IdentifiedMolecule");
SQLite::Statement subquery_parent(*db_, "");
bool have_parent_matches = db_->tableExists(
"ID_ParentMatch");
if (have_parent_matches)
{
subquery_parent = SQLite::Statement(*db_, "SELECT * FROM ID_ParentMatch " \
"WHERE molecule_id = :id");
}
// load peptides:
query.bind(":molecule_type_id", int(ID::MoleculeType::PROTEIN) + 1);
while (query.executeStep())
{
Key id = query.getColumn("id").getInt64();
String sequence = query.getColumn("identifier").getString();
ID::IdentifiedPeptide peptide(AASequence::fromString(sequence));
if (have_meta_info)
{
handleQueryMetaInfo_(subquery_info, peptide, id);
}
if (have_applied_steps)
{
handleQueryAppliedProcessingStep_(subquery_step, peptide, id);
}
if (have_parent_matches)
{
handleQueryParentMatch_(subquery_parent, peptide.parent_matches, id);
}
ID::IdentifiedPeptideRef ref = id_data.registerIdentifiedPeptide(peptide);
identified_molecule_vars_[id] = ref;
}
query.reset(); // get ready for new executeStep()
// load RNA oligos:
query.bind(":molecule_type_id", int(ID::MoleculeType::RNA) + 1);
while (query.executeStep())
{
Key id = query.getColumn("id").getInt64();
String sequence = query.getColumn("identifier").getString();
ID::IdentifiedOligo oligo(NASequence::fromString(sequence));
if (have_meta_info)
{
handleQueryMetaInfo_(subquery_info, oligo, id);
}
if (have_applied_steps)
{
handleQueryAppliedProcessingStep_(subquery_step, oligo, id);
}
if (have_parent_matches)
{
handleQueryParentMatch_(subquery_parent, oligo.parent_matches, id);
}
ID::IdentifiedOligoRef ref = id_data.registerIdentifiedOligo(oligo);
identified_molecule_vars_[id] = ref;
}
query.reset(); // get ready for new executeStep()
}
void OMSFileLoad::handleQueryPeakAnnotation_(SQLite::Statement& query,
ID::ObservationMatch& match,
Key parent_id)
{
query.bind(":id", parent_id);
while (query.executeStep())
{
auto processing_step_id = query.getColumn("processing_step_id");
std::optional<ID::ProcessingStepRef> processing_step_opt = std::nullopt;
if (!processing_step_id.isNull())
{
processing_step_opt =
processing_step_refs_[processing_step_id.getInt64()];
}
PeptideHit::PeakAnnotation ann;
ann.annotation = query.getColumn("peak_annotation").getString();
ann.charge = query.getColumn("peak_charge").getInt();
ann.mz = query.getColumn("peak_mz").getDouble();
ann.intensity = query.getColumn("peak_intensity").getDouble();
match.peak_annotations[processing_step_opt].push_back(ann);
}
query.reset(); // get ready for new executeStep()
}
void OMSFileLoad::loadAdducts_(IdentificationData& id_data)
{
if (!db_->tableExists("AdductInfo")) return;
SQLite::Statement query(*db_, "SELECT * FROM AdductInfo");
while (query.executeStep())
{
EmpiricalFormula formula(query.getColumn("formula").getString());
AdductInfo adduct(query.getColumn("name").getString(), formula,
query.getColumn("charge").getInt(),
query.getColumn("mol_multiplier").getInt());
ID::AdductRef ref = id_data.registerAdduct(adduct);
adduct_refs_[query.getColumn("id").getInt64()] = ref;
}
}
void OMSFileLoad::loadObservationMatches_(IdentificationData& id_data)
{
if (!db_->tableExists("ID_ObservationMatch")) return;
SQLite::Statement query(*db_, "SELECT * FROM ID_ObservationMatch");
// @TODO: can we combine handling of meta info and applied processing steps?
SQLite::Statement subquery_info(*db_, "");
bool have_meta_info = prepareQueryMetaInfo_(subquery_info,
"ID_ObservationMatch");
SQLite::Statement subquery_step(*db_, "");
bool have_applied_steps =
prepareQueryAppliedProcessingStep_(subquery_step,
"ID_ObservationMatch");
SQLite::Statement subquery_ann(*db_, "");
bool have_peak_annotations =
db_->tableExists("ID_ObservationMatch_PeakAnnotation");
if (have_peak_annotations)
{
subquery_ann = SQLite::Statement(*db_,
"SELECT * FROM ID_ObservationMatch_PeakAnnotation " \
"WHERE parent_id = :id");
}
while (query.executeStep())
{
Key id = query.getColumn("id").getInt64();
Key molecule_id = query.getColumn("identified_molecule_id").getInt64();
Key query_id = query.getColumn("observation_id").getInt64();
ID::ObservationMatch match(identified_molecule_vars_[molecule_id],
observation_refs_[query_id],
query.getColumn("charge").getInt());
auto adduct_id = query.getColumn("adduct_id"); // adduct is optional
if (!adduct_id.isNull())
{
match.adduct_opt = adduct_refs_[adduct_id.getInt64()];
}
if (have_meta_info)
{
handleQueryMetaInfo_(subquery_info, match, id);
}
if (have_applied_steps)
{
handleQueryAppliedProcessingStep_(subquery_step, match, id);
}
if (have_peak_annotations)
{
handleQueryPeakAnnotation_(subquery_ann, match, id);
}
ID::ObservationMatchRef ref = id_data.registerObservationMatch(match);
observation_match_refs_[id] = ref;
}
}
void OMSFileLoad::load(IdentificationData& id_data)
{
startProgress(0, 12, "Reading identification data from file");
loadInputFiles_(id_data);
nextProgress();
loadScoreTypes_(id_data);
nextProgress();
loadProcessingSoftwares_(id_data);
nextProgress();
loadDBSearchParams_(id_data);
nextProgress();
loadProcessingSteps_(id_data);
nextProgress();
loadObservations_(id_data);
nextProgress();
loadParentSequences_(id_data);
nextProgress();
loadParentGroupSets_(id_data);
nextProgress();
loadIdentifiedCompounds_(id_data);
nextProgress();
loadIdentifiedSequences_(id_data);
nextProgress();
loadAdducts_(id_data);
nextProgress();
loadObservationMatches_(id_data);
endProgress();
// @TODO: load input match groups
}
template <class MapType>
String OMSFileLoad::loadMapMetaDataTemplate_(MapType& features)
{
if (!db_->tableExists("FEAT_MapMetaData")) return "";
SQLite::Statement query(*db_, "SELECT * FROM FEAT_MapMetaData");
query.executeStep(); // there should be only one row
Key id = query.getColumn("unique_id").getInt64();
features.setUniqueId(id);
features.setIdentifier(query.getColumn("identifier").getString());
features.setLoadedFilePath(query.getColumn("file_path").getString());
String file_type = query.getColumn("file_type").getString();
features.setLoadedFilePath(FileTypes::nameToType(file_type));
SQLite::Statement query_meta(*db_, "");
if (prepareQueryMetaInfo_(query_meta, "FEAT_MapMetaData"))
{
handleQueryMetaInfo_(query_meta, features, id);
}
if (version_number_ < 5) return ""; // "experiment_type" column doesn't exist yet
return query.getColumn("experiment_type").getString(); // for consensus map only
}
// template specializations:
template String OMSFileLoad::loadMapMetaDataTemplate_<FeatureMap>(FeatureMap&);
template String OMSFileLoad::loadMapMetaDataTemplate_<ConsensusMap>(ConsensusMap&);
void OMSFileLoad::loadMapMetaData_(FeatureMap& features)
{
loadMapMetaDataTemplate_(features);
}
void OMSFileLoad::loadMapMetaData_(ConsensusMap& consensus)
{
String experiment_type = loadMapMetaDataTemplate_(consensus);
consensus.setExperimentType(experiment_type);
}
void OMSFileLoad::loadDataProcessing_(vector<DataProcessing>& data_processing)
{
if (!db_->tableExists("FEAT_DataProcessing")) return;
// "position" column was removed in schema version 3:
String order_by = version_number_ > 2 ? "id" : "position";
SQLite::Statement query(*db_, "SELECT * FROM FEAT_DataProcessing ORDER BY " + order_by + " ASC");
SQLite::Statement subquery_info(*db_, "");
bool have_meta_info = prepareQueryMetaInfo_(subquery_info, "FEAT_DataProcessing");
while (query.executeStep())
{
DataProcessing proc;
Software sw(query.getColumn("software_name").getString(),
query.getColumn("software_version").getString());
proc.setSoftware(sw);
vector<String> actions =
ListUtils::create<String>(query.getColumn("processing_actions").getString());
for (const String& action : actions)
{
auto pos = find(begin(DataProcessing::NamesOfProcessingAction),
end(DataProcessing::NamesOfProcessingAction), action);
if (pos != end(DataProcessing::NamesOfProcessingAction))
{
Size index = pos - begin(DataProcessing::NamesOfProcessingAction);
proc.getProcessingActions().insert(DataProcessing::ProcessingAction(index));
}
else // @TODO: throw an exception here?
{
OPENMS_LOG_ERROR << "Error: unknown data processing action '" << action << "' - skipping";
}
}
DateTime time;
time.set(query.getColumn("completion_time").getString());
proc.setCompletionTime(time);
if (have_meta_info)
{
Key id = query.getColumn("id").getInt64();
handleQueryMetaInfo_(subquery_info, proc, id);
}
data_processing.push_back(proc);
}
}
BaseFeature OMSFileLoad::makeBaseFeature_(int id, SQLite::Statement& query_feat,
SQLite::Statement& query_meta,
SQLite::Statement& query_match)
{
BaseFeature feature;
feature.setRT(query_feat.getColumn("rt").getDouble());
feature.setMZ(query_feat.getColumn("mz").getDouble());
feature.setIntensity(query_feat.getColumn("intensity").getDouble());
feature.setCharge(query_feat.getColumn("charge").getInt());
feature.setWidth(query_feat.getColumn("width").getDouble());
string quality_column = (version_number_ < 5) ? "overall_quality" : "quality";
feature.setQuality(query_feat.getColumn(quality_column.c_str()).getDouble());
feature.setUniqueId(query_feat.getColumn("unique_id").getInt64());
if (id == -1) return feature; // stop here for feature handles (in consensus maps)
auto primary_id = query_feat.getColumn("primary_molecule_id"); // optional
if (!primary_id.isNull())
{
feature.setPrimaryID(identified_molecule_vars_[primary_id.getInt64()]);
}
// meta data:
if (!isEmpty_(query_meta))
{
handleQueryMetaInfo_(query_meta, feature, id);
}
// ID matches:
if (!isEmpty_(query_match))
{
query_match.bind(":id", id);
while (query_match.executeStep())
{
Key match_id = query_match.getColumn("observation_match_id").getInt64();
feature.addIDMatch(observation_match_refs_[match_id]);
}
query_match.reset(); // get ready for new executeStep()
}
return feature;
}
void OMSFileLoad::prepareQueriesBaseFeature_(SQLite::Statement& query_meta,
SQLite::Statement& query_match)
{
// the "main" query is different for Feature/ConsensusFeature, so don't include it here
string main_table = (version_number_ < 5) ? "FEAT_Feature" : "FEAT_BaseFeature";
prepareQueryMetaInfo_(query_meta, main_table);
if (db_->tableExists("FEAT_ObservationMatch"))
{
query_match = SQLite::Statement(*db_, "SELECT * FROM FEAT_ObservationMatch WHERE feature_id = :id");
}
}
Feature OMSFileLoad::loadFeatureAndSubordinates_(
SQLite::Statement& query_feat, SQLite::Statement& query_meta,
SQLite::Statement& query_match, SQLite::Statement& query_hull)
{
int id = query_feat.getColumn("id").getInt();
Feature feature(makeBaseFeature_(id, query_feat, query_meta, query_match));
// Feature-specific attributes:
feature.setQuality(0, query_feat.getColumn("rt_quality").getDouble());
feature.setQuality(1, query_feat.getColumn("mz_quality").getDouble());
// convex hulls:
if (!isEmpty_(query_hull))
{
query_hull.bind(":id", id);
while (query_hull.executeStep())
{
Size hull_index = query_hull.getColumn("hull_index").getUInt();
// first row should have max. hull index (sorted descending):
if (feature.getConvexHulls().size() <= hull_index)
{
feature.getConvexHulls().resize(hull_index + 1);
}
ConvexHull2D::PointType point(query_hull.getColumn("point_x").getDouble(),
query_hull.getColumn("point_y").getDouble());
// @TODO: this may be inefficient (see implementation of "addPoint"):
feature.getConvexHulls()[hull_index].addPoint(point);
}
query_hull.reset(); // get ready for new executeStep()
}
// subordinates:
string from = (version_number_ < 5) ? "FEAT_Feature" : "FEAT_BaseFeature JOIN FEAT_Feature ON id = feature_id";
SQLite::Statement query_sub(*db_, "SELECT * FROM " + from + " WHERE subordinate_of = " + String(id) + " ORDER BY id ASC");
while (query_sub.executeStep())
{
Feature sub = loadFeatureAndSubordinates_(query_sub, query_meta,
query_match, query_hull);
feature.getSubordinates().push_back(sub);
}
return feature;
}
void OMSFileLoad::loadFeatures_(FeatureMap& features)
{
if (!db_->tableExists("FEAT_Feature")) return;
// start with top-level features only:
string from = (version_number_ < 5) ? "FEAT_Feature" : "FEAT_BaseFeature JOIN FEAT_Feature ON id = feature_id";
SQLite::Statement query_feat(*db_, "SELECT * FROM " + from + " WHERE subordinate_of IS NULL ORDER BY id ASC");
// prepare sub-queries (optional - corresponding tables may not be present):
SQLite::Statement query_meta(*db_, "");
SQLite::Statement query_match(*db_, "");
prepareQueriesBaseFeature_(query_meta, query_match);
SQLite::Statement query_hull(*db_, "");
if (db_->tableExists("FEAT_ConvexHull"))
{
query_hull = SQLite::Statement(*db_, "SELECT * FROM FEAT_ConvexHull WHERE feature_id = :id " \
"ORDER BY hull_index DESC, point_index ASC");
}
while (query_feat.executeStep())
{
Feature feature = loadFeatureAndSubordinates_(query_feat, query_meta,
query_match, query_hull);
features.push_back(feature);
}
}
void OMSFileLoad::load(FeatureMap& features)
{
load(features.getIdentificationData()); // load IDs, if any
startProgress(0, 3, "Reading feature data from file");
loadMapMetaData_(features);
nextProgress();
loadDataProcessing_(features.getDataProcessing());
nextProgress();
loadFeatures_(features);
endProgress();
}
void OMSFileLoad::loadConsensusFeatures_(ConsensusMap& consensus)
{
if (!db_->tableExists("FEAT_FeatureHandle")) return;
// start with top-level features only:
SQLite::Statement query_feat(*db_, "SELECT * FROM FEAT_BaseFeature LEFT JOIN FEAT_FeatureHandle ON id = feature_id ORDER BY id ASC");
// prepare sub-queries (optional - corresponding tables may not be present):
SQLite::Statement query_meta(*db_, "");
SQLite::Statement query_match(*db_, "");
prepareQueriesBaseFeature_(query_meta, query_match);
SQLite::Statement query_ratio(*db_, "");
if (db_->tableExists("FEAT_ConsensusRatio"))
{
query_ratio = SQLite::Statement(*db_, "SELECT * FROM FEAT_ConsensusRatio WHERE feature_id = :id " \
"ORDER BY ratio_index DESC");
}
while (query_feat.executeStep())
{
if (query_feat.getColumn("subordinate_of").isNull()) // ConsensusFeature
{
int id = query_feat.getColumn("id").getInt();
ConsensusFeature feature(makeBaseFeature_(id, query_feat, query_meta, query_match));
consensus.push_back(feature);
if (!isEmpty_(query_ratio))
{
query_ratio.bind(":id", id);
while (query_ratio.executeStep())
{
Size ratio_index = query_ratio.getColumn("ratio_index").getUInt();
// first row should have max. hull index (sorted descending):
if (feature.getRatios().size() <= ratio_index)
{
feature.getRatios().resize(ratio_index + 1);
}
ConsensusFeature::Ratio& ratio = feature.getRatios()[ratio_index];
ratio.ratio_value_ = query_ratio.getColumn("ratio_value").getDouble();
ratio.denominator_ref_ = query_ratio.getColumn("denominator_ref").getString();
ratio.numerator_ref_ = query_ratio.getColumn("numerator_ref").getString();
ratio.description_ = ListUtils::create<String>(query_ratio.getColumn("description").getString());
}
query_ratio.reset(); // get ready for new executeStep()
}
}
else // FeatureHandle
{
BaseFeature feature(makeBaseFeature_(-1, query_feat, query_meta, query_match));
UInt64 map_index = query_feat.getColumn("map_index").getInt64();
FeatureHandle handle(map_index, feature);
consensus.back().insert(handle);
}
}
}
void OMSFileLoad::loadConsensusColumnHeaders_(ConsensusMap& consensus)
{
consensus.getColumnHeaders().clear();
if (!db_->tableExists("FEAT_ConsensusColumnHeader")) return;
SQLite::Statement query(*db_, "SELECT * FROM FEAT_ConsensusColumnHeader");
SQLite::Statement query_info(*db_, "");
bool have_meta_info = prepareQueryMetaInfo_(query_info, "FEAT_ConsensusColumnHeader");
while (query.executeStep())
{
UInt64 id = query.getColumn("id").getInt64();
ConsensusMap::ColumnHeader header;
header.filename = query.getColumn("filename").getString();
header.label = query.getColumn("label").getString();
header.size = query.getColumn("size").getInt64();
header.unique_id = query.getColumn("unique_id").getInt64();
if (have_meta_info)
{
handleQueryMetaInfo_(query_info, header, id);
}
consensus.getColumnHeaders()[id] = header;
}
}
void OMSFileLoad::load(ConsensusMap& consensus)
{
load(consensus.getIdentificationData()); // load IDs, if any
startProgress(0, 4, "Reading feature data from file");
loadMapMetaData_(consensus);
nextProgress();
loadConsensusColumnHeaders_(consensus);
nextProgress();
loadDataProcessing_(consensus.getDataProcessing());
nextProgress();
loadConsensusFeatures_(consensus);
endProgress();
}
QJsonArray OMSFileLoad::exportTableToJSON_(const QString& table, const QString& order_by)
{
// code based on: https://stackoverflow.com/a/18067555
String sql = "SELECT * FROM " + table;
if (!order_by.isEmpty())
{
sql += " ORDER BY " + order_by;
}
SQLite::Statement query(*db_, sql);
QJsonArray array;
while (query.executeStep())
{
QJsonObject record;
for (int i = 0; i < query.getColumnCount(); ++i)
{
// @TODO: this will repeat field names for every row -
// avoid this with separate "header" and "rows" (array)?
// sqlite stores each cell based on the actual value, not the declared column type;
// thus, we could use query.getColumnDeclaredType(i), but it would incur conversion
switch (query.getColumn(i).getType())
{
case SQLITE_INTEGER: record.insert(query.getColumnName(i), qint64(query.getColumn(i).getInt64())); break;
case SQLITE_FLOAT: record.insert(query.getColumnName(i), query.getColumn(i).getDouble()); break;
case SQLITE_BLOB: record.insert(query.getColumnName(i), query.getColumn(i).getText()); break;
case SQLITE_NULL: record.insert(query.getColumnName(i), ""); break;
case SQLITE3_TEXT: record.insert(query.getColumnName(i), query.getColumn(i).getText()); break;
default:
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
}
array.push_back(record);
}
return array;
}
void OMSFileLoad::exportToJSON(ostream& output)
{
// @TODO: this constructs the whole JSON file in memory - write directly to stream instead?
// (more code, but would use less memory)
QJsonObject json_data;
// get names of all tables (except SQLite-internal ones) in the database:
SQLite::Statement query(*db_, "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name");
while (query.executeStep())
{
String table = query.getColumn("name").getString();
QString order_by = "id"; // row order for most tables
// special cases regarding ordering, e.g. tables without "id" column:
if (table.hasSuffix("_MetaInfo"))
{
order_by = "parent_id, name";
}
else if (table.hasSuffix("_AppliedProcessingStep"))
{
order_by = "parent_id, processing_step_order, score_type_id";
}
else if (auto pos = export_order_by_.find(table.toQString()); pos != export_order_by_.end())
{
order_by = pos->second;
}
json_data.insert(table.toQString(), exportTableToJSON_(table.toQString(), order_by));
}
QJsonDocument json_doc;
json_doc.setObject(json_data);
output << json_doc.toJson().toStdString();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/TransformationXMLFile.cpp | .cpp | 5,858 | 184 | // 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/FORMAT/TransformationXMLFile.h>
#include <fstream>
using namespace std;
namespace OpenMS
{
TransformationXMLFile::TransformationXMLFile() :
XMLHandler("", "1.1"),
XMLFile("/SCHEMAS/TrafoXML_1_1.xsd", "1.1"),
params_(), data_(), model_type_()
{
}
void TransformationXMLFile::load(const String& filename, TransformationDescription& transformation, bool fit_model)
{
//Filename for error messages in XMLHandler
file_ = filename;
params_.clear();
data_.clear();
model_type_.clear();
parse_(filename, this);
transformation.setDataPoints(data_);
if (fit_model)
{
transformation.fitModel(model_type_, params_);
}
}
void TransformationXMLFile::store(const String& filename, const TransformationDescription& transformation)
{
if (transformation.getModelType().empty())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "will not write a transformation with empty name");
}
//open stream
std::ofstream os(filename.c_str());
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
os.precision(writtenDigits<double>(0.0));
//write header
os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
//add XSLT file if it can be found
os << "<TrafoXML version=\"" << getVersion() << "\" xsi:noNamespaceSchemaLocation=\"https://raw.githubusercontent.com/OpenMS/OpenMS/develop/share/OpenMS/SCHEMAS/"
<< schema_location_.suffix('/') << "\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
// open tag
os << "\t<Transformation name=\"" << transformation.getModelType()
<< "\">\n";
// write parameters
const Param& params = transformation.getModelParameters();
for (Param::ParamIterator it = params.begin(); it != params.end(); ++it)
{
if (it->value.valueType() != ParamValue::EMPTY_VALUE)
{
switch (it->value.valueType())
{
case ParamValue::INT_VALUE:
os << "\t\t<Param type=\"int\" name=\"" << it->name << "\" value=\"" << it->value.toString() << "\"/>\n";
break;
case ParamValue::DOUBLE_VALUE:
os << "\t\t<Param type=\"float\" name=\"" << it->name << "\" value=\"" << it->value.toString() << "\"/>\n";
break;
case ParamValue::STRING_VALUE:
case ParamValue::STRING_LIST:
case ParamValue::INT_LIST:
case ParamValue::DOUBLE_LIST:
os << "\t\t<Param type=\"string\" name=\"" << it->name << "\" value=\"" << it->value.toString() << "\"/>\n";
break;
default: // no other value types are supported!
fatalError(STORE, String("Unsupported parameter type of parameter '") + it->name + "'");
break;
}
}
}
//write pairs
if (!transformation.getDataPoints().empty())
{
os << "\t\t<Pairs count=\"" << transformation.getDataPoints().size() << "\">\n";
for (TransformationDescription::DataPoints::const_iterator it = transformation.getDataPoints().begin();
it != transformation.getDataPoints().end(); ++it)
{
os << "\t\t\t<Pair from=\"" << it->first << "\" to=\"" << it->second;
if (!it->note.empty())
{
os << "\" note=\"" << writeXMLEscape(it->note);
}
os << "\"/>\n";
}
os << "\t\t</Pairs>\n";
}
// close tag
os << "\t</Transformation>\n";
//write footer
os << "</TrafoXML>\n";
//close stream
os.close();
}
void TransformationXMLFile::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes)
{
String element = sm_.convert(qname);
if (element == "TrafoXML")
{
//check file version against schema version
double file_version = attributeAsDouble_(attributes, "version");
if (file_version > version_.toDouble())
{
warning(LOAD, String("The XML file (") + file_version + ") is newer than the parser (" + version_ + "). This might lead to undefined program behavior.");
}
}
else if (element == "Transformation")
{
model_type_ = attributeAsString_(attributes, "name");
}
else if (element == "Param")
{
String type = attributeAsString_(attributes, "type");
if (type == "int")
{
params_.setValue(attributeAsString_(attributes, "name"), attributeAsInt_(attributes, "value"));
}
else if (type == "float")
{
params_.setValue(attributeAsString_(attributes, "name"), attributeAsDouble_(attributes, "value"));
}
else if (type == "string")
{
params_.setValue(attributeAsString_(attributes, "name"), String(attributeAsString_(attributes, "value")));
}
else
{
error(LOAD, String("Unsupported parameter type: '") + type + "'");
}
}
else if (element == "Pairs")
{
data_.reserve(attributeAsInt_(attributes, "count"));
}
else if (element == "Pair")
{
TransformationDescription::DataPoint point;
point.first = attributeAsDouble_(attributes, "from");
point.second = attributeAsDouble_(attributes, "to");
optionalAttributeAsString_(point.note, attributes, "note");
data_.push_back(point);
}
else
{
warning(LOAD, String("Unknown element: '") + element + "'");
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/PTMXMLFile.cpp | .cpp | 986 | 34 | // 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/FORMAT/PTMXMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/PTMXMLHandler.h>
using namespace std;
namespace OpenMS
{
PTMXMLFile::PTMXMLFile() = default;
void PTMXMLFile::load(const String & filename, map<String, pair<String, String> > & ptm_informations)
{
ptm_informations.clear();
Internal::PTMXMLHandler handler(ptm_informations, filename);
parse_(filename, &handler);
}
void PTMXMLFile::store(const String& filename, map<String, pair<String, String> > & ptm_informations) const
{
Internal::PTMXMLHandler handler(ptm_informations, filename);
save_(filename, &handler);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/TriqlerFile.cpp | .cpp | 15,560 | 398 | // 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, Lukas Heumos $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/TriqlerFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/ANALYSIS/ID/IDScoreSwitcherAlgorithm.h>
#include <tuple>
using namespace std;
using namespace OpenMS;
const String TriqlerFile::na_string_ = "NA";
void TriqlerFile::checkConditionLFQ_(const ExperimentalDesign::SampleSection& sampleSection,
const String& condition)
{
// Sample Section must contain the column that contains the condition used for Triqler
if (!sampleSection.hasFactor(condition))
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Sample Section of the experimental design does not contain condition column: " + condition);
}
}
//TODO why do we need this method and store everything three times??? (Once in the CMap, once in the feature
// of aggregatedConsensusInfo, and once in the other fields of aggregatedConsensusInfo)
// Cant we just get this stuff on the fly?
// We go through the features anyway again.
TriqlerFile::AggregatedConsensusInfo TriqlerFile::aggregateInfo_(const ConsensusMap& consensus_map,
const std::vector<String>& spectra_paths)
{
TriqlerFile::AggregatedConsensusInfo aggregatedInfo; //results
const auto &column_headers = consensus_map.getColumnHeaders(); // needed for label_id
for (const ConsensusFeature &consensus_feature : consensus_map)
{
vector<String> filenames;
vector<TriqlerFile::Intensity> intensities;
vector<TriqlerFile::Coordinate> retention_times;
vector<unsigned> cf_labels;
// Store the file names and the run intensities of this feature
const ConsensusFeature::HandleSetType& fs(consensus_feature.getFeatures());
for (const auto& feat : fs)
{
filenames.push_back(spectra_paths[feat.getMapIndex()]);
intensities.push_back(feat.getIntensity());
retention_times.push_back(feat.getRT());
// Get the label_id from the file description MetaValue
auto &column = column_headers.at(feat.getMapIndex());
if (column.metaValueExists("channel_id"))
{
cf_labels.push_back(Int(column.getMetaValue("channel_id")));
}
else
{
// label id 1 is used in case the experimental design specifies a LFQ experiment
//TODO Not really, according to the if-case it only cares about the metavalue.
// which could be missing due to other reasons
cf_labels.push_back(1u);
}
}
aggregatedInfo.consensus_feature_labels.push_back(cf_labels);
aggregatedInfo.consensus_feature_filenames.push_back(filenames);
aggregatedInfo.consensus_feature_intensities.push_back(intensities);
aggregatedInfo.consensus_feature_retention_times.push_back(retention_times);
aggregatedInfo.features.push_back(consensus_feature);
}
return aggregatedInfo;
}
//@todo LineType should be a template only for the line, not for the whole
// mapping structure. More exact type matching/info then.
void TriqlerFile::constructFile_(TextFile& csv_out,
const std::set<String>& peptideseq_quantifyable,
const MapSequenceToLines_& peptideseq_to_line) const
{
for (const auto& peptideseq : peptideseq_quantifyable)
{
for (const auto& line : peptideseq_to_line.at(peptideseq)) { csv_out.addLine(line.toString()); }
}
}
void TriqlerFile::storeLFQ(const String& filename,
const ConsensusMap& consensus_map,
const ExperimentalDesign& design,
const StringList& reannotate_filenames,
const String& condition)
{
// Experimental Design file
const ExperimentalDesign::SampleSection& sampleSection = design.getSampleSection();
if (design.getNumberOfLabels() != 1)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Too many labels for a label-free quantitation experiments. Please select the appropriate method, or validate the experimental design.");
}
checkConditionLFQ_(sampleSection, condition);
// assemble lookup table for run (each combination of pathname and fraction is a run)
std::map< pair< String, unsigned>, unsigned > run_map{};
assembleRunMap_(run_map, design);
// Maps run in Triqler input to run for OpenMS
map< unsigned, unsigned > Triqler_run_to_openms_fractiongroup;
// Mapping of filepath and label to sample and fraction
map< pair< String, unsigned >, unsigned> path_label_to_sample = design.getPathLabelToSampleMapping(true);
map< pair< String, unsigned >, unsigned> path_label_to_fraction = design.getPathLabelToFractionMapping(true);
map< pair< String, unsigned >, unsigned> path_label_to_fractiongroup = design.getPathLabelToFractionGroupMapping(true);
ExperimentalDesign::MSFileSection msfile_section = design.getMSFileSection();
// Extract the Spectra Filepath column from the design
std::vector<String> design_filenames{};
for (ExperimentalDesign::MSFileSectionEntry const& f : msfile_section)
{
const String fn = File::basename(f.path);
design_filenames.push_back(fn);
}
//vector< BaseFeature> features{};
vector< String > spectra_paths{};
//features.reserve(consensus_map.size());
if (reannotate_filenames.empty())
{
consensus_map.getPrimaryMSRunPath(spectra_paths);
}
else
{
spectra_paths = reannotate_filenames;
}
// Reduce spectra path to the basename of the files
for (Size i = 0; i < spectra_paths.size(); ++i)
{
spectra_paths[i] = File::basename(spectra_paths[i]);
}
if (!checkUnorderedContent_(spectra_paths, design_filenames))
{
OPENMS_LOG_FATAL_ERROR << "The filenames (extension ignored) in the consensusXML file are not the same as in the experimental design" << endl;
OPENMS_LOG_FATAL_ERROR << "Spectra files (consensus map): \n";
for (auto const & s : spectra_paths)
{
OPENMS_LOG_FATAL_ERROR << s << endl;
}
OPENMS_LOG_FATAL_ERROR << "Spectra files (design): \n";
for (auto const & s : design_filenames)
{
OPENMS_LOG_FATAL_ERROR << s << endl;
}
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The filenames (extension ignored) in the consensusXML file are not the same as in the experimental design");
}
// Extract information from the consensus features.
TriqlerFile::AggregatedConsensusInfo aggregatedInfo = TriqlerFile::aggregateInfo_(consensus_map, spectra_paths);
// The output file of the Triqler converter
TextFile csv_out;
// output the header
csv_out.addLine("run\tcondition\tcharge\tsearchScore\tintensity\tpeptide\tproteins");
if (consensus_map.getProteinIdentifications().empty())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"No protein information found in the ConsensusXML.");
}
// warn if we have more than one protein ID run
//TODO actually allow having more than one inference run e.g. for different conditions
if (consensus_map.getProteinIdentifications().size() > 1)
{
OPENMS_LOG_WARN << "Found " +
String(consensus_map.getProteinIdentifications().size()) +
" protein runs in consensusXML. Using first one only to parse inference data for now." << std::endl;
}
if (!consensus_map.getProteinIdentifications()[0].hasInferenceData())
{
OPENMS_LOG_WARN << "No inference was performed on the first run, defaulting to one-peptide-rule." << std::endl;
}
// We quantify indistinguishable groups with one (corner case) or multiple proteins.
// If indistinguishable groups are not annotated (no inference or only trivial inference has been performed) we assume
// that all proteins can be independently quantified (each forming an indistinguishable group).
// TODO currently we always create the mapping. If groups are missing we create it based on singletons which is
// quite unnecessary. Think about skipping if no groups are present
//consensus_map.getProteinIdentifications()[0].fillIndistinguishableGroupsWithSingletons();
const IndProtGrps& ind_prots = consensus_map.getProteinIdentifications()[0].getIndistinguishableProteins();
// Map protein accession to its indistinguishable group
std::unordered_map< String, const IndProtGrp* > accession_to_group = getAccessionToGroupMap_(ind_prots);
// To aggregate/uniquify on peptide sequence-level and save if a peptide is quantifyable
std::set<String> peptideseq_quantifyable; //set for deterministic ordering
// Stores all the lines that will be present in the final Triqler output
MapSequenceToLines_ peptideseq_to_line;
IDScoreSwitcherAlgorithm scores;
for (Size i = 0; i < aggregatedInfo.features.size(); ++i)
{
const BaseFeature &base_feature = aggregatedInfo.features[i];
for (const PeptideIdentification &pep_id : base_feature.getPeptideIdentifications())
{
if (!scores.isScoreType(pep_id.getScoreType(), IDScoreSwitcherAlgorithm::ScoreType::PEP))
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"TriqlerFile export expects Posterior Error Probabilities in the IDs of all features"
" to convert them to Posterior Probabilities.");
}
for (const PeptideHit & pep_hit : pep_id.getHits())
{
const String & sequence = pep_hit.getSequence().toString(); // to modified string
const double & search_score = pep_hit.getScore();
// check if all referenced protein accessions are part of the same indistinguishable group
// if so, we mark the sequence as quantifiable
std::set<String> accs = pep_hit.extractProteinAccessionsSet();
//Note: In general as long as we only support merged proteins across conditions,
// we check if the map is already set at this sequence since
// it cannot happen that to peptides with the same sequence map to different proteins unless something is wrong.
// Also I think Triqler cannot handle different associations to proteins across conditions.
if (isQuantifyable_(accs, accession_to_group))
{
peptideseq_quantifyable.emplace(sequence);
}
else
{
continue; // we don't need the rest of the loop
}
// Variables of the peptide hit
const Int precursor_charge = pep_hit.getCharge();
String accession = ListUtils::concatenate(accs, accdelim_);
if (accession.empty())
{
accession = na_string_; // shouldn't really matter since we skip unquantifiable peptides
}
// Write new line for each run
for (Size j = 0; j < aggregatedInfo.consensus_feature_filenames[i].size(); j++)
{
const String ¤t_filename = aggregatedInfo.consensus_feature_filenames[i][j];
const Intensity intensity(aggregatedInfo.consensus_feature_intensities[i][j]);
// const Coordinate retention_time(aggregatedInfo.consensus_feature_retention_times[i][j]);
const unsigned label(aggregatedInfo.consensus_feature_labels[i][j]);
const pair< String, unsigned> tpl1 = make_pair(current_filename, label);
const unsigned sample = path_label_to_sample[tpl1];
const unsigned fraction = path_label_to_fraction[tpl1];
const pair< String, unsigned> tpl2 = make_pair(current_filename, fraction);
// Resolve run
const unsigned run = run_map[tpl2]; // Triqler run according to the file table
const unsigned openms_fractiongroup = path_label_to_fractiongroup[tpl1];
Triqler_run_to_openms_fractiongroup[run] = openms_fractiongroup;
// Store Triqler line
peptideseq_to_line[sequence].insert(TriqlerLine_(
String(run),
sampleSection.getFactorValue(sample, condition),
String(precursor_charge),
String(1. - search_score),
String(intensity),
sequence,
accession));
}
}
}
}
// Print the run mapping between Triqler and OpenMS
for (const auto& run_mapping : Triqler_run_to_openms_fractiongroup)
{
cout << "Triqler run " << String(run_mapping.first)
<< " corresponds to OpenMS fraction group " << String(run_mapping.second) << endl;
}
constructFile_(csv_out,
peptideseq_quantifyable,
peptideseq_to_line);
// Store the final assembled CSV file
csv_out.store(filename);
}
bool TriqlerFile::checkUnorderedContent_(const std::vector<String> &first, const std::vector<String> &second)
{
const std::set< String > lhs(first.begin(), first.end());
const std::set< String > rhs(second.begin(), second.end());
return lhs == rhs
&& std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
void TriqlerFile::assembleRunMap_(
std::map< std::pair<String, unsigned>, unsigned> &run_map,
const ExperimentalDesign &design)
{
run_map.clear();
const ExperimentalDesign::MSFileSection& msfile_section = design.getMSFileSection();
unsigned run_counter = 1;
for (ExperimentalDesign::MSFileSectionEntry const& r : msfile_section)
{
std::pair< String, unsigned> tpl = std::make_pair(File::basename(r.path), r.fraction);
if (run_map.find(tpl) == run_map.end())
{
run_map[tpl] = run_counter++;
}
}
}
std::unordered_map<String, const IndProtGrp* > TriqlerFile::getAccessionToGroupMap_(const IndProtGrps& ind_prots)
{
std::unordered_map<String, const IndProtGrp* > res{};
for (const IndProtGrp& pgrp : ind_prots)
{
for (const String& a : pgrp.accessions)
{
res[a] = &(pgrp);
}
}
return res;
}
bool TriqlerFile::isQuantifyable_(
const std::set<String>& accs,
const std::unordered_map<String, const IndProtGrp*>& accession_to_group) const
{
if (accs.empty())
{
return false;
}
if (accs.size() == 1)
{
return true;
}
auto git = accession_to_group.find(*accs.begin());
if (git == accession_to_group.end())
{
return false;
}
const IndProtGrp* grp = git->second;
// every prot accession in the set needs to belong to the same indist. group to make this peptide
// eligible for quantification
auto accit = ++accs.begin();
for (; accit != accs.end(); ++accit)
{
const auto it = accession_to_group.find(*accit);
// we assume that it is a singleton. Cannot be quantifiable anymore.
// Set makes them unique. Non-membership in groups means that there is at least one other
// non-agreeing protein in the set.
if (it == accession_to_group.end())
{
return false;
}
// check if two different groups
if (it->second != grp)
{
return false;
}
}
return true;
}
String TriqlerFile::TriqlerLine_::toString() const
{
const String delim("\t");
return run_
+ delim + condition_
+ delim + precursor_charge_
+ delim + search_score_
+ delim + intensity_
+ delim + sequence_
+ delim + accession_;
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/SqMassFile.cpp | .cpp | 3,398 | 95 | // 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/FORMAT/SqMassFile.h>
#include <OpenMS/FORMAT/HANDLERS/MzMLSqliteHandler.h>
namespace OpenMS
{
SqMassFile::SqMassFile() = default;
SqMassFile::~SqMassFile() = default;
void SqMassFile::load(const String& filename, MapType& map) const
{
OpenMS::Internal::MzMLSqliteHandler sql_mass(filename, 0);
sql_mass.setConfig(config_.write_full_meta, config_.use_lossy_numpress, config_.linear_fp_mass_acc);
sql_mass.readExperiment(map);
}
void SqMassFile::store(const String& filename, const MapType& map) const
{
OpenMS::Internal::MzMLSqliteHandler sql_mass(filename, map.getSqlRunID());
sql_mass.setConfig(config_.write_full_meta, config_.use_lossy_numpress, config_.linear_fp_mass_acc);
sql_mass.createTables();
sql_mass.writeExperiment(map);
}
void SqMassFile::transform(const String& filename_in, Interfaces::IMSDataConsumer* consumer, bool /* skip_full_count */, bool /* skip_first_pass */) const
{
OpenMS::Internal::MzMLSqliteHandler sql_mass(filename_in, 0);
sql_mass.setConfig(config_.write_full_meta, config_.use_lossy_numpress, config_.linear_fp_mass_acc);
// First pass through the file -> get the meta-data and hand it to the consumer
// if (!skip_first_pass) transformFirstPass_(filename_in, consumer, skip_full_count);
consumer->setExpectedSize(sql_mass.getNrSpectra(), sql_mass.getNrChromatograms());
MSExperiment experimental_settings;
sql_mass.readExperiment(experimental_settings, true);
consumer->setExperimentalSettings(experimental_settings);
{
int batch_size = 500;
std::vector<int> indices;
for (size_t batch_idx = 0; batch_idx <= (sql_mass.getNrSpectra() / batch_size); batch_idx++)
{
int idx_start, idx_end;
idx_start = batch_idx * batch_size;
idx_end = std::max(batch_idx * (batch_size+1), sql_mass.getNrSpectra());
indices.resize(idx_end - idx_start);
for (int k = 0; k < idx_end-idx_start; k++)
{
indices[k] = idx_start + k;
}
std::vector<MSSpectrum> tmp_spectra;
sql_mass.readSpectra(tmp_spectra, indices, false);
for (Size k = 0; k < tmp_spectra.size(); k++)
{
consumer->consumeSpectrum(tmp_spectra[k]);
}
}
}
{
int batch_size = 500;
std::vector<int> indices;
for (size_t batch_idx = 0; batch_idx <= (sql_mass.getNrChromatograms() / batch_size); batch_idx++)
{
int idx_start, idx_end;
idx_start = batch_idx * batch_size;
idx_end = std::max(batch_idx * (batch_size+1), sql_mass.getNrChromatograms());
indices.resize(idx_end - idx_start);
for (int k = 0; k < idx_end-idx_start; k++)
{
indices[k] = idx_start + k;
}
std::vector<MSChromatogram> tmp_chroms;
sql_mass.readChromatograms(tmp_chroms, indices, false);
for (Size k = 0; k < tmp_chroms.size(); k++)
{
consumer->consumeChromatogram(tmp_chroms[k]);
}
}
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/XMassFile.cpp | .cpp | 508 | 19 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Guillaume Belz $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/XMassFile.h>
namespace OpenMS
{
XMassFile::XMassFile() = default;
XMassFile::~XMassFile() = default;
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/PeakTypeEstimator.cpp | .cpp | 458 | 18 | // 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/FORMAT/PeakTypeEstimator.h>
using namespace std;
namespace OpenMS
{
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MzTabMFile.cpp | .cpp | 24,327 | 633 | // 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/Exception.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/MzTabFile.h>
#include <OpenMS/FORMAT/MzTabMFile.h>
#include <OpenMS/FORMAT/TextFile.h>
namespace OpenMS
{
MzTabMFile::MzTabMFile()= default;
MzTabMFile::~MzTabMFile()= default;
void MzTabMFile::generateMzTabMMetaDataSection_(const MzTabMMetaData& md, StringList& sl) const
{
sl.push_back(String("MTD\tmzTab-version\t") + md.mz_tab_version.toCellString()); // mandatory
sl.push_back(String("MTD\tmzTab-ID\t") + md.mz_tab_id.toCellString()); // mandatory
if (!md.title.isNull())
{
String s = String("MTD\ttitle\t") + md.title.toCellString();
sl.push_back(s);
}
if(!md.description.isNull())
{
String s = String("MTD\tdescription\t") + md.description.toCellString();
sl.push_back(s);
}
for (const auto& sp : md.sample_processing)
{
String s = "MTD\tsample_processing[" + String(sp.first) + "]\t" + sp.second.toCellString();
sl.push_back(s);
}
for (const auto& inst : md.instrument)
{
const MzTabInstrumentMetaData& imd = inst.second;
if (!imd.name.isNull())
{
String s = "MTD\tinstrument[" + String(inst.first) + "]-name\t" + imd.name.toCellString();
sl.push_back(s);
}
if (!imd.source.isNull())
{
String s = "MTD\tinstrument[" + String(inst.first) + "]-source\t" + imd.source.toCellString();
sl.push_back(s);
}
for (const auto& mit : imd.analyzer)
{
if (!mit.second.isNull())
{
String s = "MTD\tinstrument[" + String(inst.first) + "]-analyzer[" + String(mit.first) + "]\t" + mit.second.toCellString();
sl.push_back(s);
}
}
if (!imd.detector.isNull())
{
String s = "MTD\tinstrument[" + String(inst.first) + "]-detector\t" + imd.detector.toCellString();
sl.push_back(s);
}
}
for (const auto & sw : md.software)
{
MzTabSoftwareMetaData msmd = sw.second;
String s = "MTD\tsoftware[" + String(sw.first) + "]\t" + msmd.software.toCellString(); // mandatory
sl.push_back(s);
for (const auto& setting : msmd.setting)
{
String s = "MTD\tsoftware[" + String(sw.first) + "]-setting[" + String(setting.first) + String("]\t") + setting.second.toCellString();
sl.push_back(s);
}
}
for (auto const& pub : md.publication)
{
String s = "MTD\tpublication[" + String(pub.first) + "]\t" + pub.second.toCellString();
sl.push_back(s);
}
for (const auto& contact : md.contact)
{
const MzTabContactMetaData& md = contact.second;
if (!md.name.isNull())
{
String s = "MTD\tcontact[" + String(contact.first) + "]-name\t" + md.name.toCellString();
sl.push_back(s);
}
if (!md.affiliation.isNull())
{
String s = "MTD\tcontact[" + String(contact.first) + "]-affiliation\t" + md.affiliation.toCellString();
sl.push_back(s);
}
if (!md.email.isNull())
{
String s = "MTD\tcontact[" + String(contact.first) + "]-email\t" + md.email.toCellString();
sl.push_back(s);
}
}
for (const auto& uri : md.uri)
{
String s = "MTD\turi[" + String(uri.first) + "]\t" + uri.second.toCellString();
sl.push_back(s);
}
for (const auto& ext_study : md.external_study_uri)
{
String s = "MTD\texternal_study_uri[" + String(ext_study.first) + "]\t" + ext_study.second.toCellString();
sl.push_back(s);
}
String s = String("MTD\tquantification_method\t") + md.quantification_method.toCellString(); // mandatory
sl.push_back(s);
for (const auto& sample : md.sample)
{
const MzTabSampleMetaData& msmd = sample.second;
if (!msmd.description.isNull())
{
String s = "MTD\tsample[" + String(sample.first) + "]-description\t" + msmd.description.toCellString();
sl.push_back(s);
}
for (const auto& species : msmd.species)
{
String s = "MTD\tsample[" + String(sample.first) + "]-species[" + String(species.first) + "]\t" + species.second.toCellString();
sl.push_back(s);
}
for (const auto& tissue : msmd.tissue)
{
String s = "MTD\tsample[" + String(sample.first) + "]-tissue[" + String(tissue.first) + "]\t" + tissue.second.toCellString();
sl.push_back(s);
}
for (const auto& cell_type : msmd.cell_type)
{
String s = "MTD\tsample[" + String(sample.first) + "]-cell_type[" + String(cell_type.first) + "]\t" + cell_type.second.toCellString();
sl.push_back(s);
}
for (auto const& disease : msmd.disease)
{
String s = "MTD\tsample[" + String(sample.first) + "]-disease[" + String(disease.first) + "]\t" + disease.second.toCellString();
sl.push_back(s);
}
for (const auto& custom : msmd.custom)
{
String s = "MTD\tsample[" + String(sample.first) + "]-custom[" + String(custom.first) + "]\t" + custom.second.toCellString();
sl.push_back(s);
}
}
for (const auto& ms_run : md.ms_run)
{
const MzTabMMSRunMetaData& rmmd = ms_run.second;
String s = "MTD\tms_run[" + String(ms_run.first) + "]-location\t" + rmmd.location.toCellString(); // mandatory
sl.push_back(s);
if (!rmmd.instrument_ref.isNull())
{
String s = "MTD\tms_run[" + String(ms_run.first) + "]-instrument_ref\t" + rmmd.instrument_ref.toCellString();
sl.push_back(s);
}
if (!rmmd.format.isNull())
{
String s = "MTD\tms_run[" + String(ms_run.first) + "]-format\t" + rmmd.format.toCellString();
sl.push_back(s);
}
for (const auto& fragmentation_method : rmmd.fragmentation_method)
{
String s = "MTD\tms_run[" + String(ms_run.first) + "]-fragmentation_method[" + String(fragmentation_method.first) + "]\t" + fragmentation_method.second.toCellString();
sl.push_back(s);
}
for (const auto& scan_polarity : rmmd.scan_polarity)
{
String s = "MTD\tms_run[" + String(ms_run.first) + "]-scan_polarity[" + String(scan_polarity.first) + "]\t" + scan_polarity.second.toCellString(); // mandatory
sl.push_back(s);
}
if (!rmmd.hash.isNull())
{
String s = "MTD\tms_run[" + String(ms_run.first) + "]-hash\t" + rmmd.hash.toCellString();
sl.push_back(s);
}
if (!rmmd.hash_method.isNull())
{
String s = "MTD\tms_run[" + String(ms_run.first) + "]-hash_method\t" + rmmd.hash_method.toCellString();
sl.push_back(s);
}
}
for (const auto& assay : md.assay)
{
const MzTabMAssayMetaData& amd = assay.second;
String name = "MTD\tassay[" + String(assay.first) + "]\t" + amd.name.toCellString(); // mandatory
sl.push_back(name);
for (const auto& custom : amd.custom)
{
String s = "MTD\tms_run[" + String(assay.first) + "]-custom[" + String(custom.first) + "]\t" + custom.second.toCellString();
sl.push_back(s);
}
if (!amd.external_uri.isNull())
{
String s = "MTD\tassay[" + String(assay.first) + "]-external_uri\t" + amd.external_uri.toCellString();
sl.push_back(s);
}
if (!amd.sample_ref.isNull())
{
String s = "MTD\tassay[" + String(assay.first) + "]-sample_ref\tsample[" + amd.sample_ref.toCellString() + "]";
sl.push_back(s);
}
String ms_run_ref = "MTD\tassay[" + String(assay.first) + "]-ms_run_ref\tms_run[" + amd.ms_run_ref.toCellString() + "]"; // mandatory
sl.push_back(ms_run_ref);
}
for (const auto& sv : md.study_variable)
{
const MzTabMStudyVariableMetaData& svmd = sv.second;
String name = "MTD\tstudy_variable[" + String(sv.first) + "]\t" + svmd.name.toCellString(); // mandatory
sl.push_back(name);
std::vector<MzTabString> strings;
MzTabStringList refs_string;
for (const auto& ref : svmd.assay_refs)
{
strings.emplace_back(MzTabString("assay[" + std::to_string(ref) + ']'));
}
refs_string.set(strings);
String refs = "MTD\tstudy_variable[" + String(sv.first) + "]-assay_refs\t" + refs_string.toCellString(); // mandatory
sl.push_back(refs);
if (!svmd.average_function.isNull())
{
String s = "MTD\tstudy_variable[" + String(sv.first) + "]-average_function\t" + svmd.average_function.toCellString();
sl.push_back(s);
}
if (!svmd.variation_function.isNull())
{
String s = "MTD\tstudy_variable[" + String(sv.first) + "]-variation_function\t" + svmd.variation_function.toCellString();
sl.push_back(s);
}
String description = "MTD\tstudy_variable[" + String(sv.first) + "]-description\t" + svmd.description.toCellString(); // mandatory
sl.push_back(description);
for (const auto& factor : svmd.factors.get())
{
String s = "MTD\tstudy_variable[" + String(sv.first) + "]-factors\t" + factor.toCellString();
sl.push_back(s);
}
}
for (const auto& custom : md.custom)
{
String s = "MTD\tcustom[" + String(custom.first) + "]\t" + custom.second.toCellString();
sl.push_back(s);
}
for (const auto& cv : md.cv)
{
const MzTabCVMetaData& cvmd = cv.second;
String label = "MTD\tcv[" + String(cv.first) + "]-label\t" + cvmd.label.toCellString(); // mandatory
sl.push_back(label);
String full_name = "MTD\tcv[" + String(cv.first) + "]-full_name\t" + cvmd.full_name.toCellString(); // mandatory
sl.push_back(full_name);
String version = "MTD\tcv[" + String(cv.first) + "]-version\t" + cvmd.version.toCellString(); // mandatory
sl.push_back(version);
String url = "MTD\tcv[" + String(cv.first) + "]-uri\t" + cvmd.url.toCellString(); // mandatory
sl.push_back(url);
}
for (const auto& db : md.database)
{
MzTabMDatabaseMetaData dbmd = db.second;
String database = "MTD\tdatabase[" + String(db.first) + "]\t" + dbmd.database.toCellString(); // mandatory
sl.push_back(database);
String prefix = "MTD\tdatabase[" + String(db.first) + "]-prefix\t" + dbmd.prefix.toCellString(); // mandatory
sl.push_back(prefix);
String version = "MTD\tdatabase[" + String(db.first) + "]-version\t" + dbmd.version.toCellString(); // mandatory
sl.push_back(version);
String uri = "MTD\tdatabase[" + String(db.first) + "]-uri\t" + dbmd.uri.toCellString(); // mandatory
sl.push_back(uri);
}
for (const auto& agent : md.derivatization_agent)
{
String s = "MTD\tderivatization_agent[" + String(agent.first) + "]-uri\t" + agent.second.toCellString();
sl.push_back(s);
}
sl.push_back(String("MTD\tsmall_molecule-quantification_unit\t") + md.small_molecule_quantification_unit.toCellString()); // mandatory
sl.push_back(String("MTD\tsmall_molecule_feature-quantification_unit\t") + md.small_molecule_feature_quantification_unit.toCellString()); // mandatory (feature section)
sl.push_back(String("MTD\tsmall_molecule-identification_reliability\t") + md.small_molecule_identification_reliability.toCellString()); // mandatory
for (const auto& id_conf : md.id_confidence_measure)
{
String s = "MTD\tid_confidence_measure[" + String(id_conf.first) + "]\t" + id_conf.second.toCellString(); // mandatory
sl.push_back(s);
}
for (const auto& csm : md.colunit_small_molecule)
{
String s = "MTD\tcolunit_small_molecule\t" + csm.toCellString();
sl.push_back(s);
}
for (const auto& csmf : md.colunit_small_molecule_feature)
{
String s = "MTD\tcolunit_small_molecule\t" + csmf.toCellString();
sl.push_back(s);
}
for (const auto& csme : md.colunit_small_molecule_evidence)
{
String s = "MTD\tcolunit_small_molecule\t" + csme.toCellString();
sl.push_back(s);
}
}
String MzTabMFile::generateMzTabMSmallMoleculeHeader_(const MzTabMMetaData& meta, const std::vector<String>& optional_columns, size_t& n_columns) const
{
StringList header;
header.emplace_back("SMH");
header.emplace_back("SML_ID");
header.emplace_back("SMF_ID_REFS");
header.emplace_back("database_identifier");
header.emplace_back("chemical_formula");
header.emplace_back("smiles");
header.emplace_back("inchi");
header.emplace_back("chemical_name");
header.emplace_back("uri");
header.emplace_back("theoretical_neutral_mass");
header.emplace_back("adduct_ions");
header.emplace_back("reliability");
header.emplace_back("best_id_confidence_measure");
header.emplace_back("best_id_confidence_value");
for (const auto& a : meta.assay)
{
header.emplace_back(String("abundance_assay[") + String(a.first) + String("]"));
}
for (const auto& a : meta.study_variable)
{
header.emplace_back(String("abundance_study_variable[") + String(a.first) + String("]"));
}
for (const auto& a : meta.study_variable)
{
header.emplace_back(String("abundance_variation_study_variable[") + String(a.first) + String("]"));
}
std::copy(optional_columns.begin(), optional_columns.end(), std::back_inserter(header));
n_columns = header.size();
return ListUtils::concatenate(header, "\t");
}
String MzTabMFile::generateMzTabMSmallMoleculeSectionRow_(const MzTabMSmallMoleculeSectionRow& row, const std::vector<String>& optional_columns, size_t& n_columns) const
{
StringList s;
s.emplace_back("SML");
s.emplace_back(row.sml_identifier.toCellString());
s.emplace_back(row.smf_id_refs.toCellString());
s.emplace_back(row.database_identifier.toCellString());
s.emplace_back(row.chemical_formula.toCellString());
s.emplace_back(row.smiles.toCellString());
s.emplace_back(row.inchi.toCellString());
s.emplace_back(row.chemical_name.toCellString());
s.emplace_back(row.uri.toCellString());
s.emplace_back(row.theoretical_neutral_mass.toCellString());
s.emplace_back(row.adducts.toCellString());
s.emplace_back(row.reliability.toCellString());
s.emplace_back(row.best_id_confidence_measure.toCellString());
s.emplace_back(row.best_id_confidence_value.toCellString());
for (const auto& abundance_assay : row.small_molecule_abundance_assay)
{
s.emplace_back(abundance_assay.second.toCellString());
}
for (const auto& abundance_study_variable : row.small_molecule_abundance_study_variable)
{
s.emplace_back(abundance_study_variable.second.toCellString());
}
for (const auto& variation_study_variable : row.small_molecule_abundance_variation_study_variable)
{
s.emplace_back(variation_study_variable.second.toCellString());
}
MzTabFile::addOptionalColumnsToSectionRow_(optional_columns, row.opt_, s);
n_columns = s.size();
return ListUtils::concatenate(s, "\t");
}
String MzTabMFile::generateMzTabMSmallMoleculeFeatureHeader_(const MzTabMMetaData& meta, const std::vector<String>& optional_columns, size_t& n_columns) const
{
StringList header;
header.emplace_back("SFH");
header.emplace_back("SMF_ID");
header.emplace_back("SME_ID_REFS");
header.emplace_back("SME_ID_REF_ambiguity_code");
header.emplace_back("adduct_ion");
header.emplace_back("isotopomer");
header.emplace_back("exp_mass_to_charge");
header.emplace_back("charge");
header.emplace_back("retention_time_in_seconds");
header.emplace_back("retention_time_in_seconds_start");
header.emplace_back("retention_time_in_seconds_end");
for (const auto& a : meta.assay)
{
header.emplace_back(String("abundance_assay[") + String(a.first) + String("]"));
}
std::copy(optional_columns.begin(), optional_columns.end(), std::back_inserter(header));
n_columns = header.size();
return ListUtils::concatenate(header, "\t");
}
String MzTabMFile::generateMzTabMSmallMoleculeFeatureSectionRow_(const MzTabMSmallMoleculeFeatureSectionRow& row, const std::vector<String>& optional_columns, size_t& n_columns) const
{
StringList s;
s.emplace_back("SMF");
s.emplace_back(row.smf_identifier.toCellString());
s.emplace_back(row.sme_id_refs.toCellString());
s.emplace_back(row.sme_id_ref_ambiguity_code.toCellString());
s.emplace_back(row.adduct.toCellString());
s.emplace_back(row.isotopomer.toCellString());
s.emplace_back(row.exp_mass_to_charge.toCellString());
s.emplace_back(row.charge.toCellString());
s.emplace_back(row.retention_time.toCellString());
s.emplace_back(row.rt_start.toCellString());
s.emplace_back(row.rt_end.toCellString());
for (const auto& feature_abundance : row.small_molecule_feature_abundance_assay)
{
s.emplace_back(feature_abundance.second.toCellString());
}
MzTabFile::addOptionalColumnsToSectionRow_(optional_columns, row.opt_, s);
n_columns = s.size();
return ListUtils::concatenate(s, "\t");
}
String MzTabMFile::generateMzTabMSmallMoleculeEvidenceHeader_(const MzTabMMetaData& meta, const std::vector<String>& optional_columns, size_t& n_columns) const
{
StringList header;
header.emplace_back("SEH");
header.emplace_back("SME_ID");
header.emplace_back("evidence_input_id");
header.emplace_back("database_identifier");
header.emplace_back("chemical_formula");
header.emplace_back("smiles");
header.emplace_back("inchi");
header.emplace_back("chemical_name");
header.emplace_back("uri");
header.emplace_back("derivatized_form");
header.emplace_back("adduct_ion");
header.emplace_back("exp_mass_to_charge");
header.emplace_back("charge");
header.emplace_back("theoretical_mass_to_charge");
header.emplace_back("spectra_ref");
header.emplace_back("identification_method");
header.emplace_back("ms_level");
for (const auto& id_conf : meta.id_confidence_measure)
{
header.emplace_back(String("id_confidence_measure[") + String(id_conf.first) + String("]"));
}
header.emplace_back("rank");
std::copy(optional_columns.begin(), optional_columns.end(), std::back_inserter(header));
n_columns = header.size();
return ListUtils::concatenate(header, "\t");
}
String MzTabMFile::generateMzTabMSmallMoleculeEvidenceSectionRow_(const MzTabMSmallMoleculeEvidenceSectionRow& row, const std::vector<String>& optional_columns, size_t& n_columns) const
{
StringList s;
s.emplace_back("SME");
s.emplace_back(row.sme_identifier.toCellString());
s.emplace_back(row.evidence_input_id.toCellString());
s.emplace_back(row.database_identifier.toCellString());
s.emplace_back(row.chemical_formula.toCellString());
s.emplace_back(row.smiles.toCellString());
s.emplace_back(row.inchi.toCellString());
s.emplace_back(row.chemical_name.toCellString());
s.emplace_back(row.uri.toCellString());
s.emplace_back(row.derivatized_form.toCellString());
s.emplace_back(row.adduct.toCellString());
s.emplace_back(row.exp_mass_to_charge.toCellString());
s.emplace_back(row.charge.toCellString());
s.emplace_back(row.calc_mass_to_charge.toCellString());
s.emplace_back(row.spectra_ref.toCellString());
s.emplace_back(row.identification_method.toCellString());
s.emplace_back(row.ms_level.toCellString());
for (const auto& id_conf : row.id_confidence_measure)
{
s.emplace_back(id_conf.second.toCellString());
}
s.emplace_back(row.rank.toCellString());
MzTabFile::addOptionalColumnsToSectionRow_(optional_columns, row.opt_, s);
n_columns = s.size();
return ListUtils::concatenate(s, "\t");
}
void MzTabMFile::store(const String& filename, const MzTabM& mztab_m) const
{
OPENMS_LOG_INFO << "exporting identification data: \"" << filename << "\" to MzTab-M: " << std::endl;
if (!(FileHandler::hasValidExtension(filename, FileTypes::MZTAB) || FileHandler::hasValidExtension(filename, FileTypes::TSV)))
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "invalid file extension, expected '"
+ FileTypes::typeToName(FileTypes::MZTAB) + "' or '" + FileTypes::typeToName(FileTypes::TSV) + "'");
}
StringList out;
generateMzTabMMetaDataSection_(mztab_m.getMetaData(), out);
size_t n_sml_header_columns = 0;
out.emplace_back("");
out.emplace_back(generateMzTabMSmallMoleculeHeader_(mztab_m.getMetaData(),
mztab_m.getMSmallMoleculeOptionalColumnNames(),
n_sml_header_columns));
size_t n_sml_section_columns = 0;
const MzTabMSmallMoleculeSectionRows& sm_section = mztab_m.getMSmallMoleculeSectionRows();
for (const auto& sms_row: sm_section)
{
out.emplace_back(generateMzTabMSmallMoleculeSectionRow_(sms_row,
mztab_m.getMSmallMoleculeOptionalColumnNames(),
n_sml_section_columns));
OPENMS_POSTCONDITION(n_sml_header_columns == n_sml_section_columns,
"The number of columns of the small molecule header do not assort to the number of columns of the small molecule section row.")
}
size_t n_smf_header_columns = 0;
out.emplace_back("");
out.emplace_back(generateMzTabMSmallMoleculeFeatureHeader_(mztab_m.getMetaData(),
mztab_m.getMSmallMoleculeFeatureOptionalColumnNames(),
n_smf_header_columns));
size_t n_smf_section_columns = 0;
const MzTabMSmallMoleculeFeatureSectionRows& feature_section = mztab_m.getMSmallMoleculeFeatureSectionRows();
for (const auto& smf_row : feature_section)
{
out.emplace_back(generateMzTabMSmallMoleculeFeatureSectionRow_(smf_row,
mztab_m.getMSmallMoleculeFeatureOptionalColumnNames(),
n_smf_section_columns));
OPENMS_POSTCONDITION(n_smf_header_columns == n_smf_section_columns,
"The number of columns of the small molecule feature header do not assort to the number of columns of the small molecule feature section row.")
}
size_t n_sme_header_columns = 0;
out.emplace_back("");
out.emplace_back(generateMzTabMSmallMoleculeEvidenceHeader_(mztab_m.getMetaData(),
mztab_m.getMSmallMoleculeEvidenceOptionalColumnNames(),
n_sme_header_columns));
size_t n_sme_section_columns = 0;
const MzTabMSmallMoleculeEvidenceSectionRows& evidence_section = mztab_m.getMSmallMoleculeEvidenceSectionRows();
for (const auto& sme_row : evidence_section)
{
out.emplace_back(generateMzTabMSmallMoleculeEvidenceSectionRow_(sme_row,
mztab_m.getMSmallMoleculeEvidenceOptionalColumnNames(),
n_sme_section_columns));
OPENMS_POSTCONDITION(n_sme_header_columns == n_sme_section_columns,
"The number of columns in the small molecule evidence header do not assort to the number of columns of the small molecule evidence section row.")
}
TextFile tmp_out;
for (TextFile::ConstIterator it = out.begin(); it != out.end(); ++it)
{
tmp_out.addLine(*it);
}
tmp_out.store(filename);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MzIdentMLFile.cpp | .cpp | 2,252 | 61 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Andreas Bertsch, Mathias Walzer$
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/MzIdentMLFile.h>
#include <OpenMS/FORMAT/VALIDATORS/MzIdentMLValidator.h>
#include <OpenMS/FORMAT/CVMappingFile.h>
#include <OpenMS/FORMAT/HANDLERS/MzIdentMLHandler.h>
#include <OpenMS/FORMAT/HANDLERS/MzIdentMLDOMHandler.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/FORMAT/FileHandler.h>
namespace OpenMS
{
MzIdentMLFile::MzIdentMLFile() :
XMLFile("/SCHEMAS/mzIdentML1.1.0.xsd", "1.1.0")
{
}
MzIdentMLFile::~MzIdentMLFile() = default;
void MzIdentMLFile::load(const String& filename, std::vector<ProteinIdentification>& poid, PeptideIdentificationList& peid)
{
Internal::MzIdentMLDOMHandler handler(poid, peid, schema_version_, *this);
handler.readMzIdentMLFile(filename);
}
void MzIdentMLFile::store(const String& filename, const std::vector<ProteinIdentification>& poid, const PeptideIdentificationList& peid) const
{
if (!FileHandler::hasValidExtension(filename, FileTypes::MZIDENTML))
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "invalid file extension, expected '" + FileTypes::typeToName(FileTypes::MZIDENTML) + "'");
}
Internal::MzIdentMLHandler handler(poid, peid, filename, schema_version_, *this);
save_(filename, &handler);
// Internal::MzIdentMLDOMHandler handler(poid, peid, schema_version_, *this);
// handler.writeMzIdentMLFile(filename);
}
bool MzIdentMLFile::isSemanticallyValid(const String& filename, StringList& errors, StringList& warnings)
{
// load mapping
CVMappings mapping;
CVMappingFile().load(File::find("/MAPPING/mzIdentML-mapping.xml"), mapping);
// validate
Internal::MzIdentMLValidator v(mapping, ControlledVocabulary::getPSIMSCV());
bool result = v.validate(filename, errors, warnings);
return result;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/XTandemInfile.cpp | .cpp | 30,374 | 717 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Andreas Bertsch, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/XTandemInfile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <boost/regex.hpp>
#include <fstream>
using namespace std;
namespace OpenMS
{
XTandemInfile::XTandemInfile() :
Internal::XMLFile(),
fragment_mass_tolerance_(0.3),
precursor_mass_tolerance_plus_(2.0),
precursor_mass_tolerance_minus_(2.0),
fragment_mass_error_unit_(XTandemInfile::DALTONS),
precursor_mass_error_unit_(XTandemInfile::DALTONS),
fragment_mass_type_(XTandemInfile::MONOISOTOPIC),
precursor_mass_type_(XTandemInfile::MONOISOTOPIC),
max_precursor_charge_(4),
precursor_lower_mz_(500.0),
fragment_lower_mz_(200.0),
number_of_threads_(1),
modifications_(),
input_filename_(""),
output_filename_(""),
cleavage_site_("[KR]|{P}"),
semi_cleavage_(false),
allow_isotope_error_(false),
number_of_missed_cleavages_(1),
default_parameters_file_(""),
output_results_("valid"),
max_valid_evalue_(0.01),
force_default_mods_(false)
{
}
XTandemInfile::~XTandemInfile() = default;
void XTandemInfile::write(const String& filename, bool ignore_member_parameters, bool force_default_mods)
{
if (!File::writable(filename))
{
throw (Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename));
}
force_default_mods_ = force_default_mods;
ofstream os(filename.c_str());
writeTo_(os, ignore_member_parameters);
return;
}
String XTandemInfile::convertModificationSet_(const set<ModificationDefinition>& mods, map<String, double>& affected_origins) const
{
// check if both "Glu->pyro-Glu (N-term E)" and "Gln->pyro-Glu (N-term Q)"
// are specified:
bool has_pyroglu_e = false, has_pyroglu_q = false;
for (set<ModificationDefinition>::const_iterator it = mods.begin();
it != mods.end(); ++it)
{
if (it->getModificationName() == "Glu->pyro-Glu (N-term E)")
{
has_pyroglu_e = true;
}
else if (it->getModificationName() == "Gln->pyro-Glu (N-term Q)")
{
has_pyroglu_q = true;
}
if (has_pyroglu_e && has_pyroglu_q)
{
break;
}
}
map<String, double> origin_set;
StringList xtandem_mods;
for (set<ModificationDefinition>::const_iterator it = mods.begin();
it != mods.end(); ++it)
{
if (!force_default_mods_ &&
// @TODO: change Acetyl spec. to "protein N-term" once it's supported
((it->getModificationName() == "Acetyl (N-term)") ||
// for the pyro-Glus, only skip if both are present:
((it->getModificationName() == "Gln->pyro-Glu (N-term Q)") &&
has_pyroglu_e) ||
((it->getModificationName() == "Glu->pyro-Glu (N-term E)") &&
has_pyroglu_q)))
{
continue;
}
double mod_mass = it->getModification().getDiffMonoMass();
String orig = it->getModification().getOrigin();
ResidueModification::TermSpecificity ts = it->getModification().getTermSpecificity();
if ((ts != ResidueModification::ANYWHERE) && !orig.empty())
{
OPENMS_LOG_WARN << "Warning: X! Tandem doesn't support modifications with both residue and terminal specificity. Using only terminal specificity for modification '" << it->getModificationName() << "'." << endl;
}
if (ts == ResidueModification::C_TERM)
{
orig = "]";
}
else if (ts == ResidueModification::N_TERM)
{
orig = "[";
}
// check double usage
if (origin_set.find(orig) != origin_set.end())
{
OPENMS_LOG_WARN << "X! Tandem config file: Duplicate modification assignment to origin '" << orig << "'. "
<< "X! Tandem will ignore the first modification '" << origin_set.find(orig)->second << "'!\n";
}
// check if already used before (i.e. we are currently looking at variable mods)
if (affected_origins.find(orig) != affected_origins.end())
{
OPENMS_LOG_INFO << "X! Tandem config file: Fixed modification and variable modification to origin '" << orig << "' detected. "
<< "Using corrected mass of " << mod_mass - affected_origins.find(orig)->second << " instead of " << mod_mass << ".\n";
mod_mass -= affected_origins.find(orig)->second;
}
// insert the (corrected) value
origin_set.insert(make_pair(orig, mod_mass));
String mod_string;
if (mod_mass >= 0)
{
mod_string = String("+") + String(mod_mass); // prepend a "+"
}
else
{
mod_string = String(mod_mass); // the '-' is implicit
}
mod_string += "@" + orig;
xtandem_mods.push_back(mod_string);
}
// copy now; above we need an independent set, in case 'affected_origins' was non-empty
affected_origins = origin_set;
return ListUtils::concatenate(xtandem_mods, ",");
}
void XTandemInfile::writeTo_(ostream& os, bool ignore_member_parameters)
{
os << "<?xml version=\"1.0\"?>" << "\n"
<< R"(<?xml-stylesheet type="text/xsl" href="tandem-input-style.xsl"?>)" << "\n"
<< "<bioml>" << "\n";
writeNote_(os, "spectrum, path", input_filename_);
writeNote_(os, "output, path", output_filename_);
writeNote_(os, "list path, taxonomy information", taxonomy_file_); // contains the FASTA database
if (!default_parameters_file_.empty())
{
writeNote_(os, "list path, default parameters", default_parameters_file_);
}
// these are needed for finding and parsing the results:
writeNote_(os, "output, path hashing", false);
writeNote_(os, "output, proteins", true);
writeNote_(os, "output, spectra", true);
writeNote_(os, "output, sort results by", "spectrum");
// required by Percolator to recognize output file
// (see https://github.com/percolator/percolator/issues/180):
writeNote_(os, "output, xsl path", "tandem-style.xsl");
// to help diagnose problems:
writeNote_(os, "output, parameters", true);
if (!ignore_member_parameters)
{
//////////////// spectrum parameters
//<note type="input" label="spectrum, fragment monoisotopic mass error">0.4</note>
writeNote_(os, "spectrum, fragment monoisotopic mass error", String(fragment_mass_tolerance_));
//<note type="input" label="spectrum, parent monoisotopic mass error plus">100</note>
writeNote_(os, "spectrum, parent monoisotopic mass error plus", String(precursor_mass_tolerance_plus_));
//<note type="input" label="spectrum, parent monoisotopic mass error minus">100</note>
writeNote_(os, "spectrum, parent monoisotopic mass error minus", String(precursor_mass_tolerance_minus_));
//<note type="input" label="spectrum, parent monoisotopic mass isotope error">yes</note>
String allow = allow_isotope_error_ ? "yes" : "no";
writeNote_(os, "spectrum, parent monoisotopic mass isotope error", allow);
//<note type="input" label="spectrum, fragment monoisotopic mass error units">Daltons</note>
//<note>The value for this parameter may be 'Daltons' or 'ppm': all other values are ignored</note>
if (fragment_mass_error_unit_ == XTandemInfile::DALTONS)
{
writeNote_(os, "spectrum, fragment monoisotopic mass error units", "Daltons");
}
else
{
writeNote_(os, "spectrum, fragment monoisotopic mass error units", "ppm");
}
//<note type="input" label="spectrum, parent monoisotopic mass error units">ppm</note>
//<note>The value for this parameter may be 'Daltons' or 'ppm': all other values are ignored</note>
if (precursor_mass_error_unit_ == XTandemInfile::PPM)
{
writeNote_(os, "spectrum, parent monoisotopic mass error units", "ppm");
}
else
{
writeNote_(os, "spectrum, parent monoisotopic mass error units", "Daltons");
}
//<note type="input" label="spectrum, fragment mass type">monoisotopic</note>
//<note>values are monoisotopic|average </note>
if (fragment_mass_type_ == XTandemInfile::MONOISOTOPIC)
{
writeNote_(os, "spectrum, fragment mass type", "monoisotopic"); // default
}
else
{
writeNote_(os, "spectrum, fragment mass type", "average");
}
////////////////////////////////////////////////////////////////////////////////
//////////////// spectrum conditioning parameters
//<note type="input" label="spectrum, dynamic range">100.0</note>
//<note>The peaks read in are normalized so that the most intense peak
//is set to the dynamic range value. All peaks with values of less that
//1, using this normalization, are not used. This normalization has the
//overall effect of setting a threshold value for peak intensities.</note>
//writeNote_(os, "spectrum, dynamic range", String(dynamic_range_);
//<note type="input" label="spectrum, total peaks">50</note>
//<note>If this value is 0, it is ignored. If it is greater than zero (lets say 50),
//then the number of peaks in the spectrum with be limited to the 50 most intense
//peaks in the spectrum. X! tandem does not do any peak finding: it only
//limits the peaks used by this parameter, and the dynamic range parameter.</note>
//writeNote_(os, "spectrum, total peaks", String(total_number_peaks_);
//<note type="input" label="spectrum, maximum parent charge">4</note>
writeNote_(os, "spectrum, maximum parent charge", String(max_precursor_charge_));
// <note type="input" label="spectrum, use noise suppression">yes</note>
//writeNote_(os, "spectrum, use noise suppression", noise_suppression_);
//<note type="input" label="spectrum, minimum parent m+h">500.0</note>
//writeNote_(os, "spectrum, minimum parent m+h", String(precursor_lower_mz_));
//<note type="input" label="spectrum, minimum fragment mz">150.0</note>
//writeNote_(os, "spectrum, minimum fragment mz", String(fragment_lower_mz_));
//<note type="input" label="spectrum, minimum peaks">15</note>
//writeNote_(os, "spectrum, minimum peaks", String(min_number_peaks_));
//<note type="input" label="spectrum, threads">1</note>
writeNote_(os, "spectrum, threads", String(number_of_threads_));
//<note type="input" label="spectrum, sequence batch size">1000</note>
//writeNote_(os, "spectrum, sequence batch size", String(batch_size_));
////////////////////////////////////////////////////////////////////////////////
//////////////// protein parameters
//<note type="input" label="protein, taxon">other mammals</note>
//<note>This value is interpreted using the information in taxonomy.xml.</note>
writeNote_(os, "protein, taxon", taxon_);
//<note type="input" label="protein, cleavage site">[RK]|{P}</note>
//<note>this setting corresponds to the enzyme trypsin. The first characters
//in brackets represent residues N-terminal to the bond - the '|' pipe -
//and the second set of characters represent residues C-terminal to the
//bond. The characters must be in square brackets (denoting that only
//these residues are allowed for a cleavage) or french brackets (denoting
//that these residues cannot be in that position). Use UPPERCASE characters.
//To denote cleavage at any residue, use [X]|[X] and reset the
//scoring, maximum missed cleavage site parameter (see below) to something like 50.
//</note>
writeNote_(os, "protein, cleavage site", cleavage_site_);
//////////////// semi cleavage parameter
//<note type="input" label="protein, cleavage semi">yes</note>
writeNote_(os, "protein, cleavage semi", semi_cleavage_);
//<note type="input" label="protein, modified residue mass file"></note>
//writeNote_(os, "protein, modified residue mass file", modified_residue_mass_file_);
//<note type="input" label="protein, cleavage C-terminal mass change">+17.002735</note>
//writeNote_(os, "protein, cleavage C-terminal mass change", String(cleavage_c_term_mass_change_));
//<note type="input" label="protein, cleavage N-terminal mass change">+1.007825</note>
//writeNote_(os, "protein, cleavage N-terminal mass change", String(cleavage_n_term_mass_change_));
//<note type="input" label="protein, N-terminal residue modification mass">0.0</note>
//writeNote_(os, "protein, N-terminal residue modification mass", String(protein_n_term_mod_mass_));
//<note type="input" label="protein, C-terminal residue modification mass">0.0</note>
//writeNote_(os, "protein, C-terminal residue modification mass", String(protein_c_term_mod_mass_));
//<note type="input" label="protein, homolog management">no</note>
//<note>if yes, an upper limit is set on the number of homologues kept for a particular spectrum</note>
//writeNote_(os, "protein, homolog management", protein_homolog_management_);
// special cases for default (N-terminal) modifications:
set<String> var_mods = modifications_.getVariableModificationNames();
// Ron Beavis: "If a variable modification is set for the peptide N-terminus, the 'quick acetyl' and 'quick pyrolidone' are turned off so that they don't interfere with the specified variable modification." -> check for that
boost::regex re(" \\(N-term( .)?\\)$");
for (set<String>::iterator vm_it = var_mods.begin();
vm_it != var_mods.end(); ++vm_it)
{
if (boost::regex_search(*vm_it, re) && (*vm_it != "Acetyl (N-term)") &&
(*vm_it != "Gln->pyro-Glu (N-term Q)") &&
(*vm_it != "Glu->pyro-Glu (N-term E)"))
{
force_default_mods_ = true;
}
}
if (!force_default_mods_ &&
(var_mods.find("Gln->pyro-Glu (N-term Q)") != var_mods.end()) &&
(var_mods.find("Glu->pyro-Glu (N-term E)") != var_mods.end()))
{
writeNote_(os, "protein, quick pyrolidone", true);
OPENMS_LOG_INFO << "Modifications 'Gln->pyro-Glu (N-term Q)' and 'Glu->pyro-Glu (N-term E)' are handled implicitly by the X! Tandem option 'protein, quick pyrolidone'. Set the 'force' flag in XTandemAdapter to force explicit inclusion of these modifications." << endl;
}
// special case for "Acetyl (N-term)" modification:
if (!force_default_mods_ &&
(var_mods.find("Acetyl (N-term)") != var_mods.end()))
{
writeNote_(os, "protein, quick acetyl", true);
OPENMS_LOG_INFO << "Modification 'Acetyl (N-term)' is handled implicitly by the X! Tandem option 'protein, quick acetyl'. Set the 'force' flag in XTandemAdapter to force explicit inclusion of this modification." << endl;
}
////////////////////////////////////////////////////////////////////////////////
//////////////// residue modification parameters
//<note type="input" label="residue, modification mass">57.022@C</note>
//<note>The format of this parameter is m@X, where m is the modification
//mass in Daltons and X is the appropriate residue to modify. Lists of
//modifications are separated by commas. For example, to modify M and C
//with the addition of 16.0 Daltons, the parameter line would be
//+16.0@M,+16.0@C
//Positive and negative values are allowed.
//</note>
map<String, double> affected_origins;
writeNote_(os, "residue, modification mass", convertModificationSet_(modifications_.getFixedModifications(), affected_origins));
//<note type="input" label="residue, potential modification mass"></note>
//<note>The format of this parameter is the same as the format
//for residue, modification mass (see above).</note>
writeNote_(os, "residue, potential modification mass", convertModificationSet_(modifications_.getVariableModifications(), affected_origins));
//<note type="input" label="residue, potential modification motif"></note>
//<note>The format of this parameter is similar to residue, modification mass,
//with the addition of a modified PROSITE notation sequence motif specification.
//For example, a value of 80@[ST!]PX[KR] indicates a modification
//of either S or T when followed by P, and residue and the a K or an R.
//A value of 204@N!{P}[ST]{P} indicates a modification of N by 204, if it
//is NOT followed by a P, then either an S or a T, NOT followed by a P.
//Positive and negative values are allowed.
//</note>
// writeNote_(os, "residue, potential modification motif", variable_modification_motif_);
////////////////////////////////////////////////////////////////////////////////
//////////////// model refinement parameters
//<note type="input" label="refine">yes</note>
//writeNote_(os, "refine", refine_);
//<note type="input" label="refine, modification mass"></note>
//writeNote_(os, "refine, modification mass", String(refine_mod_mass_));
//<note type="input" label="refine, sequence path"></note>
//writeNote_(os, "refine, sequence path", refine_sequence_path_);
//<note type="input" label="refine, tic percent">20</note>
//writeNote_(os, "refine, tic percent", String(refine_tic_percent_));
//<note type="input" label="refine, spectrum synthesis">yes</note>
//writeNote_(os, "refine, spectrum synthesis", refine_spectrum_synthesis_);
//<note type="input" label="refine, maximum valid expectation value">0.1</note>
//writeNote_(os, "refine, maximum valid expectation value", String(refine_max_valid_evalue_));
//<note type="input" label="refine, potential N-terminus modifications">+42.010565@[</note>
//writeNote_(os, "refine, potential N-terminus modifications", refine_variable_n_term_mods_);
//<note type="input" label="refine, potential C-terminus modifications"></note>
//writeNote_(os, "refine, potential C-terminus modifications", refine_variable_c_term_mods_);
//<note type="input" label="refine, unanticipated cleavage">yes</note>
//writeNote_(os, "refine, unanticipated cleavage", refine_unanticipated_cleavage_);
//<note type="input" label="refine, potential modification mass"></note>
//writeNote_(os, "refine, potential modification mass", String(variable_mod_mass_));
//<note type="input" label="refine, point mutations">no</note>
//writeNote_(os, "refine, point mutations", refine_point_mutations_);
//<note type="input" label="refine, use potential modifications for full refinement">no</note>
//writeNote_(os, "refine, use potential modifications for full refinement", use_var_mod_for_full_refinement_);
//<note type="input" label="refine, potential modification motif"></note>
//<note>The format of this parameter is similar to residue, modification mass,
//with the addition of a modified PROSITE notation sequence motif specification.
//For example, a value of 80@[ST!]PX[KR] indicates a modification
//of either S or T when followed by P, and residue and the a K or an R.
//A value of 204@N!{P}[ST]{P} indicates a modification of N by 204, if it
//is NOT followed by a P, then either an S or a T, NOT followed by a P.
//Positive and negative values are allowed.
//</note>
//writeNote_(os, "refine, potential modification motif", refine_var_mod_motif_);
////////////////////////////////////////////////////////////////////////////////
//////////////// scoring parameters
//<note type="input" label="scoring, minimum ion count">4</note>
//writeNote_(os, "scoring, minimum ion count", String(scoring_min_ion_count_));
//<note type="input" label="scoring, maximum missed cleavage sites">1</note>
writeNote_(os, "scoring, maximum missed cleavage sites", String(number_of_missed_cleavages_));
//<note type="input" label="scoring, x ions">no</note>
//writeNote_(os, "scoring, x ions", score_x_ions_);
//<note type="input" label="scoring, y ions">yes</note>
//writeNote_(os, "scoring, y ions", score_y_ions_);
//<note type="input" label="scoring, z ions">no</note>
//writeNote_(os, "scoring, z ions", score_z_ions_);
//<note type="input" label="scoring, a ions">no</note>
//writeNote_(os, "scoring, a ions", score_a_ions_);
//<note type="input" label="scoring, b ions">yes</note>
//writeNote_(os, "scoring, b ions", score_b_ions_);
//<note type="input" label="scoring, c ions">no</note>
//writeNote_(os, "scoring, c ions", score_c_ions_);
//<note type="input" label="scoring, cyclic permutation">no</note>
//<note>if yes, cyclic peptide sequence permutation is used to pad the scoring histograms</note>
//writeNote_(os, "scoring, cyclic permutation", scoring_cyclic_permutation_);
//<note type="input" label="scoring, include reverse">no</note>
//<note>if yes, then reversed sequences are searched at the same time as forward sequences</note>
//writeNote_(os, "scoring, include reverse", scoring_include_reverse_);
////////////////////////////////////////////////////////////////////////////////
//////////////// output parameters
//<note type="input" label="output, log path"></note>
//<note type="input" label="output, message">...</note>
//writeNote_(os, "output, message", String("..."));
//<note type="input" label="output, one sequence copy">no</note>
//<note type="input" label="output, sequence path"></note>
//<note type="input" label="output, path">output.xml</note>
//writeNote_(os, "output, path", output_filename_);
//<note type="input" label="output, sort results by">protein</note>
//<note>values = protein|spectrum (spectrum is the default)</note>
//<note type="input" label="output, path hashing">yes</note>
//<note>values = yes|no</note>
//<note type="input" label="output, xsl path">tandem-style.xsl</note>
//<note type="input" label="output, parameters">yes</note>
//<note>values = yes|no</note>
//<note type="input" label="output, performance">yes</note>
//<note>values = yes|no</note>
//<note type="input" label="output, spectra">yes</note>
//<note>values = yes|no</note>
//<note type="input" label="output, histograms">yes</note>
//<note>values = yes|no</note>
//<note type="input" label="output, proteins">yes</note>
//<note>values = yes|no</note>
//<note type="input" label="output, sequences">yes</note>
//<note>values = yes|no</note>
//<note type="input" label="output, one sequence copy">no</note>
//<note>values = yes|no, set to yes to produce only one copy of each protein sequence in the output xml</note>
//<note type="input" label="output, results">valid</note>
//<note>values = all|valid|stochastic</note>
writeNote_(os, "output, results", output_results_);
//<note type="input" label="output, maximum valid expectation value">0.1</note>
writeNote_(os, "output, maximum valid expectation value", String(max_valid_evalue_));
//<note>value is used in the valid|stochastic setting of output, results</note>
//<note type="input" label="output, histogram column width">30</note>
//<note>values any integer greater than 0. Setting this to '1' makes cutting and pasting histograms
//into spread sheet programs easier.</note>
//<note type="description">ADDITIONAL EXPLANATIONS</note>
//<note type="description">Each one of the parameters for X! tandem is entered as a labeled note
// node. In the current version of X!, keep those note nodes
// on a single line.
//</note>
//<note type="description">The presence of the type 'input' is necessary if a note is to be considered
// an input parameter.
//</note>
//<note type="description">Any of the parameters that are paths to files may require alteration for a
// particular installation. Full path names usually cause the least trouble,
// but there is no reason not to use relative path names, if that is the
// most convenient.
//</note>
//<note type="description">Any parameter values set in the 'list path, default parameters' file are
// reset by entries in the normal input file, if they are present. Otherwise,
// the default set is used.
//</note>
//<note type="description">The 'list path, taxonomy information' file must exist.
//</note>
//<note type="description">The directory containing the 'output, path' file must exist: it will not be created.
//</note>
//<note type="description">The 'output, xsl path' is optional: it is only of use if a good XSLT style sheet exists.
//</note>
////////////////////////////////////////////////////////////////////////////////
}
os << "</bioml>\n";
}
void XTandemInfile::writeNote_(ostream& os, const String& label, const String& value)
{
os << "\t<note type=\"input\" label=\"" << label << "\">" << value << "</note>\n";
}
void XTandemInfile::writeNote_(ostream& os, const String& label, const char* value)
{
String val(value);
writeNote_(os, label, val);
}
void XTandemInfile::writeNote_(ostream& os, const String& label, bool value)
{
String val = value ? "yes" : "no";
writeNote_(os, label, val);
}
void XTandemInfile::setOutputFilename(const String& filename)
{
output_filename_ = filename;
}
const String& XTandemInfile::getOutputFilename() const
{
return output_filename_;
}
void XTandemInfile::setInputFilename(const String& filename)
{
input_filename_ = filename;
}
const String& XTandemInfile::getInputFilename() const
{
return input_filename_;
}
void XTandemInfile::setTaxonomyFilename(const String& filename)
{
taxonomy_file_ = filename;
}
const String& XTandemInfile::getTaxonomyFilename() const
{
return taxonomy_file_;
}
void XTandemInfile::setDefaultParametersFilename(const String& filename)
{
default_parameters_file_ = filename;
}
const String& XTandemInfile::getDefaultParametersFilename() const
{
return default_parameters_file_;
}
void XTandemInfile::setModifications(const ModificationDefinitionsSet& mods)
{
modifications_ = mods;
}
const ModificationDefinitionsSet& XTandemInfile::getModifications() const
{
return modifications_;
}
void XTandemInfile::setTaxon(const String& taxon)
{
taxon_ = taxon;
}
const String& XTandemInfile::getTaxon() const
{
return taxon_;
}
void XTandemInfile::setPrecursorMassTolerancePlus(double tolerance)
{
precursor_mass_tolerance_plus_ = tolerance;
}
double XTandemInfile::getPrecursorMassTolerancePlus() const
{
return precursor_mass_tolerance_plus_;
}
void XTandemInfile::setPrecursorMassToleranceMinus(double tolerance)
{
precursor_mass_tolerance_minus_ = tolerance;
}
double XTandemInfile::getPrecursorMassToleranceMinus() const
{
return precursor_mass_tolerance_minus_;
}
void XTandemInfile::setPrecursorMassErrorUnit(ErrorUnit unit)
{
precursor_mass_error_unit_ = unit;
}
XTandemInfile::ErrorUnit XTandemInfile::getPrecursorMassErrorUnit() const
{
return precursor_mass_error_unit_;
}
void XTandemInfile::setFragmentMassErrorUnit(ErrorUnit unit)
{
fragment_mass_error_unit_ = unit;
}
XTandemInfile::ErrorUnit XTandemInfile::getFragmentMassErrorUnit() const
{
return fragment_mass_error_unit_;
}
void XTandemInfile::setMaxPrecursorCharge(Int max_charge)
{
max_precursor_charge_ = max_charge;
}
Int XTandemInfile::getMaxPrecursorCharge() const
{
return max_precursor_charge_;
}
void XTandemInfile::setFragmentMassTolerance(double tolerance)
{
fragment_mass_tolerance_ = tolerance;
}
double XTandemInfile::getFragmentMassTolerance() const
{
return fragment_mass_tolerance_;
}
void XTandemInfile::setNumberOfThreads(UInt num_threads)
{
number_of_threads_ = num_threads;
}
UInt XTandemInfile::getNumberOfThreads() const
{
return number_of_threads_;
}
XTandemInfile::MassType XTandemInfile::getPrecursorErrorType() const
{
return precursor_mass_type_;
}
void XTandemInfile::setPrecursorErrorType(const MassType mass_type)
{
precursor_mass_type_ = mass_type;
}
void XTandemInfile::setMaxValidEValue(double value)
{
max_valid_evalue_ = value;
}
double XTandemInfile::getMaxValidEValue() const
{
return max_valid_evalue_;
}
void XTandemInfile::setNumberOfMissedCleavages(UInt missed_cleavages)
{
number_of_missed_cleavages_ = missed_cleavages;
}
UInt XTandemInfile::getNumberOfMissedCleavages() const
{
return number_of_missed_cleavages_;
}
void XTandemInfile::setOutputResults(const String& result)
{
if (result == "valid" || result == "all" || result == "stochastic")
{
output_results_ = result;
}
else
{
throw OpenMS::Exception::FailedAPICall(__FILE__, __LINE__, __FUNCTION__, "Invalid result type provided (must be either all, valid or stochastic).: '" + result + "'");
}
}
String XTandemInfile::getOutputResults() const
{
return output_results_;
}
void XTandemInfile::setSemiCleavage(const bool semi_cleavage)
{
semi_cleavage_ = semi_cleavage;
}
void XTandemInfile::setAllowIsotopeError(const bool allow_isotope_error)
{
allow_isotope_error_ = allow_isotope_error;
}
void XTandemInfile::setCleavageSite(const String& cleavage_site)
{
cleavage_site_ = cleavage_site;
}
const String& XTandemInfile::getCleavageSite() const
{
return cleavage_site_;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/OMSFileStore.cpp | .cpp | 69,137 | 1,599 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/OMSFileStore.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/CONCEPT/UniqueIdGenerator.h>
#include <SQLiteCpp/Database.h>
#include <SQLiteCpp/Transaction.h>
#include <sqlite3.h>
using namespace std;
using ID = OpenMS::IdentificationData;
namespace OpenMS::Internal
{
constexpr int version_number = 5; // increase this whenever the DB schema changes!
void raiseDBError_(const String& error, int line, const char* function,
const String& context, const String& query)
{
String msg = context + ": " + error;
if (!query.empty())
{
msg += String("\nQuery was: ") + query;
}
throw Exception::FailedAPICall(__FILE__, line, function, msg);
}
bool execAndReset(SQLite::Statement& query, int expected_modifications)
{
auto ret = query.exec();
query.reset();
return ret == expected_modifications;
}
void execWithExceptionAndReset(SQLite::Statement& query, int expected_modifications, int line, const char* function, const char* context)
{
if (!execAndReset(query, expected_modifications))
{
raiseDBError_(query.getErrorMsg(), line, function, context);
}
}
OMSFileStore::OMSFileStore(const String& filename, LogType log_type)
{
setLogType(log_type);
File::remove(filename); // nuke the file (SQLite cannot overwrite it)
db_ = make_unique<SQLite::Database>(filename, SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE); // throws on error
// foreign key constraints are disabled by default - turn them on:
// @TODO: performance impact? (seems negligible, but should be tested more)
db_->exec("PRAGMA foreign_keys = ON");
// disable synchronous filesystem access and the rollback journal to greatly
// increase write performance - since we write a new output file every time,
// we don't have to worry about database consistency:
db_->exec("PRAGMA synchronous = OFF");
db_->exec("PRAGMA journal_mode = OFF");
db_->exec("PRAGMA foreign_keys = ON");
db_->exec("PRAGMA foreign_keys = ON");
}
OMSFileStore::~OMSFileStore() = default;
void OMSFileStore::createTable_(const String& name, const String& definition, bool may_exist)
{
String sql_create = "CREATE TABLE ";
if (may_exist) sql_create += "IF NOT EXISTS ";
sql_create += name + " (" + definition + ")";
db_->exec(sql_create);
}
void OMSFileStore::storeVersionAndDate_()
{
createTable_("version",
"OMSFile INT NOT NULL, " \
"date TEXT NOT NULL, " \
"OpenMS TEXT, " \
"build_date TEXT");
SQLite::Statement query(*db_, "INSERT INTO version VALUES (" \
":format_version, " \
"datetime('now'), " \
":openms_version, " \
":build_date)");
query.bind(":format_version", version_number);
query.bind(":openms_version", VersionInfo::getVersion());
query.bind(":build_date", VersionInfo::getTime());
query.exec();
}
void OMSFileStore::createTableMoleculeType_()
{
createTable_("ID_MoleculeType",
"id INTEGER PRIMARY KEY NOT NULL, " \
"molecule_type TEXT UNIQUE NOT NULL");
auto sql_insert =
"INSERT INTO ID_MoleculeType VALUES " \
"(1, 'PROTEIN'), " \
"(2, 'COMPOUND'), " \
"(3, 'RNA')";
db_->exec(sql_insert);
}
void OMSFileStore::createTableDataValue_DataType_()
{
createTable_("DataValue_DataType",
"id INTEGER PRIMARY KEY NOT NULL, " \
"data_type TEXT UNIQUE NOT NULL");
auto sql_insert =
"INSERT INTO DataValue_DataType VALUES " \
"(1, 'STRING_VALUE'), " \
"(2, 'INT_VALUE'), " \
"(3, 'DOUBLE_VALUE'), " \
"(4, 'STRING_LIST'), " \
"(5, 'INT_LIST'), " \
"(6, 'DOUBLE_LIST')";
db_->exec(sql_insert);
}
void OMSFileStore::createTableCVTerm_()
{
createTable_("CVTerm",
"id INTEGER PRIMARY KEY NOT NULL, " \
"accession TEXT UNIQUE, " \
"name TEXT NOT NULL, " \
"cv_identifier_ref TEXT, " \
// does this constrain "name" if "accession" is NULL?
"UNIQUE (accession, name)");
// @TODO: add support for unit and value
// prepare query for inserting data:
auto query = make_unique<SQLite::Statement>(*db_, "INSERT OR IGNORE INTO CVTerm VALUES (" \
"NULL, " \
":accession, " \
":name, " \
":cv_identifier_ref)");
prepared_queries_.emplace("CVTerm", std::move(query));
// alternative query if CVTerm already exists:
auto query2 = make_unique<SQLite::Statement>(*db_, "SELECT id FROM CVTerm " \
"WHERE accession = :accession AND name = :name");
prepared_queries_.emplace("CVTerm_2", std::move(query2));
}
OMSFileStore::Key OMSFileStore::storeCVTerm_(const CVTerm& cv_term)
{
// this assumes the "CVTerm" table exists already!
auto& query = *prepared_queries_["CVTerm"];
if (cv_term.getAccession().empty()) // use NULL for empty accessions
{
query.bind(":accession");
}
else
{
query.bind(":accession", cv_term.getAccession());
}
query.bind(":name", cv_term.getName());
query.bind(":cv_identifier_ref", cv_term.getCVIdentifierRef());
if (execAndReset(query, 1)) // one row was inserted
{
return db_->getLastInsertRowid();
}
// else: insert has failed, record must already exist - get the key:
auto& alt_query = *prepared_queries_["CVTerm_2"];
alt_query.reset(); // get ready for a new execution
if (cv_term.getAccession().empty()) // use NULL for empty accessions
{
alt_query.bind(":accession");
}
else
{
alt_query.bind(":accession", cv_term.getAccession());
}
alt_query.bind(":name", cv_term.getName());
if (!alt_query.executeStep())
{
raiseDBError_(alt_query.getErrorMsg(), __LINE__, OPENMS_PRETTY_FUNCTION, "error querying database");
}
return Key(alt_query.getColumn(0).getInt64());
}
void OMSFileStore::createTableMetaInfo_(const String& parent_table, const String& key_column)
{
if (!db_->tableExists("DataValue_DataType")) createTableDataValue_DataType_();
String parent_ref = parent_table + " (" + key_column + ")";
String table = parent_table + "_MetaInfo";
// for the data_type_id, empty values are represented using NULL
createTable_(
table,
"parent_id INTEGER NOT NULL, " \
"name TEXT NOT NULL, " \
"data_type_id INTEGER, " \
"value TEXT, " \
"FOREIGN KEY (parent_id) REFERENCES " + parent_ref + ", " \
"FOREIGN KEY (data_type_id) REFERENCES DataValue_DataType (id), " \
"PRIMARY KEY (parent_id, name)");
// @TODO: add support for units
// prepare query for inserting data:
auto query = make_unique<SQLite::Statement>(*db_, "INSERT INTO " + table +
" VALUES (" \
":parent_id, " \
":name, " \
":data_type_id, " \
":value)");
prepared_queries_.emplace(table, std::move(query));
}
void OMSFileStore::storeMetaInfo_(const MetaInfoInterface& info, const String& parent_table, Key parent_id)
{
if (info.isMetaEmpty()) return;
// this assumes the "..._MetaInfo" and "DataValue_DataType" tables exist already!
auto& query = *prepared_queries_[parent_table + "_MetaInfo"];
query.bind(":parent_id", parent_id);
// this is inefficient, but MetaInfoInterface doesn't support iteration:
vector<String> info_keys;
info.getKeys(info_keys);
for (const String& info_key : info_keys)
{
query.bind(":name", info_key);
const DataValue& value = info.getMetaValue(info_key);
if (value.isEmpty()) // use NULL as the type for empty values
{
query.bind(":data_type_id");
}
else
{
query.bind(":data_type_id", int(value.valueType()) + 1);
}
query.bind(":value", value.toString());
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
}
void OMSFileStore::createTableAppliedProcessingStep_(const String& parent_table)
{
String table = parent_table + "_AppliedProcessingStep";
createTable_(
table,
"parent_id INTEGER NOT NULL, " \
"processing_step_id INTEGER, " \
"processing_step_order INTEGER NOT NULL, " \
"score_type_id INTEGER, " \
"score REAL, " \
"UNIQUE (parent_id, processing_step_id, score_type_id), " \
"FOREIGN KEY (parent_id) REFERENCES " + parent_table + " (id), " \
"FOREIGN KEY (score_type_id) REFERENCES ID_ScoreType (id), " \
"FOREIGN KEY (processing_step_id) REFERENCES ID_ProcessingStep (id)");
// @TODO: add constraint that "processing_step_id" and "score_type_id" can't both be NULL
// @TODO: add constraint that "processing_step_order" must match "..._id"?
// @TODO: normalize table? (splitting into multiple tables is awkward here)
// prepare query for inserting data:
auto query = make_unique<SQLite::Statement>(*db_, "INSERT INTO " + table +
" VALUES (" \
":parent_id, "
":processing_step_id, "
":processing_step_order, "
":score_type_id, "
":score)");
prepared_queries_.emplace(table, std::move(query));
}
void OMSFileStore::storeAppliedProcessingStep_(const ID::AppliedProcessingStep& step, Size step_order,
const String& parent_table, Key parent_id)
{
// this assumes the "..._AppliedProcessingStep" table exists already!
auto& query = *prepared_queries_[parent_table + "_AppliedProcessingStep"];
query.bind(":parent_id", parent_id);
query.bind(":processing_step_order", int(step_order));
if (step.processing_step_opt)
{
query.bind(":processing_step_id", processing_step_keys_[&(**step.processing_step_opt)]);
if (step.scores.empty()) // insert processing step information only
{
query.bind(":score_type_id"); // NULL
query.bind(":score"); // NULL
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
}
else // use NULL for missing processing step reference
{
query.bind(":processing_step_id");
}
for (const auto& score_pair : step.scores)
{
query.bind(":score_type_id", score_type_keys_[&(*score_pair.first)]);
query.bind(":score", score_pair.second);
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
}
void OMSFileStore::storeScoreTypes_(const IdentificationData& id_data)
{
if (id_data.getScoreTypes().empty()) return;
createTableCVTerm_();
createTable_(
"ID_ScoreType",
"id INTEGER PRIMARY KEY NOT NULL, " \
"cv_term_id INTEGER NOT NULL, " \
"higher_better NUMERIC NOT NULL CHECK (higher_better in (0, 1)), " \
"FOREIGN KEY (cv_term_id) REFERENCES CVTerm (id)");
SQLite::Statement query(*db_, "INSERT INTO ID_ScoreType VALUES (" \
":id, " \
":cv_term_id, " \
":higher_better)");
Key id = 1;
for (const ID::ScoreType& score_type : id_data.getScoreTypes())
{
Key cv_id = storeCVTerm_(score_type.cv_term);
query.bind(":id", id);
query.bind(":cv_term_id", cv_id);
query.bind(":higher_better", int(score_type.higher_better));
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
score_type_keys_[&score_type] = id;
++id;
}
}
void OMSFileStore::storeInputFiles_(const IdentificationData& id_data)
{
if (id_data.getInputFiles().empty()) return;
createTable_("ID_InputFile",
"id INTEGER PRIMARY KEY NOT NULL, " \
"name TEXT UNIQUE NOT NULL, " \
"experimental_design_id TEXT, " \
"primary_files TEXT");
SQLite::Statement query(*db_, "INSERT INTO ID_InputFile VALUES (" \
":id, " \
":name, " \
":experimental_design_id, " \
":primary_files)");
Key id = 1;
for (const ID::InputFile& input : id_data.getInputFiles())
{
query.bind(":id", id);
query.bind(":name", input.name);
query.bind(":experimental_design_id",
input.experimental_design_id);
// @TODO: what if a primary file name contains ","?
String primary_files = ListUtils::concatenate(input.primary_files, ",");
query.bind(":primary_files", primary_files);
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
input_file_keys_[&input] = id;
++id;
}
}
void OMSFileStore::storeProcessingSoftwares_(const IdentificationData& id_data)
{
if (id_data.getProcessingSoftwares().empty()) return;
createTable_("ID_ProcessingSoftware",
"id INTEGER PRIMARY KEY NOT NULL, " \
"name TEXT NOT NULL, " \
"version TEXT, " \
"UNIQUE (name, version)");
SQLite::Statement query(*db_, "INSERT INTO ID_ProcessingSoftware VALUES (" \
":id, " \
":name, " \
":version)");
bool any_scores = false; // does any software have assigned scores stored?
Key id = 1;
for (const ID::ProcessingSoftware& software : id_data.getProcessingSoftwares())
{
if (!software.assigned_scores.empty()) any_scores = true;
query.bind(":id", id);
query.bind(":name", software.getName());
query.bind(":version", software.getVersion());
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
processing_software_keys_[&software] = id;
++id;
}
if (any_scores)
{
createTable_(
"ID_ProcessingSoftware_AssignedScore",
"software_id INTEGER NOT NULL, " \
"score_type_id INTEGER NOT NULL, " \
"score_type_order INTEGER NOT NULL, " \
"UNIQUE (software_id, score_type_id), " \
"UNIQUE (software_id, score_type_order), " \
"FOREIGN KEY (software_id) REFERENCES ID_ProcessingSoftware (id), " \
"FOREIGN KEY (score_type_id) REFERENCES ID_ScoreType (id)");
SQLite::Statement query2(*db_,
"INSERT INTO ID_ProcessingSoftware_AssignedScore VALUES (" \
":software_id, " \
":score_type_id, " \
":score_type_order)");
for (const ID::ProcessingSoftware& software : id_data.getProcessingSoftwares())
{
query2.bind(":software_id", processing_software_keys_[&software]);
Size counter = 0;
for (ID::ScoreTypeRef score_type_ref : software.assigned_scores)
{
query2.bind(":score_type_id", score_type_keys_[&(*score_type_ref)]);
query2.bind(":score_type_order", int(++counter));
execWithExceptionAndReset(query2, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
}
}
}
void OMSFileStore::storeDBSearchParams_(const IdentificationData& id_data)
{
if (id_data.getDBSearchParams().empty()) return;
if (!db_->tableExists("ID_MoleculeType")) createTableMoleculeType_();
createTable_(
"ID_DBSearchParam",
"id INTEGER PRIMARY KEY NOT NULL, " \
"molecule_type_id INTEGER NOT NULL, " \
"mass_type_average NUMERIC NOT NULL CHECK (mass_type_average in (0, 1)) DEFAULT 0, " \
"database TEXT, " \
"database_version TEXT, " \
"taxonomy TEXT, " \
"charges TEXT, " \
"fixed_mods TEXT, " \
"variable_mods TEXT, " \
"precursor_mass_tolerance REAL, " \
"fragment_mass_tolerance REAL, " \
"precursor_tolerance_ppm NUMERIC NOT NULL CHECK (precursor_tolerance_ppm in (0, 1)) DEFAULT 0, " \
"fragment_tolerance_ppm NUMERIC NOT NULL CHECK (fragment_tolerance_ppm in (0, 1)) DEFAULT 0, " \
"digestion_enzyme TEXT, " \
"enzyme_term_specificity TEXT, " // new in version 2!
"missed_cleavages NUMERIC, " \
"min_length NUMERIC, " \
"max_length NUMERIC, " \
"FOREIGN KEY (molecule_type_id) REFERENCES ID_MoleculeType (id)");
SQLite::Statement query(*db_, "INSERT INTO ID_DBSearchParam VALUES (" \
":id, " \
":molecule_type_id, " \
":mass_type_average, " \
":database, " \
":database_version, " \
":taxonomy, " \
":charges, " \
":fixed_mods, " \
":variable_mods, " \
":precursor_mass_tolerance, " \
":fragment_mass_tolerance, " \
":precursor_tolerance_ppm, " \
":fragment_tolerance_ppm, " \
":digestion_enzyme, " \
":enzyme_term_specificity, " \
":missed_cleavages, " \
":min_length, " \
":max_length)");
Key id = 1;
for (const ID::DBSearchParam& param : id_data.getDBSearchParams())
{
query.bind(":id", id);
query.bind(":molecule_type_id", int(param.molecule_type) + 1);
query.bind(":mass_type_average", int(param.mass_type));
query.bind(":database", param.database);
query.bind(":database_version", param.database_version);
query.bind(":taxonomy", param.taxonomy);
String charges = ListUtils::concatenate(param.charges, ",");
query.bind(":charges", charges);
String fixed_mods = ListUtils::concatenate(param.fixed_mods, ",");
query.bind(":fixed_mods", fixed_mods);
String variable_mods = ListUtils::concatenate(param.variable_mods, ",");
query.bind(":variable_mods", variable_mods);
query.bind(":precursor_mass_tolerance", param.precursor_mass_tolerance);
query.bind(":fragment_mass_tolerance", param.fragment_mass_tolerance);
query.bind(":precursor_tolerance_ppm", int(param.precursor_tolerance_ppm));
query.bind(":fragment_tolerance_ppm", int(param.fragment_tolerance_ppm));
if (param.digestion_enzyme != nullptr)
{
query.bind(":digestion_enzyme", param.digestion_enzyme->getName());
}
else // bind NULL value
{
query.bind(":digestion_enzyme");
}
query.bind(":enzyme_term_specificity",
EnzymaticDigestion::NamesOfSpecificity[param.enzyme_term_specificity]);
query.bind(":missed_cleavages", uint32_t(param.missed_cleavages));
query.bind(":min_length", uint32_t(param.min_length));
query.bind(":max_length", uint32_t(param.max_length));
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
search_param_keys_[¶m] = id;
++id;
}
}
void OMSFileStore::storeProcessingSteps_(const IdentificationData& id_data)
{
if (id_data.getProcessingSteps().empty()) return;
createTable_(
"ID_ProcessingStep",
"id INTEGER PRIMARY KEY NOT NULL, " \
"software_id INTEGER NOT NULL, " \
"date_time TEXT, " \
"search_param_id INTEGER, " \
"FOREIGN KEY (search_param_id) REFERENCES ID_DBSearchParam (id)");
// @TODO: add support for processing actions
// @TODO: store primary files in a separate table (like input files)?
// @TODO: store (optional) search param reference in a separate table?
SQLite::Statement query(*db_, "INSERT INTO ID_ProcessingStep VALUES (" \
":id, " \
":software_id, " \
":date_time, " \
":search_param_id)");
bool any_input_files = false;
Key id = 1;
// use iterator here because we need one to look up the DB search params:
for (ID::ProcessingStepRef step_ref = id_data.getProcessingSteps().begin();
step_ref != id_data.getProcessingSteps().end(); ++step_ref)
{
const ID::ProcessingStep& step = *step_ref;
if (!step.input_file_refs.empty()) any_input_files = true;
query.bind(":id", id);
query.bind(":software_id", processing_software_keys_[&(*step.software_ref)]);
query.bind(":date_time", step.date_time.get());
auto pos = id_data.getDBSearchSteps().find(step_ref);
if (pos != id_data.getDBSearchSteps().end())
{
query.bind(":search_param_id", search_param_keys_[&(*pos->second)]);
}
else
{
query.bind(":search_param_id"); // NULL
}
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
processing_step_keys_[&step] = id;
++id;
}
if (any_input_files)
{
createTable_(
"ID_ProcessingStep_InputFile",
"processing_step_id INTEGER NOT NULL, " \
"input_file_id INTEGER NOT NULL, " \
"FOREIGN KEY (processing_step_id) REFERENCES ID_ProcessingStep (id), " \
"FOREIGN KEY (input_file_id) REFERENCES ID_InputFile (id), " \
"UNIQUE (processing_step_id, input_file_id)");
SQLite::Statement query2(*db_, "INSERT INTO ID_ProcessingStep_InputFile VALUES (" \
":processing_step_id, " \
":input_file_id)");
for (const ID::ProcessingStep& step : id_data.getProcessingSteps())
{
query2.bind(":processing_step_id", processing_step_keys_[&step]);
for (ID::InputFileRef input_file_ref : step.input_file_refs)
{
query2.bind(":input_file_id", input_file_keys_[&(*input_file_ref)]);
execWithExceptionAndReset(query2, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
}
}
storeMetaInfos_(id_data.getProcessingSteps(), "ID_ProcessingStep", processing_step_keys_);
}
void OMSFileStore::storeObservations_(const IdentificationData& id_data)
{
if (id_data.getObservations().empty()) return;
createTable_("ID_Observation",
"id INTEGER PRIMARY KEY NOT NULL, " \
"data_id TEXT NOT NULL, " \
"input_file_id INTEGER NOT NULL, " \
"rt REAL, " \
"mz REAL, " \
"UNIQUE (data_id, input_file_id), " \
"FOREIGN KEY (input_file_id) REFERENCES ID_InputFile (id)");
SQLite::Statement query(*db_, "INSERT INTO ID_Observation VALUES (" \
":id, " \
":data_id, " \
":input_file_id, " \
":rt, " \
":mz)");
Key id = 1;
for (const ID::Observation& obs : id_data.getObservations())
{
query.bind(":id", id);
query.bind(":data_id", obs.data_id);
query.bind(":input_file_id", input_file_keys_[&(*obs.input_file)]);
if (obs.rt == obs.rt)
{
query.bind(":rt", obs.rt);
}
else // NaN
{
query.bind(":rt"); // NULL
}
if (obs.mz == obs.mz)
{
query.bind(":mz", obs.mz);
}
else // NaN
{
query.bind(":mz"); // NULL
}
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
observation_keys_[&obs] = id;
++id;
}
storeMetaInfos_(id_data.getObservations(), "ID_Observation", observation_keys_);
}
void OMSFileStore::storeParentSequences_(const IdentificationData& id_data)
{
if (id_data.getParentSequences().empty()) return;
if (!db_->tableExists("ID_MoleculeType")) createTableMoleculeType_();
createTable_(
"ID_ParentSequence",
"id INTEGER PRIMARY KEY NOT NULL, " \
"accession TEXT UNIQUE NOT NULL, " \
"molecule_type_id INTEGER NOT NULL, " \
"sequence TEXT, " \
"description TEXT, " \
"coverage REAL, " \
"is_decoy NUMERIC NOT NULL CHECK (is_decoy in (0, 1)) DEFAULT 0, " \
"FOREIGN KEY (molecule_type_id) REFERENCES ID_MoleculeType (id)");
SQLite::Statement query(*db_, "INSERT INTO ID_ParentSequence VALUES (" \
":id, " \
":accession, " \
":molecule_type_id, " \
":sequence, " \
":description, " \
":coverage, " \
":is_decoy)");
Key id = 1;
for (const ID::ParentSequence& parent : id_data.getParentSequences())
{
query.bind(":id", id);
query.bind(":accession", parent.accession);
query.bind(":molecule_type_id", int(parent.molecule_type) + 1);
query.bind(":sequence", parent.sequence);
query.bind(":description", parent.description);
query.bind(":coverage", parent.coverage);
query.bind(":is_decoy", int(parent.is_decoy));
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
parent_sequence_keys_[&parent] = id;
++id;
}
storeScoredProcessingResults_(id_data.getParentSequences(), "ID_ParentSequence", parent_sequence_keys_);
}
void OMSFileStore::storeParentGroupSets_(const IdentificationData& id_data)
{
if (id_data.getParentGroupSets().empty()) return;
createTable_("ID_ParentGroupSet",
"id INTEGER PRIMARY KEY NOT NULL, " \
"label TEXT UNIQUE");
createTable_(
"ID_ParentGroup",
"id INTEGER PRIMARY KEY NOT NULL, " \
"grouping_id INTEGER NOT NULL, " \
"score_type_id INTEGER, " \
"score REAL, " \
"UNIQUE (id, score_type_id), " \
"FOREIGN KEY (grouping_id) REFERENCES ID_ParentGroupSet (id)");
createTable_(
"ID_ParentGroup_ParentSequence",
"group_id INTEGER NOT NULL, " \
"parent_id INTEGER NOT NULL, " \
"UNIQUE (group_id, parent_id), " \
"FOREIGN KEY (group_id) REFERENCES ID_ParentGroup (id), " \
"FOREIGN KEY (parent_id) REFERENCES ID_ParentSequence (id)");
SQLite::Statement query_grouping(*db_, "INSERT INTO ID_ParentGroupSet VALUES (" \
":id, " \
":label)");
SQLite::Statement query_group(*db_, "INSERT INTO ID_ParentGroup VALUES (" \
":id, " \
":grouping_id, " \
":score_type_id, " \
":score)");
SQLite::Statement query_parent(*db_, "INSERT INTO ID_ParentGroup_ParentSequence VALUES (" \
":group_id, " \
":parent_id)");
Key grouping_id = 1;
Key group_id = 1;
for (const ID::ParentGroupSet& grouping : id_data.getParentGroupSets())
{
query_grouping.bind(":id", grouping_id);
query_grouping.bind(":label", grouping.label);
execWithExceptionAndReset(query_grouping, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
for (const ID::ParentGroup& group : grouping.groups)
{
query_group.bind(":id", group_id);
query_group.bind(":grouping_id", grouping_id);
if (group.scores.empty()) // store group with an empty score
{
query_group.bind(":score_type_id");
query_group.bind(":score");
execWithExceptionAndReset(query_group, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
else // store group multiple times with different scores
{
for (const auto& score_pair : group.scores)
{
query_group.bind(":score_type_id", score_type_keys_[&(*score_pair.first)]);
query_group.bind(":score", score_pair.second);
execWithExceptionAndReset(query_group, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
}
query_parent.bind(":group_id", group_id);
for (ID::ParentSequenceRef parent_ref : group.parent_refs)
{
query_parent.bind(":parent_id", parent_sequence_keys_[&(*parent_ref)]);
execWithExceptionAndReset(query_parent, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
++group_id;
}
parent_grouping_keys_[&grouping] = grouping_id;
++grouping_id;
}
storeScoredProcessingResults_(id_data.getParentGroupSets(), "ID_ParentGroupSet", parent_grouping_keys_);
}
void OMSFileStore::createTableIdentifiedMolecule_()
{
if (!db_->tableExists("ID_MoleculeType")) createTableMoleculeType_();
// use one table for all types of identified molecules to allow foreign key
// references from the input match table:
createTable_(
"ID_IdentifiedMolecule",
"id INTEGER PRIMARY KEY NOT NULL, " \
"molecule_type_id INTEGER NOT NULL, " \
"identifier TEXT NOT NULL, " \
"UNIQUE (molecule_type_id, identifier), " \
"FOREIGN KEY (molecule_type_id) REFERENCES ID_MoleculeType (id)");
// prepare query for inserting data:
auto query = make_unique<SQLite::Statement>(*db_, "INSERT INTO ID_IdentifiedMolecule VALUES (" \
":id, " \
":molecule_type_id, " \
":identifier)");
prepared_queries_.emplace("ID_IdentifiedMolecule", std::move(query));
}
void OMSFileStore::storeIdentifiedCompounds_(const IdentificationData& id_data)
{
if (id_data.getIdentifiedCompounds().empty()) return;
if (!db_->tableExists("ID_IdentifiedMolecule"))
{
createTableIdentifiedMolecule_();
}
auto& query_molecule = *prepared_queries_["ID_IdentifiedMolecule"];
query_molecule.bind(":molecule_type_id", int(ID::MoleculeType::COMPOUND) + 1);
createTable_(
"ID_IdentifiedCompound",
"molecule_id INTEGER UNIQUE NOT NULL , " \
"formula TEXT, " \
"name TEXT, " \
"smile TEXT, " \
"inchi TEXT, " \
"FOREIGN KEY (molecule_id) REFERENCES ID_IdentifiedMolecule (id)");
SQLite::Statement query_compound(*db_, "INSERT INTO ID_IdentifiedCompound VALUES (" \
":molecule_id, " \
":formula, " \
":name, " \
":smile, " \
":inchi)");
Key id = 1;
for (const ID::IdentifiedCompound& compound : id_data.getIdentifiedCompounds())
{
query_molecule.bind(":id", id);
query_molecule.bind(":identifier", compound.identifier);
execWithExceptionAndReset(query_molecule, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
query_compound.bind(":molecule_id", id);
query_compound.bind(":formula", compound.formula.toString());
query_compound.bind(":name", compound.name);
query_compound.bind(":smile", compound.name);
query_compound.bind(":inchi", compound.inchi);
execWithExceptionAndReset(query_compound, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
identified_compound_keys_[&compound] = id;
++id;
}
storeScoredProcessingResults_(id_data.getIdentifiedCompounds(), "ID_IdentifiedMolecule",
identified_compound_keys_);
}
void OMSFileStore::storeIdentifiedSequences_(const IdentificationData& id_data)
{
if (id_data.getIdentifiedPeptides().empty() &&
id_data.getIdentifiedOligos().empty()) return;
if (!db_->tableExists("ID_IdentifiedMolecule"))
{
createTableIdentifiedMolecule_();
}
auto& query = *prepared_queries_["ID_IdentifiedMolecule"];
bool any_parent_matches = false;
// identified compounds get stored earlier and use the same key range as peptides/oligos:
Key id = id_data.getIdentifiedCompounds().size() + 1;
// store peptides:
query.bind(":molecule_type_id", int(ID::MoleculeType::PROTEIN) + 1);
for (const ID::IdentifiedPeptide& peptide : id_data.getIdentifiedPeptides())
{
if (!peptide.parent_matches.empty()) any_parent_matches = true;
query.bind(":id", id);
query.bind(":identifier", peptide.sequence.toString());
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
identified_peptide_keys_[&peptide] = id;
++id;
}
storeScoredProcessingResults_(id_data.getIdentifiedPeptides(), "ID_IdentifiedMolecule",
identified_peptide_keys_);
// store RNA oligos:
query.bind(":molecule_type_id", int(ID::MoleculeType::RNA) + 1);
for (const ID::IdentifiedOligo& oligo : id_data.getIdentifiedOligos())
{
if (!oligo.parent_matches.empty()) any_parent_matches = true;
query.bind(":id", id); // use address as primary key
query.bind(":identifier", oligo.sequence.toString());
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
identified_oligo_keys_[&oligo] = id;
++id;
}
storeScoredProcessingResults_(id_data.getIdentifiedOligos(), "ID_IdentifiedMolecule",
identified_oligo_keys_);
if (any_parent_matches)
{
createTableParentMatches_();
for (const ID::IdentifiedPeptide& peptide : id_data.getIdentifiedPeptides())
{
if (!peptide.parent_matches.empty())
{
storeParentMatches_(peptide.parent_matches, identified_peptide_keys_[&peptide]);
}
}
for (const ID::IdentifiedOligo& oligo : id_data.getIdentifiedOligos())
{
if (!oligo.parent_matches.empty())
{
storeParentMatches_(oligo.parent_matches, identified_oligo_keys_[&oligo]);
}
}
}
}
void OMSFileStore::createTableParentMatches_()
{
createTable_(
"ID_ParentMatch",
"molecule_id INTEGER NOT NULL, " \
"parent_id INTEGER NOT NULL, " \
"start_pos NUMERIC, " \
"end_pos NUMERIC, " \
"left_neighbor TEXT, " \
"right_neighbor TEXT, " \
"UNIQUE (molecule_id, parent_id, start_pos, end_pos), " \
"FOREIGN KEY (parent_id) REFERENCES ID_ParentSequence (id), " \
"FOREIGN KEY (molecule_id) REFERENCES ID_IdentifiedMolecule (id)");
// prepare query for inserting data:
auto query = make_unique<SQLite::Statement>(*db_, "INSERT INTO ID_ParentMatch VALUES (" \
":molecule_id, " \
":parent_id, " \
":start_pos, " \
":end_pos, " \
":left_neighbor, " \
":right_neighbor)");
prepared_queries_.emplace("ID_ParentMatch", std::move(query));
}
void OMSFileStore::storeParentMatches_(const ID::ParentMatches& matches, Key molecule_id)
{
// this assumes the "ID_ParentMatch" table exists already!
auto& query = *prepared_queries_["ID_ParentMatch"];
// @TODO: cache the prepared query between function calls somehow?
query.bind(":molecule_id", molecule_id);
for (const auto& pair : matches)
{
query.bind(":parent_id", parent_sequence_keys_[&(*pair.first)]);
for (const auto& match : pair.second)
{
if (match.start_pos != ID::ParentMatch::UNKNOWN_POSITION)
{
query.bind(":start_pos", uint32_t(match.start_pos));
}
else // use NULL value
{
query.bind(":start_pos");
}
if (match.end_pos != ID::ParentMatch::UNKNOWN_POSITION)
{
query.bind(":end_pos", uint32_t(match.end_pos));
}
else // use NULL value
{
query.bind(":end_pos");
}
query.bind(":left_neighbor", match.left_neighbor);
query.bind(":right_neighbor", match.right_neighbor);
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
}
}
void OMSFileStore::storeAdducts_(const IdentificationData& id_data)
{
if (id_data.getAdducts().empty()) return;
createTable_("AdductInfo",
"id INTEGER PRIMARY KEY NOT NULL, " \
"name TEXT, " \
"formula TEXT NOT NULL, " \
"charge INTEGER NOT NULL, " \
"mol_multiplier INTEGER NOT NULL CHECK (mol_multiplier > 0) DEFAULT 1, " \
"UNIQUE (formula, charge)");
SQLite::Statement query(*db_, "INSERT INTO AdductInfo VALUES (" \
":id, " \
":name, " \
":formula, " \
":charge, " \
":mol_multiplier)");
Key id = 1;
for (const AdductInfo& adduct : id_data.getAdducts())
{
query.bind(":id", id);
query.bind(":name", adduct.getName());
query.bind(":formula", adduct.getEmpiricalFormula().toString());
query.bind(":charge", adduct.getCharge());
query.bind(":mol_multiplier", adduct.getMolMultiplier());
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
adduct_keys_[&adduct] = id;
++id;
}
}
OMSFileStore::Key OMSFileStore::getDatabaseKey_(const ID::IdentifiedMolecule& molecule_var)
{
switch (molecule_var.getMoleculeType())
{
case ID::MoleculeType::PROTEIN:
return identified_peptide_keys_[&(*molecule_var.getIdentifiedPeptideRef())];
case ID::MoleculeType::COMPOUND:
return identified_compound_keys_[&(*molecule_var.getIdentifiedCompoundRef())];
case ID::MoleculeType::RNA:
return identified_oligo_keys_[&(*molecule_var.getIdentifiedOligoRef())];
default:
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
}
void OMSFileStore::storeObservationMatches_(const IdentificationData& id_data)
{
if (id_data.getObservationMatches().empty()) return;
String table_def =
"id INTEGER PRIMARY KEY NOT NULL, " \
"identified_molecule_id INTEGER NOT NULL, " \
"observation_id INTEGER NOT NULL, " \
"adduct_id INTEGER, " \
"charge INTEGER, " \
"FOREIGN KEY (identified_molecule_id) REFERENCES ID_IdentifiedMolecule (id), " \
"FOREIGN KEY (observation_id) REFERENCES ID_Observation (id)";
// add foreign key constraint if the adduct table exists (having the
// constraint without the table would cause an error on data insertion):
if (db_->tableExists("AdductInfo"))
{
table_def += ", FOREIGN KEY (adduct_id) REFERENCES AdductInfo (id)";
}
createTable_("ID_ObservationMatch", table_def);
SQLite::Statement query(*db_, "INSERT INTO ID_ObservationMatch VALUES (" \
":id, " \
":identified_molecule_id, " \
":observation_id, " \
":adduct_id, " \
":charge)");
bool any_peak_annotations = false;
Key id = 1;
for (const ID::ObservationMatch& match : id_data.getObservationMatches())
{
if (!match.peak_annotations.empty()) any_peak_annotations = true;
query.bind(":id", id);
query.bind(":identified_molecule_id", getDatabaseKey_(match.identified_molecule_var));
query.bind(":observation_id", observation_keys_[&(*match.observation_ref)]);
if (match.adduct_opt)
{
query.bind(":adduct_id", adduct_keys_[&(**match.adduct_opt)]);
}
else // bind NULL value
{
query.bind(":adduct_id");
}
query.bind(":charge", match.charge);
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
observation_match_keys_[&match] = id;
++id;
}
storeScoredProcessingResults_(id_data.getObservationMatches(), "ID_ObservationMatch", observation_match_keys_);
if (any_peak_annotations)
{
createTable_(
"ID_ObservationMatch_PeakAnnotation",
"parent_id INTEGER NOT NULL, " \
"processing_step_id INTEGER, " \
"peak_annotation TEXT, " \
"peak_charge INTEGER, " \
"peak_mz REAL, " \
"peak_intensity REAL, " \
"FOREIGN KEY (parent_id) REFERENCES ID_ObservationMatch (id), " \
"FOREIGN KEY (processing_step_id) REFERENCES ID_ProcessingStep (id)");
SQLite::Statement query2(*db_,
"INSERT INTO ID_ObservationMatch_PeakAnnotation VALUES (" \
":parent_id, " \
":processing_step_id, " \
":peak_annotation, " \
":peak_charge, " \
":peak_mz, " \
":peak_intensity)");
for (const ID::ObservationMatch& match : id_data.getObservationMatches())
{
if (match.peak_annotations.empty()) continue;
query2.bind(":parent_id", observation_match_keys_[&match]);
for (const auto& pair : match.peak_annotations)
{
if (pair.first) // processing step given
{
query2.bind(":processing_step_id", processing_step_keys_[&(**pair.first)]);
}
else // use NULL value
{
query2.bind(":processing_step_id");
}
for (const auto& peak_ann : pair.second)
{
query2.bind(":peak_annotation", peak_ann.annotation);
query2.bind(":peak_charge", peak_ann.charge);
query2.bind(":peak_mz", peak_ann.mz);
query2.bind(":peak_intensity", peak_ann.intensity);
execWithExceptionAndReset(query2, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
}
}
// create index on parent_id column
db_->exec("CREATE INDEX PeakAnnotation_parent_id ON ID_ObservationMatch_PeakAnnotation (parent_id)");
}
}
void OMSFileStore::store(const IdentificationData& id_data)
{
startProgress(0, 13, "Writing identification data to file");
// generally, create tables only if we have data to write - no empty ones!
auto body = [&]() {
storeVersionAndDate_();
nextProgress(); // 1
storeInputFiles_(id_data);
nextProgress(); // 2
storeScoreTypes_(id_data);
nextProgress(); // 3
storeProcessingSoftwares_(id_data);
nextProgress(); // 4
storeDBSearchParams_(id_data);
nextProgress(); // 5
storeProcessingSteps_(id_data);
nextProgress(); // 6
storeObservations_(id_data);
nextProgress(); // 7
storeParentSequences_(id_data);
nextProgress(); // 8
storeParentGroupSets_(id_data);
nextProgress(); // 9
storeIdentifiedCompounds_(id_data);
nextProgress(); // 10
storeIdentifiedSequences_(id_data);
nextProgress(); // 11
storeAdducts_(id_data);
nextProgress(); // 12
storeObservationMatches_(id_data);
};
if (sqlite3_get_autocommit(db_->getHandle()) == 1)
{ // allow a transaction, otherwise another on is already in flight
SQLite::Transaction transaction(*db_); // avoid SQLite's "implicit transactions", improve runtime
body();
transaction.commit();
}
else
{
body();
}
endProgress();
// @TODO: store input match groups
}
void OMSFileStore::createTableBaseFeature_(bool with_metainfo, bool with_idmatches)
{
createTable_("FEAT_BaseFeature",
"id INTEGER PRIMARY KEY NOT NULL, " \
"rt REAL, " \
"mz REAL, " \
"intensity REAL, " \
"charge INTEGER, " \
"width REAL, " \
"quality REAL, " \
"unique_id INTEGER, " \
"primary_molecule_id INTEGER, " \
"subordinate_of INTEGER, " \
"FOREIGN KEY (primary_molecule_id) REFERENCES ID_IdentifiedMolecule (id), " \
"FOREIGN KEY (subordinate_of) REFERENCES FEAT_BaseFeature (id), " \
"CHECK (id > subordinate_of)"); // check to prevent cycles
auto query = make_unique<SQLite::Statement>(*db_,
"INSERT INTO FEAT_BaseFeature VALUES (" \
":id, " \
":rt, " \
":mz, " \
":intensity, " \
":charge, " \
":width, " \
":quality, " \
":unique_id, " \
":primary_molecule_id, " \
":subordinate_of)");
prepared_queries_.emplace("FEAT_BaseFeature", std::move(query));
if (with_metainfo)
{
createTableMetaInfo_("FEAT_BaseFeature");
}
if (with_idmatches)
{
createTable_("FEAT_ObservationMatch",
"feature_id INTEGER NOT NULL, " \
"observation_match_id INTEGER NOT NULL, " \
"FOREIGN KEY (feature_id) REFERENCES FEAT_BaseFeature (id), " \
"FOREIGN KEY (observation_match_id) REFERENCES ID_ObservationMatch (id)");
query = make_unique<SQLite::Statement>(*db_,
"INSERT INTO FEAT_ObservationMatch VALUES (" \
":feature_id, " \
":observation_match_id)");
prepared_queries_.emplace("FEAT_ObservationMatch", std::move(query));
}
}
void OMSFileStore::storeBaseFeature_(const BaseFeature& feature, int feature_id, int parent_id)
{
auto& query_feat = *prepared_queries_["FEAT_BaseFeature"];
query_feat.bind(":id", feature_id);
query_feat.bind(":rt", feature.getRT());
query_feat.bind(":mz", feature.getMZ());
query_feat.bind(":intensity", feature.getIntensity());
query_feat.bind(":charge", feature.getCharge());
query_feat.bind(":width", feature.getWidth());
query_feat.bind(":quality", feature.getQuality());
query_feat.bind(":unique_id", int64_t(feature.getUniqueId()));
if (feature.hasPrimaryID())
{
query_feat.bind(":primary_molecule_id", getDatabaseKey_(feature.getPrimaryID()));
}
else // use NULL value
{
query_feat.bind(":primary_molecule_id");
}
if (parent_id >= 0) // feature is a subordinate
{
query_feat.bind(":subordinate_of", parent_id);
}
else // use NULL value
{
query_feat.bind(":subordinate_of");
}
execWithExceptionAndReset(query_feat, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
// store ID observation matches:
if (!feature.getIDMatches().empty())
{
auto& query_match = *prepared_queries_["FEAT_ObservationMatch"];
query_match.bind(":feature_id", feature_id);
for (ID::ObservationMatchRef ref : feature.getIDMatches())
{
query_match.bind(":observation_match_id", observation_match_keys_[&(*ref)]);
execWithExceptionAndReset(query_match, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
}
storeMetaInfo_(feature, "FEAT_BaseFeature", feature_id);
}
void OMSFileStore::storeFeatureAndSubordinates_(
const Feature& feature, int& feature_id, int parent_id)
{
storeBaseFeature_(feature, feature_id, parent_id);
auto& query_feat = *prepared_queries_["FEAT_Feature"];
query_feat.bind(":feature_id", feature_id);
query_feat.bind(":rt_quality", feature.getQuality(0));
query_feat.bind(":mz_quality", feature.getQuality(1));
execWithExceptionAndReset(query_feat, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
// store convex hulls:
const vector<ConvexHull2D>& hulls = feature.getConvexHulls();
if (!hulls.empty())
{
auto& query_hull = *prepared_queries_["FEAT_ConvexHull"];
query_hull.bind(":feature_id", feature_id);
for (size_t i = 0; i < hulls.size(); ++i)
{
query_hull.bind(":hull_index", (int64_t)i);
for (size_t j = 0; j < hulls[i].getHullPoints().size(); ++j)
{
const ConvexHull2D::PointType& point = hulls[i].getHullPoints()[j];
query_hull.bind(":point_index", (int64_t)j);
query_hull.bind(":point_x", point.getX());
query_hull.bind(":point_y", point.getY());
execWithExceptionAndReset(query_hull, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
}
}
// recurse into subordinates:
parent_id = feature_id;
++feature_id; // variable is passed by reference, so effect is global
for (const Feature& sub : feature.getSubordinates())
{
storeFeatureAndSubordinates_(sub, feature_id, parent_id);
}
}
void OMSFileStore::storeFeatures_(const FeatureMap& features)
{
if (features.empty()) return;
// create table(s) for BaseFeature parent class:
// any meta infos on features?
bool any_metainfo = anyFeaturePredicate_(features, [](const Feature& feature) {
return !feature.isMetaEmpty();
});
// any ID observations on features?
bool any_idmatches = anyFeaturePredicate_(features, [](const Feature& feature) {
return !feature.getIDMatches().empty();
});
createTableBaseFeature_(any_metainfo, any_idmatches);
createTable_("FEAT_Feature",
"feature_id INTEGER NOT NULL, " \
"rt_quality REAL, " \
"mz_quality REAL, " \
"FOREIGN KEY (feature_id) REFERENCES FEAT_BaseFeature (id)");
auto query = make_unique<SQLite::Statement>(*db_,
"INSERT INTO FEAT_Feature VALUES (" \
":feature_id, " \
":rt_quality, " \
":mz_quality)");
prepared_queries_.emplace("FEAT_Feature", std::move(query));
// any convex hulls on features?
if (anyFeaturePredicate_(features, [](const Feature& feature) {
return !feature.getConvexHulls().empty();
}))
{
createTable_("FEAT_ConvexHull",
"feature_id INTEGER NOT NULL, " \
"hull_index INTEGER NOT NULL CHECK (hull_index >= 0), " \
"point_index INTEGER NOT NULL CHECK (point_index >= 0), " \
"point_x REAL, " \
"point_y REAL, " \
"FOREIGN KEY (feature_id) REFERENCES FEAT_BaseFeature (id)");
auto query2 = make_unique<SQLite::Statement>(*db_, "INSERT INTO FEAT_ConvexHull VALUES (" \
":feature_id, " \
":hull_index, " \
":point_index, " \
":point_x, " \
":point_y)");
prepared_queries_.emplace("FEAT_ConvexHull", std::move(query2));
}
// features and their subordinates are stored in DFS-like order:
int feature_id = 0;
for (const Feature& feat : features)
{
storeFeatureAndSubordinates_(feat, feature_id, -1);
nextProgress();
}
}
template <class MapType>
void OMSFileStore::storeMapMetaData_(const MapType& features,
const String& experiment_type)
{
createTable_("FEAT_MapMetaData",
"unique_id INTEGER PRIMARY KEY, " \
"identifier TEXT, " \
"file_path TEXT, " \
"file_type TEXT, "
"experiment_type TEXT"); // ConsensusMap only
// @TODO: worth using a prepared query for just one insert?
SQLite::Statement query(*db_,
"INSERT INTO FEAT_MapMetaData VALUES (" \
":unique_id, " \
":identifier, " \
":file_path, " \
":file_type, " \
":experiment_type)");
query.bind(":unique_id", int64_t(features.getUniqueId()));
query.bind(":identifier", features.getIdentifier());
query.bind(":file_path", features.getLoadedFilePath());
String file_type = FileTypes::typeToName(features.getLoadedFileType());
query.bind(":file_type", file_type);
if (!experiment_type.empty())
{
query.bind(":experiment_type", experiment_type);
}
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
if (!features.isMetaEmpty())
{
createTableMetaInfo_("FEAT_MapMetaData", "unique_id");
storeMetaInfo_(features, "FEAT_MapMetaData", int64_t(features.getUniqueId()));
}
}
// template specializations:
template void OMSFileStore::storeMapMetaData_<FeatureMap>(const FeatureMap&, const String&);
template void OMSFileStore::storeMapMetaData_<ConsensusMap>(const ConsensusMap&, const String&);
void OMSFileStore::storeDataProcessing_(const vector<DataProcessing>& data_processing)
{
if (data_processing.empty()) return;
createTable_("FEAT_DataProcessing",
"id INTEGER PRIMARY KEY NOT NULL, " \
"software_name TEXT, " \
"software_version TEXT, " \
"processing_actions TEXT, " \
"completion_time TEXT");
// "id" is needed to connect to meta info table (see "storeMetaInfos_");
// "position" is position in the vector ("index" is a reserved word in SQL)
SQLite::Statement query(*db_, "INSERT INTO FEAT_DataProcessing VALUES (" \
":id, " \
":software_name, " \
":software_version, " \
":processing_actions, " \
":completion_time)");
Key id = 1;
for (const DataProcessing& proc : data_processing)
{
query.bind(":id", id);
query.bind(":software_name", proc.getSoftware().getName());
query.bind(":software_version", proc.getSoftware().getVersion());
String actions;
for (DataProcessing::ProcessingAction action : proc.getProcessingActions())
{
if (!actions.empty()) actions += ","; // @TODO: use different separator?
actions += DataProcessing::NamesOfProcessingAction[action];
}
query.bind(":processing_actions", actions);
query.bind(":completion_time", proc.getCompletionTime().get());
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
feat_processing_keys_[&proc] = id;
++id;
}
storeMetaInfos_(data_processing, "FEAT_DataProcessing", feat_processing_keys_);
}
void OMSFileStore::store(const FeatureMap& features)
{
SQLite::Transaction transaction(*db_); // avoid SQLite's "implicit transactions", improve runtime
if (features.getIdentificationData().empty())
{
storeVersionAndDate_();
}
else
{
store(features.getIdentificationData());
}
startProgress(0, features.size() + 2, "Writing feature data to file");
storeMapMetaData_(features);
nextProgress();
storeDataProcessing_(features.getDataProcessing());
nextProgress();
storeFeatures_(features);
transaction.commit();
endProgress();
}
void OMSFileStore::storeConsensusColumnHeaders_(const ConsensusMap& consensus)
{
if (consensus.getColumnHeaders().empty()) return; // shouldn't be empty in practice
createTable_("FEAT_ConsensusColumnHeader",
"id INTEGER PRIMARY KEY NOT NULL, " \
"filename TEXT, " \
"label TEXT, " \
"size INTEGER, " \
"unique_id INTEGER");
if (any_of(consensus.getColumnHeaders().begin(), consensus.getColumnHeaders().end(),
[](const auto& pair){
return !pair.second.isMetaEmpty();
}))
{
createTableMetaInfo_("FEAT_ConsensusColumnHeader");
}
SQLite::Statement query(*db_,
"INSERT INTO FEAT_ConsensusColumnHeader VALUES (" \
":id, " \
":filename, " \
":label, " \
":size, " \
":unique_id)");
for (const auto& pair : consensus.getColumnHeaders())
{
Key id = int64_t(pair.first);
query.bind(":id", id);
query.bind(":filename", pair.second.filename);
query.bind(":label", pair.second.label);
query.bind(":size", int64_t(pair.second.size));
query.bind(":unique_id", int64_t(pair.second.unique_id));
execWithExceptionAndReset(query, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
storeMetaInfo_(pair.second, "FEAT_ConsensusColumnHeader", id);
}
}
void OMSFileStore::storeConsensusFeatures_(const ConsensusMap& consensus)
{
if (consensus.empty()) return;
// create table(s) for BaseFeature parent class:
// any meta infos on features?
bool any_metainfo = any_of(consensus.begin(), consensus.end(), [](const ConsensusFeature& feature) {
return !feature.isMetaEmpty();
});
// any ID observations on features?
bool any_idmatches = any_of(consensus.begin(), consensus.end(), [](const ConsensusFeature& feature) {
return !feature.getIDMatches().empty();
});
createTableBaseFeature_(any_metainfo, any_idmatches);
createTable_("FEAT_FeatureHandle",
"feature_id INTEGER NOT NULL, " \
"map_index INTEGER NOT NULL, " \
"FOREIGN KEY (feature_id) REFERENCES FEAT_BaseFeature (id)");
SQLite::Statement query_handle(*db_,
"INSERT INTO FEAT_FeatureHandle VALUES (" \
":feature_id, " \
":map_index)");
// any ratios on consensus features?
unique_ptr<SQLite::Statement> query_ratio; // only assign if needed below
if (any_of(consensus.begin(), consensus.end(), [](const ConsensusFeature& feature) {
return !feature.getRatios().empty();
}))
{
createTable_("FEAT_ConsensusRatio",
"feature_id INTEGER NOT NULL, " \
"ratio_index INTEGER NOT NULL CHECK (ratio_index >= 0), " \
"ratio_value REAL, " \
"denominator_ref TEXT, " \
"numerator_ref TEXT, " \
"description TEXT, " \
"FOREIGN KEY (feature_id) REFERENCES FEAT_BaseFeature (id)");
query_ratio = make_unique<SQLite::Statement>(*db_, "INSERT INTO FEAT_ConsensusRatio VALUES (" \
":feature_id, " \
":ratio_index, " \
":ratio_value, " \
":denominator_ref, " \
":numerator_ref, " \
":description)");
}
// consensus features and their subfeatures are stored in DFS-like order:
int feature_id = 0;
for (const ConsensusFeature& feat : consensus)
{
storeBaseFeature_(feat, feature_id, -1);
int parent_id = feature_id;
for (const FeatureHandle& handle : feat.getFeatures())
{
storeBaseFeature_(BaseFeature(handle), ++feature_id, parent_id);
query_handle.bind(":feature_id", feature_id);
query_handle.bind(":map_index", int64_t(handle.getMapIndex()));
execWithExceptionAndReset(query_handle, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
for (uint32_t i = 0; i < feat.getRatios().size(); ++i)
{
const ConsensusFeature::Ratio& ratio = feat.getRatios()[i];
query_ratio->bind(":feature_id", feature_id);
query_ratio->bind(":ratio_index", i);
query_ratio->bind(":ratio_value", ratio.ratio_value_);
query_ratio->bind(":denominator_ref", ratio.denominator_ref_);
query_ratio->bind(":numerator_ref", ratio.numerator_ref_);
query_ratio->bind(":description", ListUtils::concatenate(ratio.description_, ","));
execWithExceptionAndReset(*query_ratio, 1, __LINE__, OPENMS_PRETTY_FUNCTION, "error inserting data");
}
nextProgress();
++feature_id;
}
}
void OMSFileStore::store(const ConsensusMap& consensus)
{
SQLite::Transaction transaction(*db_); // avoid SQLite's "implicit transactions", improve runtime
if (consensus.getIdentificationData().empty())
{
storeVersionAndDate_();
}
else
{
store(consensus.getIdentificationData());
}
startProgress(0, consensus.size() + 3, "Writing consensus feature data to file");
storeMapMetaData_(consensus, consensus.getExperimentType());
nextProgress();
storeConsensusColumnHeaders_(consensus);
nextProgress();
storeDataProcessing_(consensus.getDataProcessing());
nextProgress();
storeConsensusFeatures_(consensus);
transaction.commit();
endProgress();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/CsvFile.cpp | .cpp | 2,170 | 91 | // 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/FORMAT/CsvFile.h>
using namespace std;
namespace OpenMS
{
CsvFile::CsvFile() :
TextFile(), itemseperator_(','), itemenclosed_(false)
{
}
CsvFile::~CsvFile() = default;
CsvFile::CsvFile(const String& filename, char is, bool ie, Int first_n) :
TextFile(), itemseperator_(is), itemenclosed_(ie)
{
TextFile::load(filename, false, first_n, false, "#");
}
void CsvFile::load(const String& filename, char is, bool ie, Int first_n)
{
itemseperator_ = is;
itemenclosed_ = ie;
TextFile::load(filename, true, first_n, false, "#");
}
void CsvFile::store(const String& filename)
{
TextFile::store(filename);
}
void CsvFile::addRow(const StringList& list)
{
StringList elements = list;
if (itemenclosed_)
{
for (Size i = 0; i < elements.size(); ++i)
{
elements[i].quote('"', String::NONE);
}
}
String line;
line.concatenate(elements.begin(), elements.end(), itemseperator_);
addLine(line);
}
void CsvFile::clear()
{
buffer_.clear();
}
bool CsvFile::getRow(Size row, StringList& list) const
{
// it is assumed that the value to be cast won't be so large to overflow an ulong int
if (static_cast<int>(row) > static_cast<int>(TextFile::buffer_.size()) - 1)
{
throw Exception::InvalidIterator(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
bool splitted = buffer_[row].split(itemseperator_, list);
if (!splitted)
{
return splitted;
}
for (Size i = 0; i < list.size(); i++)
{
if (itemenclosed_)
{
list[i] = list[i].substr(1, list[i].size() - 2);
}
}
return true;
}
std::vector<String>::size_type CsvFile::rowCount() const
{
return TextFile::buffer_.size();
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MzXMLFile.cpp | .cpp | 3,459 | 113 | // 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/FORMAT/MzXMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/MzXMLHandler.h>
using namespace std;
namespace OpenMS
{
MzXMLFile::MzXMLFile() :
XMLFile("/SCHEMAS/mzXML_idx_3.1.xsd", "3.1")
{
}
MzXMLFile::~MzXMLFile() = default;
PeakFileOptions & MzXMLFile::getOptions()
{
return options_;
}
const PeakFileOptions & MzXMLFile::getOptions() const
{
return options_;
}
void MzXMLFile::setOptions(const PeakFileOptions & options)
{
options_ = options;
}
void MzXMLFile::load(const String & filename, MapType & map)
{
map.reset();
//set DocumentIdentifier
map.setLoadedFileType(filename);
map.setLoadedFilePath(filename);
Internal::MzXMLHandler handler(map, filename, schema_version_, *this);
handler.setOptions(options_);
parse_(filename, &handler);
}
void MzXMLFile::store(const String & filename, const MapType & map) const
{
Internal::MzXMLHandler handler(map, filename, schema_version_, *this);
handler.setOptions(options_);
save_(filename, &handler);
}
void MzXMLFile::transform(const String& filename_in, Interfaces::IMSDataConsumer * consumer, bool skip_full_count)
{
// First pass through the file -> get the meta-data and hand it to the consumer
transformFirstPass_(filename_in, consumer, skip_full_count);
// Second pass through the data, now read the spectra!
{
MapType dummy;
Internal::MzXMLHandler handler(dummy, filename_in, getVersion(), *this);
handler.setOptions(options_);
handler.setMSDataConsumer(consumer);
parse_(filename_in, &handler);
}
}
void MzXMLFile::transform(const String& filename_in, Interfaces::IMSDataConsumer * consumer, MapType& map, bool skip_full_count)
{
// First pass through the file -> get the meta-data and hand it to the consumer
transformFirstPass_(filename_in, consumer, skip_full_count);
// Second pass through the data, now read the spectra!
{
PeakFileOptions tmp_options(options_);
Internal::MzXMLHandler handler(map, filename_in, getVersion(), *this);
tmp_options.setAlwaysAppendData(true);
handler.setOptions(tmp_options);
handler.setMSDataConsumer(consumer);
parse_(filename_in, &handler);
}
}
void MzXMLFile::transformFirstPass_(const String& filename_in, Interfaces::IMSDataConsumer * consumer, bool skip_full_count)
{
// Create temporary objects and counters
PeakFileOptions tmp_options(options_);
Size scount = 0, ccount = 0;
MapType experimental_settings;
Internal::MzXMLHandler handler(experimental_settings, filename_in, getVersion(), *this);
// set temporary options for handler
tmp_options.setMetadataOnly( skip_full_count );
handler.setOptions(tmp_options);
handler.setLoadDetail(Internal::XMLHandler::LD_RAWCOUNTS);
parse_(filename_in, &handler);
// After parsing, collect information
scount = handler.getScanCount();
consumer->setExpectedSize(scount, ccount);
consumer->setExperimentalSettings(experimental_settings);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/GNPSMGFFile.cpp | .cpp | 13,513 | 377 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Dorrestein Lab - University of California San Diego - https://dorresteinlab.ucsd.edu/$
// $Authors: Abinesh Sarvepalli and Louis Felix Nothias$
// $Contributors: Fabian Aicheler and Oliver Alka from Oliver Kohlbacher's group at Tubingen University$
// --------------------------------------------------------------------------
//
#include <OpenMS/FORMAT/GNPSMGFFile.h>
#include <OpenMS/COMPARISON/BinnedSpectralContrastAngle.h>
#include <OpenMS/CONCEPT/UniqueIdInterface.h>
#include <OpenMS/PROCESSING/SPECTRAMERGING/SpectraMerger.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/KERNEL/OnDiscMSExperiment.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <iostream>
#include <fstream>
using namespace std;
namespace OpenMS
{
GNPSMGFFile::GNPSMGFFile() :
DefaultParamHandler("GNPSMGFFile"),
ProgressLogger()
{
defaults_.setValue("output_type", "most_intense", "specificity of mgf output information");
defaults_.setValidStrings("output_type", {"merged_spectra","most_intense"});
defaults_.setValue("peptide_cutoff", DEF_PEPT_CUTOFF, "Number of most intense peptides to consider per consensus element; '-1' to consider all identifications.");
defaults_.setMinInt("peptide_cutoff", -1);
defaults_.setValue("ms2_bin_size", DEF_MERGE_BIN_SIZE, "Bin size (Da) for fragment ions when merging ms2 scans.");
defaults_.setMinFloat("ms2_bin_size", 0);
defaults_.setValue("merged_spectra:cos_similarity", DEF_COSINE_SIMILARITY, "Cosine similarity threshold for merged_spectra output.");
defaults_.setMinFloat("merged_spectra:cos_similarity", 0);
defaults_.setSectionDescription("merged_spectra", "Options for exporting mgf file with merged spectra per consensusElement");
defaultsToParam_(); // copy defaults into param_
}
/**
* @brief Bin peaks by similar m/z position and averaged intensities
* @param[in] peaks Vector of Peak1D peaks sorted by m/z position
* @param[in] bin_width Size of bin
* @param[out] binned_peaks Result vector with binned peaks passed in by reference
*/
void binPeaks_(
const vector<Peak1D> &peaks,
const double bin_width,
vector<Peak1D> &binned_peaks
)
{
double last_mz = peaks.at(0).getMZ();
double sum_mz{};
double sum_intensity{};
int count{};
for (auto& spec : peaks)
{
if (count > 0 && spec.getMZ() - last_mz > bin_width)
{
if (sum_intensity > 0)
{
Peak1D curr(sum_mz/count, sum_intensity/count);
binned_peaks.push_back(curr);
}
last_mz = spec.getMZ();
sum_mz = 0;
sum_intensity = 0;
count = 0;
}
sum_mz += spec.getMZ();
sum_intensity += spec.getIntensity();
count += 1;
}
if (count > 0)
{
Peak1D curr(sum_mz/count, sum_intensity/count);
binned_peaks.push_back(curr);
}
}
/**
* @brief Flatten spectra from MSExperiment into a single vector of Peak1D peaks
* @param[in] exp MSExperiment containing at least 1 spectrum
* @param[in] bin_width Size of binned scan (m/z)
* @param[out] merged_peaks Result vector of peaks passed in by reference
*/
void flattenAndBinSpectra_(
MSExperiment &exp,
const double bin_width,
vector<Peak1D> &merged_peaks
)
{
// flatten spectra
vector<Peak1D> flat_spectra;
for (auto& spec : exp.getSpectra())
{
for (auto& peak : spec)
{
flat_spectra.push_back(peak);
}
}
sort(flat_spectra.begin(), flat_spectra.end(), [](const Peak1D &a, const Peak1D &b)
{
return a.getMZ() < b.getMZ();
}
);
// bin peaks
binPeaks_(flat_spectra, bin_width, merged_peaks);
// return value is modified merged_peaks passed by reference
}
/**
* @brief Private function that outputs MS/MS Block Header
* @param[in] output_file Stream that will write to file
* @param[out] scan_index Current scan index in GNPSExport formatted output
* @param[in] feature_id ConsensusFeature Id found in input mzXML file
* @param[in] feature_charge ConsensusFeature's highest charge as mentioned in the input mzXML file
* @param[in] feature_mz m/z position of PeptideIdentification with highest intensity
* @param[in] spec_index Spectrum index of PeptideIdentification with highest intensity
* @param[in] feature_rt ConsensusFeature's retention time specified in input mzXML file
*/
void writeMSMSBlockHeader_(
ofstream &output_file,
const String &output_type,
const int &scan_index,
const String &feature_id,
const int &feature_charge,
const String &feature_mz,
const String &spec_index,
const String &feature_rt
)
{
if (output_file.is_open())
{
output_file << "BEGIN IONS" << "\n"
<< "OUTPUT=" << output_type << "\n"
<< "SCANS=" << scan_index << "\n"
<< "FEATURE_ID=e_" << feature_id << "\n"
<< "MSLEVEL=2" << "\n"
<< "CHARGE=" << to_string(feature_charge == 0 ? 1 : abs(feature_charge))+(feature_charge >= 0 ? "+" : "-") << "\n"
<< "PEPMASS=" << feature_mz << "\n"
<< "FILE_INDEX=" << spec_index << "\n"
<< "RTINSECONDS=" << feature_rt << "\n";
}
}
/**
* @brief Private function to write peak mass and intensity to output file
* @param[in] output_file Stream that will write to file
* @param[out] peaks Vector of peaks that will be outputted
*/
void writeMSMSBlock_(
ofstream &output_file,
const vector<Peak1D> &peaks
)
{
if (output_file.is_open())
{
output_file << setprecision(4) << fixed;
for (auto& peak : peaks)
{
output_file << peak.getMZ() << "\t" << peak.getIntensity() << "\n";
}
output_file << "END IONS" << "\n" << endl;
}
}
/**
* @brief Private method used to sort PeptideIdentification map indices in order of annotation's intensity
* @param[in] feature ConsensusFeature annotated with PeptideIdentifications
* @param[out] featureMaps_sortedByInt Result vector of map indices in order of PeptideIdentification intensity
*/
void sortElementMapsByIntensity_(const ConsensusFeature& feature, vector<pair<int,double>>& element_maps)
{
// convert element maps to vector of pair<int,double>(map, intensity)
for (const auto& feature_handle : feature)
{
element_maps.emplace_back(feature_handle.getMapIndex(), feature_handle.getIntensity());
}
// sort elements by intensity
sort(element_maps.begin(), element_maps.end(), [](const pair<int,double> &a, const pair<int,double> &b)
{
return a.second > b.second;
});
// return value will be reformatted vector<int> element_maps passed in by value
}
/**
* @brief Retrieve list of PeptideIdentification parameters from ConsensusFeature metadata, sorted by map intensity
* @param[in] feature ConsensusFeature feature containing PeptideIdentification annotations
* @param[in] sorted_element_maps Sorted list of element_maps
* @param[out] pepts Result vector of <map_index,spectrum_index> of PeptideIdentification annotations sorted by map intensity in feature
*/
void getElementPeptideIdentificationsByElementIntensity_(
const ConsensusFeature& feature,
vector<pair<int,double>>& sorted_element_maps,
vector<pair<int,int>>& pepts
)
{
for (pair<int,double>& element_pair : sorted_element_maps)
{
int element_map = element_pair.first;
PeptideIdentificationList feature_pepts = feature.getPeptideIdentifications();
for (PeptideIdentification& pept_id : feature_pepts)
{
if (pept_id.metaValueExists("spectrum_index") && pept_id.metaValueExists("map_index")
&& (int)pept_id.getMetaValue("map_index") == element_map)
{
int map_index = pept_id.getMetaValue("map_index");
int spec_index = pept_id.getMetaValue("spectrum_index");
pepts.emplace_back(map_index,spec_index);
break;
}
}
}
// return will be reformatted PeptideIdentificationList pepts passed in by value
}
void GNPSMGFFile::store(const String& consensus_file_path, const StringList& mzml_file_paths, const String& out) const
{
std::string output_type = getParameters().getValue("output_type");
double bin_width = getParameters().getValue("ms2_bin_size");
int pept_cutoff((output_type == "merged_spectra") ? (int)getParameters().getValue("peptide_cutoff") : 1);
double cos_sim_threshold = getParameters().getValue("merged_spectra:cos_similarity");
ofstream output_file(out);
//-------------------------------------------------------------
// reading input
//-------------------------------------------------------------
// ConsensusMap
ConsensusMap consensus_map;
FileHandler().loadConsensusFeatures(consensus_file_path, consensus_map, {FileTypes::CONSENSUSXML});
//-------------------------------------------------------------
// open on-disc data (=spectra are only loaded on demand to safe memory)
//-------------------------------------------------------------
vector<OnDiscMSExperiment> specs_list(mzml_file_paths.size(), OnDiscMSExperiment());
map<size_t, size_t> map_index2file_index; // <K, V> = <map_index, file_index>
Size num_msmaps_cached = 0;
//-------------------------------------------------------------
// write output (+ merge computations)
//-------------------------------------------------------------
startProgress(0, consensus_map.size(), "parsing features and ms2 identifications...");
for (Size cons_i = 0; cons_i < consensus_map.size(); ++cons_i)
{
setProgress(cons_i);
const ConsensusFeature& feature = consensus_map[cons_i];
// determine feature's charge as maximum feature handle charge
int charge = feature.getCharge();
for (auto& fh : feature)
{
if (fh.getCharge() > charge)
{
charge = fh.getCharge();
}
}
// compute most intense peptide identifications (based on precursor intensity)
vector<pair<int,double>> element_maps;
sortElementMapsByIntensity_(feature, element_maps);
vector<pair<int, int>> pepts;
getElementPeptideIdentificationsByElementIntensity_(feature, element_maps, pepts);
// discard poorer precursor spectra for 'merged_spectra' and 'full_spectra' output
if (pept_cutoff != -1 && pepts.size() > (unsigned long) pept_cutoff)
{
pepts.erase(pepts.begin()+pept_cutoff, pepts.end());
}
// validate all peptide annotation maps have been loaded
for (const auto& pep : pepts)
{
int map_index = pep.first;
// open on-disc experiments
if (map_index2file_index.find(map_index) == map_index2file_index.end())
{
specs_list[num_msmaps_cached].openFile(mzml_file_paths[map_index], false); // open on-disc experiment and load meta-data
map_index2file_index[map_index] = num_msmaps_cached;
++num_msmaps_cached;
}
}
// identify most intense spectrum
const int best_mapi = pepts[0].first;
const int best_speci = pepts[0].second;
auto best_spec = specs_list[map_index2file_index[best_mapi]][best_speci];
if (best_spec.empty()) continue; // some Bruker files have MS2 spectra without peaks. skip those during exprot
// write block output header
writeMSMSBlockHeader_(
output_file,
output_type,
(cons_i + 1),
feature.getUniqueId(),
charge,
feature.getMZ(),
best_speci,
best_spec.getRT()
);
// OPENMS_LOG_DEBUG << "Best spectrum (index/RT): " << best_speci << "\t" << best_spec.getRT() << std::endl;
// store outputted spectra in MSExperiment
MSExperiment exp;
// add most intense spectrum to MSExperiment
exp.addSpectrum(best_spec);
if (output_type == "merged_spectra")
{
// merge spectra that meet cosine similarity threshold to most intense spectrum
BinnedSpectrum binned_highest_int(best_spec, bin_width, false, 1, BinnedSpectrum::DEFAULT_BIN_OFFSET_HIRES);
// Retain peptide annotations that do not meet user-specified cosine similarity threshold
for (pair<int,int> &pept : pepts)
{
int map_index = pept.first;
int spec_index = pept.second;
auto test_spec = specs_list[map_index2file_index[map_index]][spec_index];
BinnedSpectrum binned_spectrum(test_spec, bin_width, false, 1, BinnedSpectrum::DEFAULT_BIN_OFFSET_HIRES);
BinnedSpectralContrastAngle bsca;
double cos_sim = bsca(binned_highest_int, binned_spectrum);
if (cos_sim >= cos_sim_threshold)
{
exp.addSpectrum(test_spec);
}
}
}
// store outputted peaks in vector<Peak1D>
vector<Peak1D> peaks;
flattenAndBinSpectra_(
exp,
bin_width,
peaks
);
// write peaks to output block
writeMSMSBlock_(
output_file,
peaks
);
}
output_file.close();
}
}
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.